blob: 01c77966244b4fad44403ed4993c8bdbf3365ae6 [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);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000608 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000609 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
610 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000611 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000612 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000613 }
614
Sebastian Redlcd965b92009-01-18 18:53:16 +0000615 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616}
617
John McCall129e2df2009-11-30 22:42:35 +0000618/// Decomposes the given name into a DeclarationName, its location, and
619/// possibly a list of template arguments.
620///
621/// If this produces template arguments, it is permitted to call
622/// DecomposeTemplateName.
623///
624/// This actually loses a lot of source location information for
625/// non-standard name kinds; we should consider preserving that in
626/// some way.
627static void DecomposeUnqualifiedId(Sema &SemaRef,
628 const UnqualifiedId &Id,
629 TemplateArgumentListInfo &Buffer,
630 DeclarationName &Name,
631 SourceLocation &NameLoc,
632 const TemplateArgumentListInfo *&TemplateArgs) {
633 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
634 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
635 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
636
637 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
638 Id.TemplateId->getTemplateArgs(),
639 Id.TemplateId->NumArgs);
640 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
641 TemplateArgsPtr.release();
642
643 TemplateName TName =
644 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
645
646 Name = SemaRef.Context.getNameForTemplate(TName);
647 NameLoc = Id.TemplateId->TemplateNameLoc;
648 TemplateArgs = &Buffer;
649 } else {
650 Name = SemaRef.GetNameFromUnqualifiedId(Id);
651 NameLoc = Id.StartLocation;
652 TemplateArgs = 0;
653 }
654}
655
656/// Decompose the given template name into a list of lookup results.
657///
658/// The unqualified ID must name a non-dependent template, which can
659/// be more easily tested by checking whether DecomposeUnqualifiedId
660/// found template arguments.
661static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
662 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
663 TemplateName TName =
664 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
665
John McCallf7a1a742009-11-24 19:00:30 +0000666 if (TemplateDecl *TD = TName.getAsTemplateDecl())
667 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000668 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
669 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
670 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000671 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000672
John McCallf7a1a742009-11-24 19:00:30 +0000673 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000674}
675
John McCall129e2df2009-11-30 22:42:35 +0000676static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
677 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
678 E = Record->bases_end(); I != E; ++I) {
679 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
680 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
681 if (!BaseRT) return false;
682
683 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
684 if (!BaseRecord->isDefinition() ||
685 !IsFullyFormedScope(SemaRef, BaseRecord))
686 return false;
687 }
688
689 return true;
690}
691
John McCalle1599ce2009-11-30 23:50:49 +0000692/// Determines whether we can lookup this id-expression now or whether
693/// we have to wait until template instantiation is complete.
694static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000695 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000696
John McCalle1599ce2009-11-30 23:50:49 +0000697 // If the qualifier scope isn't computable, it's definitely dependent.
698 if (!DC) return true;
699
700 // If the qualifier scope doesn't name a record, we can always look into it.
701 if (!isa<CXXRecordDecl>(DC)) return false;
702
703 // We can't look into record types unless they're fully-formed.
704 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
705
John McCallaa81e162009-12-01 22:10:20 +0000706 return false;
707}
John McCalle1599ce2009-11-30 23:50:49 +0000708
John McCallaa81e162009-12-01 22:10:20 +0000709/// Determines if the given class is provably not derived from all of
710/// the prospective base classes.
711static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
712 CXXRecordDecl *Record,
713 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000714 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000715 return false;
716
John McCallb1b42562009-12-01 22:28:41 +0000717 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
718 if (!RD) return false;
719 Record = cast<CXXRecordDecl>(RD);
720
John McCallaa81e162009-12-01 22:10:20 +0000721 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
722 E = Record->bases_end(); I != E; ++I) {
723 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
724 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
725 if (!BaseRT) return false;
726
727 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000728 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
729 return false;
730 }
731
732 return true;
733}
734
735static bool IsInstanceMember(NamedDecl *D) {
736 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
737 "checking whether non-member is instance member");
738
739 if (isa<FieldDecl>(D)) return true;
740
741 if (isa<CXXMethodDecl>(D))
742 return !cast<CXXMethodDecl>(D)->isStatic();
743
744 if (isa<FunctionTemplateDecl>(D)) {
745 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
746 return !cast<CXXMethodDecl>(D)->isStatic();
747 }
748
749 return false;
750}
751
752enum IMAKind {
753 /// The reference is definitely not an instance member access.
754 IMA_Static,
755
756 /// The reference may be an implicit instance member access.
757 IMA_Mixed,
758
759 /// The reference may be to an instance member, but it is invalid if
760 /// so, because the context is not an instance method.
761 IMA_Mixed_StaticContext,
762
763 /// The reference may be to an instance member, but it is invalid if
764 /// so, because the context is from an unrelated class.
765 IMA_Mixed_Unrelated,
766
767 /// The reference is definitely an implicit instance member access.
768 IMA_Instance,
769
770 /// The reference may be to an unresolved using declaration.
771 IMA_Unresolved,
772
773 /// The reference may be to an unresolved using declaration and the
774 /// context is not an instance method.
775 IMA_Unresolved_StaticContext,
776
777 /// The reference is to a member of an anonymous structure in a
778 /// non-class context.
779 IMA_AnonymousMember,
780
781 /// All possible referrents are instance members and the current
782 /// context is not an instance method.
783 IMA_Error_StaticContext,
784
785 /// All possible referrents are instance members of an unrelated
786 /// class.
787 IMA_Error_Unrelated
788};
789
790/// The given lookup names class member(s) and is not being used for
791/// an address-of-member expression. Classify the type of access
792/// according to whether it's possible that this reference names an
793/// instance member. This is best-effort; it is okay to
794/// conservatively answer "yes", in which case some errors will simply
795/// not be caught until template-instantiation.
796static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
797 const LookupResult &R) {
798 assert(!R.empty() && isa<CXXRecordDecl>((*R.begin())->getDeclContext()));
799
800 bool isStaticContext =
801 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
802 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
803
804 if (R.isUnresolvableResult())
805 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
806
807 // Collect all the declaring classes of instance members we find.
808 bool hasNonInstance = false;
809 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
810 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
811 NamedDecl *D = (*I)->getUnderlyingDecl();
812 if (IsInstanceMember(D)) {
813 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
814
815 // If this is a member of an anonymous record, move out to the
816 // innermost non-anonymous struct or union. If there isn't one,
817 // that's a special case.
818 while (R->isAnonymousStructOrUnion()) {
819 R = dyn_cast<CXXRecordDecl>(R->getParent());
820 if (!R) return IMA_AnonymousMember;
821 }
822 Classes.insert(R->getCanonicalDecl());
823 }
824 else
825 hasNonInstance = true;
826 }
827
828 // If we didn't find any instance members, it can't be an implicit
829 // member reference.
830 if (Classes.empty())
831 return IMA_Static;
832
833 // If the current context is not an instance method, it can't be
834 // an implicit member reference.
835 if (isStaticContext)
836 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
837
838 // If we can prove that the current context is unrelated to all the
839 // declaring classes, it can't be an implicit member reference (in
840 // which case it's an error if any of those members are selected).
841 if (IsProvablyNotDerivedFrom(SemaRef,
842 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
843 Classes))
844 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
845
846 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
847}
848
849/// Diagnose a reference to a field with no object available.
850static void DiagnoseInstanceReference(Sema &SemaRef,
851 const CXXScopeSpec &SS,
852 const LookupResult &R) {
853 SourceLocation Loc = R.getNameLoc();
854 SourceRange Range(Loc);
855 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
856
857 if (R.getAsSingle<FieldDecl>()) {
858 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
859 if (MD->isStatic()) {
860 // "invalid use of member 'x' in static member function"
861 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
862 << Range << R.getLookupName();
863 return;
864 }
865 }
866
867 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
868 << R.getLookupName() << Range;
869 return;
870 }
871
872 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000873}
874
John McCallf7a1a742009-11-24 19:00:30 +0000875Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
876 const CXXScopeSpec &SS,
877 UnqualifiedId &Id,
878 bool HasTrailingLParen,
879 bool isAddressOfOperand) {
880 assert(!(isAddressOfOperand && HasTrailingLParen) &&
881 "cannot be direct & operand and have a trailing lparen");
882
883 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000884 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000885
John McCall129e2df2009-11-30 22:42:35 +0000886 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000887
888 // Decompose the UnqualifiedId into the following data.
889 DeclarationName Name;
890 SourceLocation NameLoc;
891 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000892 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
893 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000894
Douglas Gregor10c42622008-11-18 15:03:34 +0000895 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000896
John McCallf7a1a742009-11-24 19:00:30 +0000897 // C++ [temp.dep.expr]p3:
898 // An id-expression is type-dependent if it contains:
899 // -- a nested-name-specifier that contains a class-name that
900 // names a dependent type.
901 // Determine whether this is a member of an unknown specialization;
902 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000903 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000904 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000905 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000906 TemplateArgs);
907 }
John McCallba135432009-11-21 08:51:07 +0000908
John McCallf7a1a742009-11-24 19:00:30 +0000909 // Perform the required lookup.
910 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
911 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +0000912 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +0000913 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +0000914 } else {
915 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000916
John McCallf7a1a742009-11-24 19:00:30 +0000917 // If this reference is in an Objective-C method, then we need to do
918 // some special Objective-C lookup, too.
919 if (!SS.isSet() && II && getCurMethodDecl()) {
920 OwningExprResult E(LookupInObjCMethod(R, S, II));
921 if (E.isInvalid())
922 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000923
John McCallf7a1a742009-11-24 19:00:30 +0000924 Expr *Ex = E.takeAs<Expr>();
925 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000926 }
Chris Lattner8a934232008-03-31 00:36:02 +0000927 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000928
John McCallf7a1a742009-11-24 19:00:30 +0000929 if (R.isAmbiguous())
930 return ExprError();
931
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000932 // Determine whether this name might be a candidate for
933 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000934 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000935
John McCallf7a1a742009-11-24 19:00:30 +0000936 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000938 // in C90, extension in C99, forbidden in C++).
939 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
940 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
941 if (D) R.addDecl(D);
942 }
943
944 // If this name wasn't predeclared and if this is not a function
945 // call, diagnose the problem.
946 if (R.empty()) {
947 if (!SS.isEmpty())
948 return ExprError(Diag(NameLoc, diag::err_no_member)
949 << Name << computeDeclContext(SS, false)
950 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000951 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Sean Hunt3e518bd2009-11-29 07:34:05 +0000952 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000953 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000954 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
955 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000956 else
John McCallf7a1a742009-11-24 19:00:30 +0000957 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 }
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
John McCallf7a1a742009-11-24 19:00:30 +0000961 // This is guaranteed from this point on.
962 assert(!R.empty() || ADL);
963
964 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000965 // Warn about constructs like:
966 // if (void *X = foo()) { ... } else { X }.
967 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Douglas Gregor751f9a42009-06-30 15:47:41 +0000969 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
970 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000971 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000972 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000973 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +0000974 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000975 << Var->getDeclName()
976 << (Var->getType()->isPointerType()? 2 :
977 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000978 break;
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000981 // Move to the parent of this scope.
982 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000983 }
984 }
John McCallf7a1a742009-11-24 19:00:30 +0000985 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000986 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
987 // C99 DR 316 says that, if a function type comes from a
988 // function definition (without a prototype), that type is only
989 // used for checking compatibility. Therefore, when referencing
990 // the function, we pretend that we don't have the full function
991 // type.
John McCallf7a1a742009-11-24 19:00:30 +0000992 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +0000993 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000994
Douglas Gregor751f9a42009-06-30 15:47:41 +0000995 QualType T = Func->getType();
996 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000997 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000998 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +0000999 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001000 }
1001 }
Mike Stump1eb44332009-09-09 15:08:12 +00001002
John McCallaa81e162009-12-01 22:10:20 +00001003 // Check whether this might be a C++ implicit instance member access.
1004 // C++ [expr.prim.general]p6:
1005 // Within the definition of a non-static member function, an
1006 // identifier that names a non-static member is transformed to a
1007 // class member access expression.
1008 // But note that &SomeClass::foo is grammatically distinct, even
1009 // though we don't parse it that way.
1010 if (!R.empty() && (*R.begin())->getDeclContext()->isRecord()) {
John McCallf7a1a742009-11-24 19:00:30 +00001011 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +00001012
John McCallaa81e162009-12-01 22:10:20 +00001013 if (!isAbstractMemberPointer) {
1014 switch (ClassifyImplicitMemberAccess(*this, R)) {
1015 case IMA_Instance:
1016 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1017
1018 case IMA_AnonymousMember:
1019 assert(R.isSingleResult());
1020 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1021 R.getAsSingle<FieldDecl>());
1022
1023 case IMA_Mixed:
1024 case IMA_Mixed_Unrelated:
1025 case IMA_Unresolved:
1026 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1027
1028 case IMA_Static:
1029 case IMA_Mixed_StaticContext:
1030 case IMA_Unresolved_StaticContext:
1031 break;
1032
1033 case IMA_Error_StaticContext:
1034 case IMA_Error_Unrelated:
1035 DiagnoseInstanceReference(*this, SS, R);
1036 return ExprError();
1037 }
John McCall5b3f9132009-11-22 01:44:31 +00001038 }
1039 }
1040
John McCallf7a1a742009-11-24 19:00:30 +00001041 if (TemplateArgs)
1042 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001043
John McCallf7a1a742009-11-24 19:00:30 +00001044 return BuildDeclarationNameExpr(SS, R, ADL);
1045}
1046
John McCall129e2df2009-11-30 22:42:35 +00001047/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1048/// declaration name, generally during template instantiation.
1049/// There's a large number of things which don't need to be done along
1050/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001051Sema::OwningExprResult
1052Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1053 DeclarationName Name,
1054 SourceLocation NameLoc) {
1055 DeclContext *DC;
1056 if (!(DC = computeDeclContext(SS, false)) ||
1057 DC->isDependentContext() ||
1058 RequireCompleteDeclContext(SS))
1059 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1060
1061 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1062 LookupQualifiedName(R, DC);
1063
1064 if (R.isAmbiguous())
1065 return ExprError();
1066
1067 if (R.empty()) {
1068 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1069 return ExprError();
1070 }
1071
1072 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1073}
1074
1075/// LookupInObjCMethod - The parser has read a name in, and Sema has
1076/// detected that we're currently inside an ObjC method. Perform some
1077/// additional lookup.
1078///
1079/// Ideally, most of this would be done by lookup, but there's
1080/// actually quite a lot of extra work involved.
1081///
1082/// Returns a null sentinel to indicate trivial success.
1083Sema::OwningExprResult
1084Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1085 IdentifierInfo *II) {
1086 SourceLocation Loc = Lookup.getNameLoc();
1087
1088 // There are two cases to handle here. 1) scoped lookup could have failed,
1089 // in which case we should look for an ivar. 2) scoped lookup could have
1090 // found a decl, but that decl is outside the current instance method (i.e.
1091 // a global variable). In these two cases, we do a lookup for an ivar with
1092 // this name, if the lookup sucedes, we replace it our current decl.
1093
1094 // If we're in a class method, we don't normally want to look for
1095 // ivars. But if we don't find anything else, and there's an
1096 // ivar, that's an error.
1097 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1098
1099 bool LookForIvars;
1100 if (Lookup.empty())
1101 LookForIvars = true;
1102 else if (IsClassMethod)
1103 LookForIvars = false;
1104 else
1105 LookForIvars = (Lookup.isSingleResult() &&
1106 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1107
1108 if (LookForIvars) {
1109 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1110 ObjCInterfaceDecl *ClassDeclared;
1111 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1112 // Diagnose using an ivar in a class method.
1113 if (IsClassMethod)
1114 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1115 << IV->getDeclName());
1116
1117 // If we're referencing an invalid decl, just return this as a silent
1118 // error node. The error diagnostic was already emitted on the decl.
1119 if (IV->isInvalidDecl())
1120 return ExprError();
1121
1122 // Check if referencing a field with __attribute__((deprecated)).
1123 if (DiagnoseUseOfDecl(IV, Loc))
1124 return ExprError();
1125
1126 // Diagnose the use of an ivar outside of the declaring class.
1127 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1128 ClassDeclared != IFace)
1129 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1130
1131 // FIXME: This should use a new expr for a direct reference, don't
1132 // turn this into Self->ivar, just return a BareIVarExpr or something.
1133 IdentifierInfo &II = Context.Idents.get("self");
1134 UnqualifiedId SelfName;
1135 SelfName.setIdentifier(&II, SourceLocation());
1136 CXXScopeSpec SelfScopeSpec;
1137 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1138 SelfName, false, false);
1139 MarkDeclarationReferenced(Loc, IV);
1140 return Owned(new (Context)
1141 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1142 SelfExpr.takeAs<Expr>(), true, true));
1143 }
1144 } else if (getCurMethodDecl()->isInstanceMethod()) {
1145 // We should warn if a local variable hides an ivar.
1146 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1147 ObjCInterfaceDecl *ClassDeclared;
1148 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1149 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1150 IFace == ClassDeclared)
1151 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1152 }
1153 }
1154
1155 // Needed to implement property "super.method" notation.
1156 if (Lookup.empty() && II->isStr("super")) {
1157 QualType T;
1158
1159 if (getCurMethodDecl()->isInstanceMethod())
1160 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1161 getCurMethodDecl()->getClassInterface()));
1162 else
1163 T = Context.getObjCClassType();
1164 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1165 }
1166
1167 // Sentinel value saying that we didn't do anything special.
1168 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001169}
John McCallba135432009-11-21 08:51:07 +00001170
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001171/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001172bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001173Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1174 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001175 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001176 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001177 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001178 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001179 if (DestType->isDependentType() || From->getType()->isDependentType())
1180 return false;
1181 QualType FromRecordType = From->getType();
1182 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001183 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001184 DestType = Context.getPointerType(DestType);
1185 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001186 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001187 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1188 CheckDerivedToBaseConversion(FromRecordType,
1189 DestRecordType,
1190 From->getSourceRange().getBegin(),
1191 From->getSourceRange()))
1192 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001193 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1194 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001195 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001196 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001197}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001198
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001199/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001200static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
John McCall129e2df2009-11-30 22:42:35 +00001201 const CXXScopeSpec &SS, NamedDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001202 SourceLocation Loc, QualType Ty,
1203 const TemplateArgumentListInfo *TemplateArgs = 0) {
1204 NestedNameSpecifier *Qualifier = 0;
1205 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001206 if (SS.isSet()) {
1207 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1208 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
John McCallf7a1a742009-11-24 19:00:30 +00001211 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1212 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001213}
1214
John McCallaa81e162009-12-01 22:10:20 +00001215/// Builds an implicit member access expression. The current context
1216/// is known to be an instance method, and the given unqualified lookup
1217/// set is known to contain only instance members, at least one of which
1218/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001219Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001220Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1221 LookupResult &R,
1222 const TemplateArgumentListInfo *TemplateArgs,
1223 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001224 assert(!R.empty() && !R.isAmbiguous());
1225
John McCallba135432009-11-21 08:51:07 +00001226 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001227
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001228 // We may have found a field within an anonymous union or struct
1229 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001230 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001231 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001232 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001233 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001234 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001235
John McCallaa81e162009-12-01 22:10:20 +00001236 // If this is known to be an instance access, go ahead and build a
1237 // 'this' expression now.
1238 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1239 Expr *This = 0; // null signifies implicit access
1240 if (IsKnownInstance) {
1241 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001242 }
1243
John McCallaa81e162009-12-01 22:10:20 +00001244 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1245 /*OpLoc*/ SourceLocation(),
1246 /*IsArrow*/ true,
1247 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001248}
1249
John McCallf7a1a742009-11-24 19:00:30 +00001250bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001251 const LookupResult &R,
1252 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001253 // Only when used directly as the postfix-expression of a call.
1254 if (!HasTrailingLParen)
1255 return false;
1256
1257 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001258 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001259 return false;
1260
1261 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001262 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001263 return false;
1264
1265 // Turn off ADL when we find certain kinds of declarations during
1266 // normal lookup:
1267 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1268 NamedDecl *D = *I;
1269
1270 // C++0x [basic.lookup.argdep]p3:
1271 // -- a declaration of a class member
1272 // Since using decls preserve this property, we check this on the
1273 // original decl.
1274 if (D->getDeclContext()->isRecord())
1275 return false;
1276
1277 // C++0x [basic.lookup.argdep]p3:
1278 // -- a block-scope function declaration that is not a
1279 // using-declaration
1280 // NOTE: we also trigger this for function templates (in fact, we
1281 // don't check the decl type at all, since all other decl types
1282 // turn off ADL anyway).
1283 if (isa<UsingShadowDecl>(D))
1284 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1285 else if (D->getDeclContext()->isFunctionOrMethod())
1286 return false;
1287
1288 // C++0x [basic.lookup.argdep]p3:
1289 // -- a declaration that is neither a function or a function
1290 // template
1291 // And also for builtin functions.
1292 if (isa<FunctionDecl>(D)) {
1293 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1294
1295 // But also builtin functions.
1296 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1297 return false;
1298 } else if (!isa<FunctionTemplateDecl>(D))
1299 return false;
1300 }
1301
1302 return true;
1303}
1304
1305
John McCallba135432009-11-21 08:51:07 +00001306/// Diagnoses obvious problems with the use of the given declaration
1307/// as an expression. This is only actually called for lookups that
1308/// were not overloaded, and it doesn't promise that the declaration
1309/// will in fact be used.
1310static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1311 if (isa<TypedefDecl>(D)) {
1312 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1313 return true;
1314 }
1315
1316 if (isa<ObjCInterfaceDecl>(D)) {
1317 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1318 return true;
1319 }
1320
1321 if (isa<NamespaceDecl>(D)) {
1322 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1323 return true;
1324 }
1325
1326 return false;
1327}
1328
1329Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001330Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001331 LookupResult &R,
1332 bool NeedsADL) {
John McCallf7a1a742009-11-24 19:00:30 +00001333 // If this isn't an overloaded result and we don't need ADL, just
1334 // build an ordinary singleton decl ref.
John McCall5b3f9132009-11-22 01:44:31 +00001335 if (!NeedsADL && !R.isOverloadedResult())
1336 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001337
1338 // We only need to check the declaration if there's exactly one
1339 // result, because in the overloaded case the results can only be
1340 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001341 if (R.isSingleResult() &&
1342 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001343 return ExprError();
1344
John McCallf7a1a742009-11-24 19:00:30 +00001345 bool Dependent
1346 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001347 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001348 = UnresolvedLookupExpr::Create(Context, Dependent,
1349 (NestedNameSpecifier*) SS.getScopeRep(),
1350 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001351 R.getLookupName(), R.getNameLoc(),
1352 NeedsADL, R.isOverloadedResult());
1353 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1354 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001355
1356 return Owned(ULE);
1357}
1358
1359
1360/// \brief Complete semantic analysis for a reference to the given declaration.
1361Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001362Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001363 SourceLocation Loc, NamedDecl *D) {
1364 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001365 assert(!isa<FunctionTemplateDecl>(D) &&
1366 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001367 DeclarationName Name = D->getDeclName();
1368
1369 if (CheckDeclInExpr(*this, Loc, D))
1370 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001371
Douglas Gregor9af2f522009-12-01 16:58:18 +00001372 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1373 // Specifically diagnose references to class templates that are missing
1374 // a template argument list.
1375 Diag(Loc, diag::err_template_decl_ref)
1376 << Template << SS.getRange();
1377 Diag(Template->getLocation(), diag::note_template_decl_here);
1378 return ExprError();
1379 }
1380
1381 // Make sure that we're referring to a value.
1382 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1383 if (!VD) {
1384 Diag(Loc, diag::err_ref_non_value)
1385 << D << SS.getRange();
1386 Diag(D->getLocation(), diag::note_previous_decl);
1387 return ExprError();
1388 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001389
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001390 // Check whether this declaration can be used. Note that we suppress
1391 // this check when we're going to perform argument-dependent lookup
1392 // on this function name, because this might not be the function
1393 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001394 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001395 return ExprError();
1396
Steve Naroffdd972f22008-09-05 22:11:13 +00001397 // Only create DeclRefExpr's for valid Decl's.
1398 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001399 return ExprError();
1400
Chris Lattner639e2d32008-10-20 05:16:36 +00001401 // If the identifier reference is inside a block, and it refers to a value
1402 // that is outside the block, create a BlockDeclRefExpr instead of a
1403 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1404 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001405 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001406 // We do not do this for things like enum constants, global variables, etc,
1407 // as they do not get snapshotted.
1408 //
1409 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001410 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001411 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001412 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001413 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001414 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001415 // This is to record that a 'const' was actually synthesize and added.
1416 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001417 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Eli Friedman5fdeae12009-03-22 23:00:19 +00001419 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001420 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001421 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001422 }
1423 // If this reference is not in a block or if the referenced variable is
1424 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001425
John McCallf7a1a742009-11-24 19:00:30 +00001426 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001427}
1428
Sebastian Redlcd965b92009-01-18 18:53:16 +00001429Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1430 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001431 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001434 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001435 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1436 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1437 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001439
Chris Lattnerfa28b302008-01-12 08:14:25 +00001440 // Pre-defined identifiers are of type char[x], where x is the length of the
1441 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Anders Carlsson3a082d82009-09-08 18:24:21 +00001443 Decl *currentDecl = getCurFunctionOrMethodDecl();
1444 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001445 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001446 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001447 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001448
Anders Carlsson773f3972009-09-11 01:22:35 +00001449 QualType ResTy;
1450 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1451 ResTy = Context.DependentTy;
1452 } else {
1453 unsigned Length =
1454 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001455
Anders Carlsson773f3972009-09-11 01:22:35 +00001456 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001457 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001458 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1459 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001460 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001461}
1462
Sebastian Redlcd965b92009-01-18 18:53:16 +00001463Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 llvm::SmallString<16> CharBuffer;
1465 CharBuffer.resize(Tok.getLength());
1466 const char *ThisTokBegin = &CharBuffer[0];
1467 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001468
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1470 Tok.getLocation(), PP);
1471 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001472 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001473
1474 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1475
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001476 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1477 Literal.isWide(),
1478 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001479}
1480
Sebastian Redlcd965b92009-01-18 18:53:16 +00001481Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1482 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1484 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001485 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001486 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001487 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001488 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 }
Ted Kremenek28396602009-01-13 23:19:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001492 // Add padding so that NumericLiteralParser can overread by one character.
1493 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001495
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 // Get the spelling of the token, which eliminates trigraphs, etc.
1497 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001498
Mike Stump1eb44332009-09-09 15:08:12 +00001499 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 Tok.getLocation(), PP);
1501 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001502 return ExprError();
1503
Chris Lattner5d661452007-08-26 03:42:43 +00001504 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001505
Chris Lattner5d661452007-08-26 03:42:43 +00001506 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001507 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001508 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001509 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001510 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001511 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001512 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001513 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001514
1515 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1516
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001517 // isExact will be set by GetFloatValue().
1518 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001519 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1520 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001521
Chris Lattner5d661452007-08-26 03:42:43 +00001522 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001523 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001524 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001525 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001526
Neil Boothb9449512007-08-29 22:00:19 +00001527 // long long is a C99 feature.
1528 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001529 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001530 Diag(Tok.getLocation(), diag::ext_longlong);
1531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001533 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 if (Literal.GetIntegerValue(ResultVal)) {
1536 // If this value didn't fit into uintmax_t, warn and force to ull.
1537 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001538 Ty = Context.UnsignedLongLongTy;
1539 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001540 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 } else {
1542 // If this value fits into a ULL, try to figure out what else it fits into
1543 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1546 // be an unsigned int.
1547 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1548
1549 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001550 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001551 if (!Literal.isLong && !Literal.isLongLong) {
1552 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001553 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001554
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // Does it fit in a unsigned int?
1556 if (ResultVal.isIntN(IntSize)) {
1557 // Does it fit in a signed int?
1558 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001559 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001561 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001562 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001567 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001568 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001569
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // Does it fit in a unsigned long?
1571 if (ResultVal.isIntN(LongSize)) {
1572 // Does it fit in a signed long?
1573 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001574 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001576 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001577 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001579 }
1580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001582 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001583 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001584
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 // Does it fit in a unsigned long long?
1586 if (ResultVal.isIntN(LongLongSize)) {
1587 // Does it fit in a signed long long?
1588 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001589 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001591 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001592 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
1594 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // If we still couldn't decide a type, we probably have something that
1597 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001598 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001600 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001601 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001603
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001604 if (ResultVal.getBitWidth() != Width)
1605 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001607 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001609
Chris Lattner5d661452007-08-26 03:42:43 +00001610 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1611 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001612 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001613 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001614
1615 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001616}
1617
Sebastian Redlcd965b92009-01-18 18:53:16 +00001618Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1619 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001620 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001621 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001622 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001623}
1624
1625/// The UsualUnaryConversions() function is *not* called by this routine.
1626/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001627bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001628 SourceLocation OpLoc,
1629 const SourceRange &ExprRange,
1630 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001631 if (exprType->isDependentType())
1632 return false;
1633
Sebastian Redl5d484e82009-11-23 17:18:46 +00001634 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1635 // the result is the size of the referenced type."
1636 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1637 // result shall be the alignment of the referenced type."
1638 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1639 exprType = Ref->getPointeeType();
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001642 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001643 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001644 if (isSizeof)
1645 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1646 return false;
1647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Chris Lattner1efaa952009-04-24 00:30:45 +00001649 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001650 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001651 Diag(OpLoc, diag::ext_sizeof_void_type)
1652 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001653 return false;
1654 }
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Chris Lattner1efaa952009-04-24 00:30:45 +00001656 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001657 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001658 PDiag(diag::err_alignof_incomplete_type)
1659 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001660 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner1efaa952009-04-24 00:30:45 +00001662 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001663 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001664 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001665 << exprType << isSizeof << ExprRange;
1666 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Chris Lattner1efaa952009-04-24 00:30:45 +00001669 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001670}
1671
Chris Lattner31e21e02009-01-24 20:17:12 +00001672bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1673 const SourceRange &ExprRange) {
1674 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001675
Mike Stump1eb44332009-09-09 15:08:12 +00001676 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001677 if (isa<DeclRefExpr>(E))
1678 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001679
1680 // Cannot know anything else if the expression is dependent.
1681 if (E->isTypeDependent())
1682 return false;
1683
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001684 if (E->getBitField()) {
1685 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1686 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001687 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001688
1689 // Alignment of a field access is always okay, so long as it isn't a
1690 // bit-field.
1691 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001692 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001693 return false;
1694
Chris Lattner31e21e02009-01-24 20:17:12 +00001695 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1696}
1697
Douglas Gregorba498172009-03-13 21:01:28 +00001698/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001699Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001700Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1701 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001702 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001703 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001704 return ExprError();
1705
John McCall5ab75172009-11-04 07:28:41 +00001706 QualType T = DInfo->getType();
1707
Douglas Gregorba498172009-03-13 21:01:28 +00001708 if (!T->isDependentType() &&
1709 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1710 return ExprError();
1711
1712 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001713 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001714 Context.getSizeType(), OpLoc,
1715 R.getEnd()));
1716}
1717
1718/// \brief Build a sizeof or alignof expression given an expression
1719/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001720Action::OwningExprResult
1721Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001722 bool isSizeOf, SourceRange R) {
1723 // Verify that the operand is valid.
1724 bool isInvalid = false;
1725 if (E->isTypeDependent()) {
1726 // Delay type-checking for type-dependent expressions.
1727 } else if (!isSizeOf) {
1728 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001729 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001730 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1731 isInvalid = true;
1732 } else {
1733 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1734 }
1735
1736 if (isInvalid)
1737 return ExprError();
1738
1739 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1740 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1741 Context.getSizeType(), OpLoc,
1742 R.getEnd()));
1743}
1744
Sebastian Redl05189992008-11-11 17:56:53 +00001745/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1746/// the same for @c alignof and @c __alignof
1747/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001748Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001749Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1750 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001752 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001753
Sebastian Redl05189992008-11-11 17:56:53 +00001754 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001755 DeclaratorInfo *DInfo;
1756 (void) GetTypeFromParser(TyOrEx, &DInfo);
1757 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001758 }
Sebastian Redl05189992008-11-11 17:56:53 +00001759
Douglas Gregorba498172009-03-13 21:01:28 +00001760 Expr *ArgEx = (Expr *)TyOrEx;
1761 Action::OwningExprResult Result
1762 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1763
1764 if (Result.isInvalid())
1765 DeleteExpr(ArgEx);
1766
1767 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001768}
1769
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001770QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001771 if (V->isTypeDependent())
1772 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Chris Lattnercc26ed72007-08-26 05:39:26 +00001774 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001775 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001776 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Chris Lattnercc26ed72007-08-26 05:39:26 +00001778 // Otherwise they pass through real integer and floating point types here.
1779 if (V->getType()->isArithmeticType())
1780 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Chris Lattnercc26ed72007-08-26 05:39:26 +00001782 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001783 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1784 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001785 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001786}
1787
1788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789
Sebastian Redl0eb23302009-01-19 00:08:26 +00001790Action::OwningExprResult
1791Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1792 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 UnaryOperator::Opcode Opc;
1794 switch (Kind) {
1795 default: assert(0 && "Unknown unary op!");
1796 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1797 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1798 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001799
Eli Friedmane4216e92009-11-18 03:38:04 +00001800 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001801}
1802
Sebastian Redl0eb23302009-01-19 00:08:26 +00001803Action::OwningExprResult
1804Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1805 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001806 // Since this might be a postfix expression, get rid of ParenListExprs.
1807 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1808
Sebastian Redl0eb23302009-01-19 00:08:26 +00001809 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1810 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregor337c6b92008-11-19 17:17:41 +00001812 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001813 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1814 Base.release();
1815 Idx.release();
1816 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1817 Context.DependentTy, RLoc));
1818 }
1819
Mike Stump1eb44332009-09-09 15:08:12 +00001820 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001821 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001822 LHSExp->getType()->isEnumeralType() ||
1823 RHSExp->getType()->isRecordType() ||
1824 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001825 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001826 }
1827
Sebastian Redlf322ed62009-10-29 20:17:01 +00001828 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1829}
1830
1831
1832Action::OwningExprResult
1833Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1834 ExprArg Idx, SourceLocation RLoc) {
1835 Expr *LHSExp = static_cast<Expr*>(Base.get());
1836 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1837
Chris Lattner12d9ff62007-07-16 00:14:47 +00001838 // Perform default conversions.
1839 DefaultFunctionArrayConversion(LHSExp);
1840 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001841
Chris Lattner12d9ff62007-07-16 00:14:47 +00001842 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001843
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001845 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001846 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001848 Expr *BaseExpr, *IndexExpr;
1849 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001850 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1851 BaseExpr = LHSExp;
1852 IndexExpr = RHSExp;
1853 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001854 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001855 BaseExpr = LHSExp;
1856 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001857 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001858 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001859 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001860 BaseExpr = RHSExp;
1861 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001862 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001863 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001864 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001865 BaseExpr = LHSExp;
1866 IndexExpr = RHSExp;
1867 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001868 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001869 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001870 // Handle the uncommon case of "123[Ptr]".
1871 BaseExpr = RHSExp;
1872 IndexExpr = LHSExp;
1873 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001874 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001875 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001876 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001877
Chris Lattner12d9ff62007-07-16 00:14:47 +00001878 // FIXME: need to deal with const...
1879 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001880 } else if (LHSTy->isArrayType()) {
1881 // If we see an array that wasn't promoted by
1882 // DefaultFunctionArrayConversion, it must be an array that
1883 // wasn't promoted because of the C90 rule that doesn't
1884 // allow promoting non-lvalue arrays. Warn, then
1885 // force the promotion here.
1886 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1887 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001888 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1889 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001890 LHSTy = LHSExp->getType();
1891
1892 BaseExpr = LHSExp;
1893 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001894 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001895 } else if (RHSTy->isArrayType()) {
1896 // Same as previous, except for 123[f().a] case
1897 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1898 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001899 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1900 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001901 RHSTy = RHSExp->getType();
1902
1903 BaseExpr = RHSExp;
1904 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001905 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001907 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1908 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001909 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001911 if (!(IndexExpr->getType()->isIntegerType() &&
1912 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001913 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1914 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001915
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001916 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001917 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1918 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001919 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1920
Douglas Gregore7450f52009-03-24 19:52:54 +00001921 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001922 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1923 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001924 // incomplete types are not object types.
1925 if (ResultType->isFunctionType()) {
1926 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1927 << ResultType << BaseExpr->getSourceRange();
1928 return ExprError();
1929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Douglas Gregore7450f52009-03-24 19:52:54 +00001931 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001932 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001933 PDiag(diag::err_subscript_incomplete_type)
1934 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001935 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Chris Lattner1efaa952009-04-24 00:30:45 +00001937 // Diagnose bad cases where we step over interface counts.
1938 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1939 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1940 << ResultType << BaseExpr->getSourceRange();
1941 return ExprError();
1942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Sebastian Redl0eb23302009-01-19 00:08:26 +00001944 Base.release();
1945 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001946 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001947 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001948}
1949
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001950QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001951CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001952 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001953 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001954 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1955 // see FIXME there.
1956 //
1957 // FIXME: This logic can be greatly simplified by splitting it along
1958 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001959 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001960
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001961 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001962 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001963
Mike Stumpeed9cac2009-02-19 03:04:26 +00001964 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001965 // special names that indicate a subset of exactly half the elements are
1966 // to be selected.
1967 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001968
Nate Begeman353417a2009-01-18 01:47:54 +00001969 // This flag determines whether or not CompName has an 's' char prefix,
1970 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001971 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001972
1973 // Check that we've found one of the special components, or that the component
1974 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001975 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001976 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1977 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001978 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001979 do
1980 compStr++;
1981 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001982 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001983 do
1984 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001985 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001986 }
Nate Begeman353417a2009-01-18 01:47:54 +00001987
Mike Stumpeed9cac2009-02-19 03:04:26 +00001988 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001989 // We didn't get to the end of the string. This means the component names
1990 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001991 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1992 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001993 return QualType();
1994 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001995
Nate Begeman353417a2009-01-18 01:47:54 +00001996 // Ensure no component accessor exceeds the width of the vector type it
1997 // operates on.
1998 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001999 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002000
2001 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002002 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002003
2004 while (*compStr) {
2005 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2006 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2007 << baseType << SourceRange(CompLoc);
2008 return QualType();
2009 }
2010 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002011 }
Nate Begeman8a997642008-05-09 06:41:27 +00002012
Nate Begeman353417a2009-01-18 01:47:54 +00002013 // If this is a halving swizzle, verify that the base type has an even
2014 // number of elements.
2015 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002016 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00002017 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00002018 return QualType();
2019 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002020
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002021 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002022 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002023 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002024 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002025 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00002026 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002027 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002028 if (HexSwizzle)
2029 CompSize--;
2030
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002031 if (CompSize == 1)
2032 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002033
Nate Begeman213541a2008-04-18 23:10:10 +00002034 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002035 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002036 // diagostics look bad. We want extended vector types to appear built-in.
2037 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2038 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2039 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002040 }
2041 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002042}
2043
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002044static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002045 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002046 const Selector &Sel,
2047 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Anders Carlsson8f28f992009-08-26 18:25:21 +00002049 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002050 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002051 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002052 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002054 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2055 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002056 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002057 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002058 return D;
2059 }
2060 return 0;
2061}
2062
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002063static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002064 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002065 const Selector &Sel,
2066 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002067 // Check protocols on qualified interfaces.
2068 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002069 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002070 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002071 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002072 GDecl = PD;
2073 break;
2074 }
2075 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002076 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002077 GDecl = OMD;
2078 break;
2079 }
2080 }
2081 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002082 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002083 E = QIdTy->qual_end(); I != E; ++I) {
2084 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002085 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002086 if (GDecl)
2087 return GDecl;
2088 }
2089 }
2090 return GDecl;
2091}
Chris Lattner76a642f2009-02-15 22:43:40 +00002092
John McCall129e2df2009-11-30 22:42:35 +00002093Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002094Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2095 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002096 const CXXScopeSpec &SS,
2097 NamedDecl *FirstQualifierInScope,
2098 DeclarationName Name, SourceLocation NameLoc,
2099 const TemplateArgumentListInfo *TemplateArgs) {
2100 Expr *BaseExpr = Base.takeAs<Expr>();
2101
2102 // Even in dependent contexts, try to diagnose base expressions with
2103 // obviously wrong types, e.g.:
2104 //
2105 // T* t;
2106 // t.f;
2107 //
2108 // In Obj-C++, however, the above expression is valid, since it could be
2109 // accessing the 'f' property if T is an Obj-C interface. The extra check
2110 // allows this, while still reporting an error if T is a struct pointer.
2111 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002112 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002113 if (PT && (!getLangOptions().ObjC1 ||
2114 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002115 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002116 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002117 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002118 return ExprError();
2119 }
2120 }
2121
John McCallaa81e162009-12-01 22:10:20 +00002122 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002123
2124 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2125 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002126 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002127 IsArrow, OpLoc,
2128 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2129 SS.getRange(),
2130 FirstQualifierInScope,
2131 Name, NameLoc,
2132 TemplateArgs));
2133}
2134
2135/// We know that the given qualified member reference points only to
2136/// declarations which do not belong to the static type of the base
2137/// expression. Diagnose the problem.
2138static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2139 Expr *BaseExpr,
2140 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002141 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002142 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002143 // If this is an implicit member access, use a different set of
2144 // diagnostics.
2145 if (!BaseExpr)
2146 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002147
2148 // FIXME: this is an exceedingly lame diagnostic for some of the more
2149 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002150 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002151 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002152 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002153}
2154
2155// Check whether the declarations we found through a nested-name
2156// specifier in a member expression are actually members of the base
2157// type. The restriction here is:
2158//
2159// C++ [expr.ref]p2:
2160// ... In these cases, the id-expression shall name a
2161// member of the class or of one of its base classes.
2162//
2163// So it's perfectly legitimate for the nested-name specifier to name
2164// an unrelated class, and for us to find an overload set including
2165// decls from classes which are not superclasses, as long as the decl
2166// we actually pick through overload resolution is from a superclass.
2167bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2168 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002169 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002170 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002171 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2172 if (!BaseRT) {
2173 // We can't check this yet because the base type is still
2174 // dependent.
2175 assert(BaseType->isDependentType());
2176 return false;
2177 }
2178 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002179
2180 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002181 // If this is an implicit member reference and we find a
2182 // non-instance member, it's not an error.
2183 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2184 return false;
John McCall129e2df2009-11-30 22:42:35 +00002185
John McCallaa81e162009-12-01 22:10:20 +00002186 // Note that we use the DC of the decl, not the underlying decl.
2187 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2188 while (RecordD->isAnonymousStructOrUnion())
2189 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2190
2191 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2192 MemberRecord.insert(RecordD->getCanonicalDecl());
2193
2194 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2195 return false;
2196 }
2197
John McCall2f841ba2009-12-02 03:53:29 +00002198 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002199 return true;
2200}
2201
2202static bool
2203LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2204 SourceRange BaseRange, const RecordType *RTy,
2205 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2206 RecordDecl *RDecl = RTy->getDecl();
2207 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2208 PDiag(diag::err_typecheck_incomplete_tag)
2209 << BaseRange))
2210 return true;
2211
2212 DeclContext *DC = RDecl;
2213 if (SS.isSet()) {
2214 // If the member name was a qualified-id, look into the
2215 // nested-name-specifier.
2216 DC = SemaRef.computeDeclContext(SS, false);
2217
John McCall2f841ba2009-12-02 03:53:29 +00002218 if (SemaRef.RequireCompleteDeclContext(SS)) {
2219 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2220 << SS.getRange() << DC;
2221 return true;
2222 }
2223
John McCallaa81e162009-12-01 22:10:20 +00002224 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2225
2226 if (!isa<TypeDecl>(DC)) {
2227 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2228 << DC << SS.getRange();
2229 return true;
John McCall129e2df2009-11-30 22:42:35 +00002230 }
2231 }
2232
John McCallaa81e162009-12-01 22:10:20 +00002233 // The record definition is complete, now look up the member.
2234 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002235
2236 return false;
2237}
2238
2239Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002240Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002241 SourceLocation OpLoc, bool IsArrow,
2242 const CXXScopeSpec &SS,
2243 NamedDecl *FirstQualifierInScope,
2244 DeclarationName Name, SourceLocation NameLoc,
2245 const TemplateArgumentListInfo *TemplateArgs) {
2246 Expr *Base = BaseArg.takeAs<Expr>();
2247
John McCall2f841ba2009-12-02 03:53:29 +00002248 if (BaseType->isDependentType() ||
2249 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002250 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002251 IsArrow, OpLoc,
2252 SS, FirstQualifierInScope,
2253 Name, NameLoc,
2254 TemplateArgs);
2255
2256 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002257
John McCallaa81e162009-12-01 22:10:20 +00002258 // Implicit member accesses.
2259 if (!Base) {
2260 QualType RecordTy = BaseType;
2261 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2262 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2263 RecordTy->getAs<RecordType>(),
2264 OpLoc, SS))
2265 return ExprError();
2266
2267 // Explicit member accesses.
2268 } else {
2269 OwningExprResult Result =
2270 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2271 SS, FirstQualifierInScope,
2272 /*ObjCImpDecl*/ DeclPtrTy());
2273
2274 if (Result.isInvalid()) {
2275 Owned(Base);
2276 return ExprError();
2277 }
2278
2279 if (Result.get())
2280 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002281 }
2282
John McCallaa81e162009-12-01 22:10:20 +00002283 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2284 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002285}
2286
2287Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002288Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2289 SourceLocation OpLoc, bool IsArrow,
2290 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002291 LookupResult &R,
2292 const TemplateArgumentListInfo *TemplateArgs) {
2293 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002294 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002295 if (IsArrow) {
2296 assert(BaseType->isPointerType());
2297 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2298 }
2299
2300 NestedNameSpecifier *Qualifier =
2301 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2302 DeclarationName MemberName = R.getLookupName();
2303 SourceLocation MemberLoc = R.getNameLoc();
2304
2305 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002306 return ExprError();
2307
John McCall129e2df2009-11-30 22:42:35 +00002308 if (R.empty()) {
2309 // Rederive where we looked up.
2310 DeclContext *DC = (SS.isSet()
2311 ? computeDeclContext(SS, false)
2312 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002313
John McCall129e2df2009-11-30 22:42:35 +00002314 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002315 << MemberName << DC
2316 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002317 return ExprError();
2318 }
2319
John McCall2f841ba2009-12-02 03:53:29 +00002320 // Diagnose qualified lookups that find only declarations from a
2321 // non-base type. Note that it's okay for lookup to find
2322 // declarations from a non-base type as long as those aren't the
2323 // ones picked by overload resolution.
2324 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002325 return ExprError();
2326
2327 // Construct an unresolved result if we in fact got an unresolved
2328 // result.
2329 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002330 bool Dependent =
2331 R.isUnresolvableResult() ||
2332 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002333
2334 UnresolvedMemberExpr *MemExpr
2335 = UnresolvedMemberExpr::Create(Context, Dependent,
2336 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002337 BaseExpr, BaseExprType,
2338 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002339 Qualifier, SS.getRange(),
2340 MemberName, MemberLoc,
2341 TemplateArgs);
2342 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2343 MemExpr->addDecl(*I);
2344
2345 return Owned(MemExpr);
2346 }
2347
2348 assert(R.isSingleResult());
2349 NamedDecl *MemberDecl = R.getFoundDecl();
2350
2351 // FIXME: diagnose the presence of template arguments now.
2352
2353 // If the decl being referenced had an error, return an error for this
2354 // sub-expr without emitting another error, in order to avoid cascading
2355 // error cases.
2356 if (MemberDecl->isInvalidDecl())
2357 return ExprError();
2358
John McCallaa81e162009-12-01 22:10:20 +00002359 // Handle the implicit-member-access case.
2360 if (!BaseExpr) {
2361 // If this is not an instance member, convert to a non-member access.
2362 if (!IsInstanceMember(MemberDecl))
2363 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2364
2365 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2366 }
2367
John McCall129e2df2009-11-30 22:42:35 +00002368 bool ShouldCheckUse = true;
2369 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2370 // Don't diagnose the use of a virtual member function unless it's
2371 // explicitly qualified.
2372 if (MD->isVirtual() && !SS.isSet())
2373 ShouldCheckUse = false;
2374 }
2375
2376 // Check the use of this member.
2377 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2378 Owned(BaseExpr);
2379 return ExprError();
2380 }
2381
2382 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2383 // We may have found a field within an anonymous union or struct
2384 // (C++ [class.union]).
2385 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2386 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2387 BaseExpr, OpLoc);
2388
2389 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2390 QualType MemberType = FD->getType();
2391 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2392 MemberType = Ref->getPointeeType();
2393 else {
2394 Qualifiers BaseQuals = BaseType.getQualifiers();
2395 BaseQuals.removeObjCGCAttr();
2396 if (FD->isMutable()) BaseQuals.removeConst();
2397
2398 Qualifiers MemberQuals
2399 = Context.getCanonicalType(MemberType).getQualifiers();
2400
2401 Qualifiers Combined = BaseQuals + MemberQuals;
2402 if (Combined != MemberQuals)
2403 MemberType = Context.getQualifiedType(MemberType, Combined);
2404 }
2405
2406 MarkDeclarationReferenced(MemberLoc, FD);
2407 if (PerformObjectMemberConversion(BaseExpr, FD))
2408 return ExprError();
2409 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2410 FD, MemberLoc, MemberType));
2411 }
2412
2413 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2414 MarkDeclarationReferenced(MemberLoc, Var);
2415 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2416 Var, MemberLoc,
2417 Var->getType().getNonReferenceType()));
2418 }
2419
2420 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2421 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2422 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2423 MemberFn, MemberLoc,
2424 MemberFn->getType()));
2425 }
2426
2427 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2428 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2429 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2430 Enum, MemberLoc, Enum->getType()));
2431 }
2432
2433 Owned(BaseExpr);
2434
2435 if (isa<TypeDecl>(MemberDecl))
2436 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2437 << MemberName << int(IsArrow));
2438
2439 // We found a declaration kind that we didn't expect. This is a
2440 // generic error message that tells the user that she can't refer
2441 // to this member with '.' or '->'.
2442 return ExprError(Diag(MemberLoc,
2443 diag::err_typecheck_member_reference_unknown)
2444 << MemberName << int(IsArrow));
2445}
2446
2447/// Look up the given member of the given non-type-dependent
2448/// expression. This can return in one of two ways:
2449/// * If it returns a sentinel null-but-valid result, the caller will
2450/// assume that lookup was performed and the results written into
2451/// the provided structure. It will take over from there.
2452/// * Otherwise, the returned expression will be produced in place of
2453/// an ordinary member expression.
2454///
2455/// The ObjCImpDecl bit is a gross hack that will need to be properly
2456/// fixed for ObjC++.
2457Sema::OwningExprResult
2458Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2459 bool IsArrow, SourceLocation OpLoc,
2460 const CXXScopeSpec &SS,
2461 NamedDecl *FirstQualifierInScope,
2462 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002463 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002464
Steve Naroff3cc4af82007-12-16 21:42:28 +00002465 // Perform default conversions.
2466 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002467
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002468 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002469 assert(!BaseType->isDependentType());
2470
2471 DeclarationName MemberName = R.getLookupName();
2472 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002473
2474 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002475 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002476 // function. Suggest the addition of those parentheses, build the
2477 // call, and continue on.
2478 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2479 if (const FunctionProtoType *Fun
2480 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2481 QualType ResultTy = Fun->getResultType();
2482 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002483 ((!IsArrow && ResultTy->isRecordType()) ||
2484 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002485 ResultTy->getAs<PointerType>()->getPointeeType()
2486 ->isRecordType()))) {
2487 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2488 Diag(Loc, diag::err_member_reference_needs_call)
2489 << QualType(Fun, 0)
2490 << CodeModificationHint::CreateInsertion(Loc, "()");
2491
2492 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002493 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002494 MultiExprArg(*this, 0, 0), 0, Loc);
2495 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002496 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002497
2498 BaseExpr = NewBase.takeAs<Expr>();
2499 DefaultFunctionArrayConversion(BaseExpr);
2500 BaseType = BaseExpr->getType();
2501 }
2502 }
2503 }
2504
David Chisnall0f436562009-08-17 16:35:33 +00002505 // If this is an Objective-C pseudo-builtin and a definition is provided then
2506 // use that.
2507 if (BaseType->isObjCIdType()) {
2508 // We have an 'id' type. Rather than fall through, we check if this
2509 // is a reference to 'isa'.
2510 if (BaseType != Context.ObjCIdRedefinitionType) {
2511 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002512 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002513 }
David Chisnall0f436562009-08-17 16:35:33 +00002514 }
John McCall129e2df2009-11-30 22:42:35 +00002515
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002516 // If this is an Objective-C pseudo-builtin and a definition is provided then
2517 // use that.
2518 if (Context.isObjCSelType(BaseType)) {
2519 // We have an 'SEL' type. Rather than fall through, we check if this
2520 // is a reference to 'sel_id'.
2521 if (BaseType != Context.ObjCSelRedefinitionType) {
2522 BaseType = Context.ObjCSelRedefinitionType;
2523 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2524 }
2525 }
John McCall129e2df2009-11-30 22:42:35 +00002526
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002527 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002528
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002529 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002530 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002531 // Also must look for a getter name which uses property syntax.
2532 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2533 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2534 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2535 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2536 ObjCMethodDecl *Getter;
2537 // FIXME: need to also look locally in the implementation.
2538 if ((Getter = IFace->lookupClassMethod(Sel))) {
2539 // Check the use of this method.
2540 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2541 return ExprError();
2542 }
2543 // If we found a getter then this may be a valid dot-reference, we
2544 // will look for the matching setter, in case it is needed.
2545 Selector SetterSel =
2546 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2547 PP.getSelectorTable(), Member);
2548 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2549 if (!Setter) {
2550 // If this reference is in an @implementation, also check for 'private'
2551 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002552 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002553 }
2554 // Look through local category implementations associated with the class.
2555 if (!Setter)
2556 Setter = IFace->getCategoryClassMethod(SetterSel);
2557
2558 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2559 return ExprError();
2560
2561 if (Getter || Setter) {
2562 QualType PType;
2563
2564 if (Getter)
2565 PType = Getter->getResultType();
2566 else
2567 // Get the expression type from Setter's incoming parameter.
2568 PType = (*(Setter->param_end() -1))->getType();
2569 // FIXME: we must check that the setter has property type.
2570 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2571 PType,
2572 Setter, MemberLoc, BaseExpr));
2573 }
2574 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2575 << MemberName << BaseType);
2576 }
2577 }
2578
2579 if (BaseType->isObjCClassType() &&
2580 BaseType != Context.ObjCClassRedefinitionType) {
2581 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002582 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002583 }
Mike Stump1eb44332009-09-09 15:08:12 +00002584
John McCall129e2df2009-11-30 22:42:35 +00002585 if (IsArrow) {
2586 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002587 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002588 else if (BaseType->isObjCObjectPointerType())
2589 ;
John McCall129e2df2009-11-30 22:42:35 +00002590 else {
2591 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2592 << BaseType << BaseExpr->getSourceRange();
2593 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002594 }
John McCall129e2df2009-11-30 22:42:35 +00002595 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002596
John McCall129e2df2009-11-30 22:42:35 +00002597 // Handle field access to simple records. This also handles access
2598 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002599 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002600 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2601 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002602 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002603 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002604 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002605
Douglas Gregora71d8192009-09-04 17:36:40 +00002606 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2607 // into a record type was handled above, any destructor we see here is a
2608 // pseudo-destructor.
2609 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2610 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002611 // The left hand side of the dot operator shall be of scalar type. The
2612 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002613 // type.
2614 if (!BaseType->isScalarType())
2615 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2616 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Douglas Gregora71d8192009-09-04 17:36:40 +00002618 // [...] The type designated by the pseudo-destructor-name shall be the
2619 // same as the object type.
2620 if (!MemberName.getCXXNameType()->isDependentType() &&
2621 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2622 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2623 << BaseType << MemberName.getCXXNameType()
2624 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002625
2626 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002627 // the form
2628 //
Mike Stump1eb44332009-09-09 15:08:12 +00002629 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2630 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002631 // shall designate the same scalar type.
2632 //
2633 // FIXME: DPG can't see any way to trigger this particular clause, so it
2634 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Douglas Gregora71d8192009-09-04 17:36:40 +00002636 // FIXME: We've lost the precise spelling of the type by going through
2637 // DeclarationName. Can we do better?
2638 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002639 IsArrow, OpLoc,
2640 (NestedNameSpecifier *) SS.getScopeRep(),
2641 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002642 MemberName.getCXXNameType(),
2643 MemberLoc));
2644 }
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Chris Lattnera38e6b12008-07-21 04:59:05 +00002646 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2647 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002648 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2649 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002650 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002651 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002652 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002653 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002654 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2655
Steve Naroffc70e8d92009-07-16 00:25:06 +00002656 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2657 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002658 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Steve Naroffc70e8d92009-07-16 00:25:06 +00002660 if (IV) {
2661 // If the decl being referenced had an error, return an error for this
2662 // sub-expr without emitting another error, in order to avoid cascading
2663 // error cases.
2664 if (IV->isInvalidDecl())
2665 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002666
Steve Naroffc70e8d92009-07-16 00:25:06 +00002667 // Check whether we can reference this field.
2668 if (DiagnoseUseOfDecl(IV, MemberLoc))
2669 return ExprError();
2670 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2671 IV->getAccessControl() != ObjCIvarDecl::Package) {
2672 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2673 if (ObjCMethodDecl *MD = getCurMethodDecl())
2674 ClassOfMethodDecl = MD->getClassInterface();
2675 else if (ObjCImpDecl && getCurFunctionDecl()) {
2676 // Case of a c-function declared inside an objc implementation.
2677 // FIXME: For a c-style function nested inside an objc implementation
2678 // class, there is no implementation context available, so we pass
2679 // down the context as argument to this routine. Ideally, this context
2680 // need be passed down in the AST node and somehow calculated from the
2681 // AST for a function decl.
2682 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002683 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002684 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2685 ClassOfMethodDecl = IMPD->getClassInterface();
2686 else if (ObjCCategoryImplDecl* CatImplClass =
2687 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2688 ClassOfMethodDecl = CatImplClass->getClassInterface();
2689 }
Mike Stump1eb44332009-09-09 15:08:12 +00002690
2691 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2692 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002693 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002694 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002695 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002696 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2697 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002698 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002699 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002700 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002701
2702 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2703 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002704 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002705 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002706 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002707 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002708 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002709 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002710 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002711 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002712 if (!IsArrow && (BaseType->isObjCIdType() ||
2713 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002714 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002715 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Steve Naroff14108da2009-07-10 23:34:53 +00002717 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002718 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002719 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2720 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2721 // Check the use of this declaration
2722 if (DiagnoseUseOfDecl(PD, MemberLoc))
2723 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Steve Naroff14108da2009-07-10 23:34:53 +00002725 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2726 MemberLoc, BaseExpr));
2727 }
2728 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2729 // Check the use of this method.
2730 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2731 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Steve Naroff14108da2009-07-10 23:34:53 +00002733 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002734 OMD->getResultType(),
2735 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002736 NULL, 0));
2737 }
2738 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002739
Steve Naroff14108da2009-07-10 23:34:53 +00002740 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002741 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002742 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002743 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2744 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002745 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002746 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002747 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2748 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002749 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Daniel Dunbar2307d312008-09-03 01:05:41 +00002751 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002752 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002753 // Check whether we can reference this property.
2754 if (DiagnoseUseOfDecl(PD, MemberLoc))
2755 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002756 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002757 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002758 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002759 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2760 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002761 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002762 MemberLoc, BaseExpr));
2763 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002764 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002765 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2766 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002767 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002768 // Check whether we can reference this property.
2769 if (DiagnoseUseOfDecl(PD, MemberLoc))
2770 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002771
Steve Naroff6ece14c2009-01-21 00:14:39 +00002772 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002773 MemberLoc, BaseExpr));
2774 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002775 // If that failed, look for an "implicit" property by seeing if the nullary
2776 // selector is implemented.
2777
2778 // FIXME: The logic for looking up nullary and unary selectors should be
2779 // shared with the code in ActOnInstanceMessage.
2780
Anders Carlsson8f28f992009-08-26 18:25:21 +00002781 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002782 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002783
Daniel Dunbar2307d312008-09-03 01:05:41 +00002784 // If this reference is in an @implementation, check for 'private' methods.
2785 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002786 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002787
Steve Naroff7692ed62008-10-22 19:16:27 +00002788 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002789 if (!Getter)
2790 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002791 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002792 // Check if we can reference this property.
2793 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2794 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002795 }
2796 // If we found a getter then this may be a valid dot-reference, we
2797 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002798 Selector SetterSel =
2799 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002800 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002801 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002802 if (!Setter) {
2803 // If this reference is in an @implementation, also check for 'private'
2804 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002805 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002806 }
2807 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002808 if (!Setter)
2809 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002810
Steve Naroff1ca66942009-03-11 13:48:17 +00002811 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2812 return ExprError();
2813
2814 if (Getter || Setter) {
2815 QualType PType;
2816
2817 if (Getter)
2818 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002819 else
2820 // Get the expression type from Setter's incoming parameter.
2821 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002822 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002823 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002824 Setter, MemberLoc, BaseExpr));
2825 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002826 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002827 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002828 }
Mike Stump1eb44332009-09-09 15:08:12 +00002829
Steve Narofff242b1b2009-07-24 17:54:45 +00002830 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002831 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002832 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002833 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002834 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2835 Context.getObjCIdType()));
2836
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002837 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002838 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002839 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002840 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2841 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002842 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002843 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002844 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002845 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002846
Douglas Gregor214f31a2009-03-27 06:00:30 +00002847 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2848 << BaseType << BaseExpr->getSourceRange();
2849
Douglas Gregor214f31a2009-03-27 06:00:30 +00002850 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002851}
2852
John McCall129e2df2009-11-30 22:42:35 +00002853static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2854 SourceLocation NameLoc,
2855 Sema::ExprArg MemExpr) {
2856 Expr *E = (Expr *) MemExpr.get();
2857 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2858 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002859 << isa<CXXPseudoDestructorExpr>(E)
2860 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2861
John McCall129e2df2009-11-30 22:42:35 +00002862 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2863 move(MemExpr),
2864 /*LPLoc*/ ExpectedLParenLoc,
2865 Sema::MultiExprArg(SemaRef, 0, 0),
2866 /*CommaLocs*/ 0,
2867 /*RPLoc*/ ExpectedLParenLoc);
2868}
2869
2870/// The main callback when the parser finds something like
2871/// expression . [nested-name-specifier] identifier
2872/// expression -> [nested-name-specifier] identifier
2873/// where 'identifier' encompasses a fairly broad spectrum of
2874/// possibilities, including destructor and operator references.
2875///
2876/// \param OpKind either tok::arrow or tok::period
2877/// \param HasTrailingLParen whether the next token is '(', which
2878/// is used to diagnose mis-uses of special members that can
2879/// only be called
2880/// \param ObjCImpDecl the current ObjC @implementation decl;
2881/// this is an ugly hack around the fact that ObjC @implementations
2882/// aren't properly put in the context chain
2883Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2884 SourceLocation OpLoc,
2885 tok::TokenKind OpKind,
2886 const CXXScopeSpec &SS,
2887 UnqualifiedId &Id,
2888 DeclPtrTy ObjCImpDecl,
2889 bool HasTrailingLParen) {
2890 if (SS.isSet() && SS.isInvalid())
2891 return ExprError();
2892
2893 TemplateArgumentListInfo TemplateArgsBuffer;
2894
2895 // Decompose the name into its component parts.
2896 DeclarationName Name;
2897 SourceLocation NameLoc;
2898 const TemplateArgumentListInfo *TemplateArgs;
2899 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2900 Name, NameLoc, TemplateArgs);
2901
2902 bool IsArrow = (OpKind == tok::arrow);
2903
2904 NamedDecl *FirstQualifierInScope
2905 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2906 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2907
2908 // This is a postfix expression, so get rid of ParenListExprs.
2909 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2910
2911 Expr *Base = BaseArg.takeAs<Expr>();
2912 OwningExprResult Result(*this);
2913 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00002914 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00002915 IsArrow, OpLoc,
2916 SS, FirstQualifierInScope,
2917 Name, NameLoc,
2918 TemplateArgs);
2919 } else {
2920 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2921 if (TemplateArgs) {
2922 // Re-use the lookup done for the template name.
2923 DecomposeTemplateName(R, Id);
2924 } else {
2925 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
2926 SS, FirstQualifierInScope,
2927 ObjCImpDecl);
2928
2929 if (Result.isInvalid()) {
2930 Owned(Base);
2931 return ExprError();
2932 }
2933
2934 if (Result.get()) {
2935 // The only way a reference to a destructor can be used is to
2936 // immediately call it, which falls into this case. If the
2937 // next token is not a '(', produce a diagnostic and build the
2938 // call now.
2939 if (!HasTrailingLParen &&
2940 Id.getKind() == UnqualifiedId::IK_DestructorName)
2941 return DiagnoseDtorReference(*this, NameLoc, move(Result));
2942
2943 return move(Result);
2944 }
2945 }
2946
John McCallaa81e162009-12-01 22:10:20 +00002947 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
2948 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002949 }
2950
2951 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002952}
2953
Anders Carlsson56c5e332009-08-25 03:49:14 +00002954Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2955 FunctionDecl *FD,
2956 ParmVarDecl *Param) {
2957 if (Param->hasUnparsedDefaultArg()) {
2958 Diag (CallLoc,
2959 diag::err_use_of_default_argument_to_function_declared_later) <<
2960 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002961 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002962 diag::note_default_argument_declared_here);
2963 } else {
2964 if (Param->hasUninstantiatedDefaultArg()) {
2965 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2966
2967 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002968 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002969
Mike Stump1eb44332009-09-09 15:08:12 +00002970 InstantiatingTemplate Inst(*this, CallLoc, Param,
2971 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002972 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002973
John McCallce3ff2b2009-08-25 22:02:44 +00002974 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002975 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002976 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002977
2978 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002979 /*FIXME:EqualLoc*/
2980 UninstExpr->getSourceRange().getBegin()))
2981 return ExprError();
2982 }
Mike Stump1eb44332009-09-09 15:08:12 +00002983
Anders Carlsson56c5e332009-08-25 03:49:14 +00002984 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Anders Carlsson56c5e332009-08-25 03:49:14 +00002986 // If the default expression creates temporaries, we need to
2987 // push them to the current stack of expression temporaries so they'll
2988 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002989 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002990 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002991 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002992 "Can't destroy temporaries in a default argument expr!");
2993 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2994 ExprTemporaries.push_back(E->getTemporary(I));
2995 }
2996 }
2997
2998 // We already type-checked the argument, so we know it works.
2999 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3000}
3001
Douglas Gregor88a35142008-12-22 05:46:06 +00003002/// ConvertArgumentsForCall - Converts the arguments specified in
3003/// Args/NumArgs to the parameter types of the function FDecl with
3004/// function prototype Proto. Call is the call expression itself, and
3005/// Fn is the function expression. For a C++ member function, this
3006/// routine does not attempt to convert the object argument. Returns
3007/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003008bool
3009Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003010 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003011 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003012 Expr **Args, unsigned NumArgs,
3013 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003014 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003015 // assignment, to the types of the corresponding parameter, ...
3016 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003017 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003018
Douglas Gregor88a35142008-12-22 05:46:06 +00003019 // If too few arguments are available (and we don't have default
3020 // arguments for the remaining parameters), don't make the call.
3021 if (NumArgs < NumArgsInProto) {
3022 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3023 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3024 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003025 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003026 }
3027
3028 // If too many are passed and not variadic, error on the extras and drop
3029 // them.
3030 if (NumArgs > NumArgsInProto) {
3031 if (!Proto->isVariadic()) {
3032 Diag(Args[NumArgsInProto]->getLocStart(),
3033 diag::err_typecheck_call_too_many_args)
3034 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3035 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3036 Args[NumArgs-1]->getLocEnd());
3037 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003038 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003039 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003040 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003041 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003042 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003043 VariadicCallType CallType =
3044 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3045 if (Fn->getType()->isBlockPointerType())
3046 CallType = VariadicBlock; // Block
3047 else if (isa<MemberExpr>(Fn))
3048 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003049 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003050 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003051 if (Invalid)
3052 return true;
3053 unsigned TotalNumArgs = AllArgs.size();
3054 for (unsigned i = 0; i < TotalNumArgs; ++i)
3055 Call->setArg(i, AllArgs[i]);
3056
3057 return false;
3058}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003059
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003060bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3061 FunctionDecl *FDecl,
3062 const FunctionProtoType *Proto,
3063 unsigned FirstProtoArg,
3064 Expr **Args, unsigned NumArgs,
3065 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003066 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003067 unsigned NumArgsInProto = Proto->getNumArgs();
3068 unsigned NumArgsToCheck = NumArgs;
3069 bool Invalid = false;
3070 if (NumArgs != NumArgsInProto)
3071 // Use default arguments for missing arguments
3072 NumArgsToCheck = NumArgsInProto;
3073 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003074 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003075 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003076 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003077
Douglas Gregor88a35142008-12-22 05:46:06 +00003078 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003079 if (ArgIx < NumArgs) {
3080 Arg = Args[ArgIx++];
3081
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003082 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3083 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003084 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003085 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003086 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003087
Douglas Gregor61366e92008-12-24 00:01:03 +00003088 // Pass the argument.
3089 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3090 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003091
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003092 if (!ProtoArgType->isReferenceType())
3093 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003094 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003095 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003096
Mike Stump1eb44332009-09-09 15:08:12 +00003097 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003098 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003099 if (ArgExpr.isInvalid())
3100 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003101
Anders Carlsson56c5e332009-08-25 03:49:14 +00003102 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003103 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003104 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003105 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003106
Douglas Gregor88a35142008-12-22 05:46:06 +00003107 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003108 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003109 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003110 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003111 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003112 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003113 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003114 }
3115 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003116 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003117}
3118
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003119/// \brief "Deconstruct" the function argument of a call expression to find
3120/// the underlying declaration (if any), the name of the called function,
3121/// whether argument-dependent lookup is available, whether it has explicit
3122/// template arguments, etc.
3123void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00003124 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003125 DeclarationName &Name,
3126 NestedNameSpecifier *&Qualifier,
3127 SourceRange &QualifierRange,
3128 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00003129 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003130 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00003131 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003132 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003133 Name = DeclarationName();
3134 Qualifier = 0;
3135 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00003136 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00003137 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003138 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00003139
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003140 // If we're directly calling a function, get the appropriate declaration.
3141 // Also, in C++, keep track of whether we should perform argument-dependent
3142 // lookup and whether there were any explicitly-specified template arguments.
3143 while (true) {
3144 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3145 FnExpr = IcExpr->getSubExpr();
3146 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003147 FnExpr = PExpr->getSubExpr();
3148 } else if (isa<UnaryOperator>(FnExpr) &&
3149 cast<UnaryOperator>(FnExpr)->getOpcode()
3150 == UnaryOperator::AddrOf) {
3151 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003152 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00003153 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3154 ArgumentDependentLookup = false;
3155 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00003156 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003157 break;
John McCallba135432009-11-21 08:51:07 +00003158 } else if (UnresolvedLookupExpr *UnresLookup
3159 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3160 Name = UnresLookup->getName();
3161 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3162 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00003163 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00003164 if ((Qualifier = UnresLookup->getQualifier()))
3165 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00003166 if (UnresLookup->hasExplicitTemplateArgs()) {
3167 HasExplicitTemplateArguments = true;
3168 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003169 }
3170 break;
3171 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003172 break;
3173 }
3174 }
3175}
3176
Steve Narofff69936d2007-09-16 03:34:24 +00003177/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003178/// This provides the location of the left/right parens and a list of comma
3179/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003180Action::OwningExprResult
3181Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3182 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003183 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003184 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003185
3186 // Since this might be a postfix expression, get rid of ParenListExprs.
3187 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003189 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003190 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003191 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Douglas Gregor88a35142008-12-22 05:46:06 +00003193 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003194 // If this is a pseudo-destructor expression, build the call immediately.
3195 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3196 if (NumArgs > 0) {
3197 // Pseudo-destructor calls should not have any arguments.
3198 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3199 << CodeModificationHint::CreateRemoval(
3200 SourceRange(Args[0]->getLocStart(),
3201 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Douglas Gregora71d8192009-09-04 17:36:40 +00003203 for (unsigned I = 0; I != NumArgs; ++I)
3204 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Douglas Gregora71d8192009-09-04 17:36:40 +00003206 NumArgs = 0;
3207 }
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Douglas Gregora71d8192009-09-04 17:36:40 +00003209 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3210 RParenLoc));
3211 }
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Douglas Gregor17330012009-02-04 15:01:18 +00003213 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003214 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003215 // FIXME: Will need to cache the results of name lookup (including ADL) in
3216 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003217 bool Dependent = false;
3218 if (Fn->isTypeDependent())
3219 Dependent = true;
3220 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3221 Dependent = true;
3222
3223 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003224 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003225 Context.DependentTy, RParenLoc));
3226
3227 // Determine whether this is a call to an object (C++ [over.call.object]).
3228 if (Fn->getType()->isRecordType())
3229 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3230 CommaLocs, RParenLoc));
3231
John McCall129e2df2009-11-30 22:42:35 +00003232 Expr *NakedFn = Fn->IgnoreParens();
3233
3234 // Determine whether this is a call to an unresolved member function.
3235 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3236 // If lookup was unresolved but not dependent (i.e. didn't find
3237 // an unresolved using declaration), it has to be an overloaded
3238 // function set, which means it must contain either multiple
3239 // declarations (all methods or method templates) or a single
3240 // method template.
3241 assert((MemE->getNumDecls() > 1) ||
3242 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003243 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003244
John McCallaa81e162009-12-01 22:10:20 +00003245 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3246 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003247 }
3248
Douglas Gregorfa047642009-02-04 00:32:51 +00003249 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003250 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003251 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003252 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003253 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3254 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003255 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003256
3257 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003258 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003259 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3260 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003261 if (const FunctionProtoType *FPT =
3262 dyn_cast<FunctionProtoType>(BO->getType())) {
3263 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003264
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003265 ExprOwningPtr<CXXMemberCallExpr>
3266 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3267 NumArgs, ResultTy,
3268 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003269
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003270 if (CheckCallReturnType(FPT->getResultType(),
3271 BO->getRHS()->getSourceRange().getBegin(),
3272 TheCall.get(), 0))
3273 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003274
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003275 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3276 RParenLoc))
3277 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003278
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003279 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3280 }
3281 return ExprError(Diag(Fn->getLocStart(),
3282 diag::err_typecheck_call_not_function)
3283 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003284 }
3285 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003286 }
3287
Douglas Gregorfa047642009-02-04 00:32:51 +00003288 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003289 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003290 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00003291 llvm::SmallVector<NamedDecl*,8> Fns;
3292 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00003293 bool Overloaded;
3294 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003295 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00003296 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003297 NestedNameSpecifier *Qualifier = 0;
3298 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00003299 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00003300 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00003301 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003302
John McCall7453ed42009-11-22 00:44:51 +00003303 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3304 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00003305
John McCall7453ed42009-11-22 00:44:51 +00003306 if (Overloaded || ADL) {
3307#ifndef NDEBUG
3308 if (ADL) {
3309 // To do ADL, we must have found an unqualified name.
3310 assert(UnqualifiedName && "found no unqualified name for ADL");
3311
3312 // We don't perform ADL for implicit declarations of builtins.
3313 // Verify that this was correctly set up.
3314 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3315 FDecl->getBuiltinID() && FDecl->isImplicit())
3316 assert(0 && "performing ADL for builtin");
3317
3318 // We don't perform ADL in C.
3319 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3320 }
3321
3322 if (Overloaded) {
3323 // To be overloaded, we must either have multiple functions or
3324 // at least one function template (which is effectively an
3325 // infinite set of functions).
3326 assert((Fns.size() > 1 ||
3327 (Fns.size() == 1 &&
3328 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3329 && "unrecognized overload situation");
3330 }
3331#endif
3332
3333 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00003334 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00003335 LParenLoc, Args, NumArgs, CommaLocs,
3336 RParenLoc, ADL);
3337 if (!FDecl)
3338 return ExprError();
3339
3340 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3341
3342 NDecl = FDecl;
3343 } else {
3344 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3345 if (Fns.empty())
John McCallaa81e162009-12-01 22:10:20 +00003346 NDecl = 0;
John McCall7453ed42009-11-22 00:44:51 +00003347 else {
3348 NDecl = Fns[0];
Douglas Gregorfa047642009-02-04 00:32:51 +00003349 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003350 }
Chris Lattner04421082008-04-08 04:40:51 +00003351
John McCallaa81e162009-12-01 22:10:20 +00003352 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3353}
3354
3355/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3356/// expression not of \p OverloadTy. The expression should
3357/// unary-convert to an expression of function-pointer or
3358/// block-pointer type.
3359///
3360/// \param NDecl the declaration being called, if available
3361Sema::OwningExprResult
3362Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3363 SourceLocation LParenLoc,
3364 Expr **Args, unsigned NumArgs,
3365 SourceLocation RParenLoc) {
3366 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3367
Chris Lattner04421082008-04-08 04:40:51 +00003368 // Promote the function operand.
3369 UsualUnaryConversions(Fn);
3370
Chris Lattner925e60d2007-12-28 05:29:59 +00003371 // Make the call expr early, before semantic checks. This guarantees cleanup
3372 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003373 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3374 Args, NumArgs,
3375 Context.BoolTy,
3376 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003377
Steve Naroffdd972f22008-09-05 22:11:13 +00003378 const FunctionType *FuncT;
3379 if (!Fn->getType()->isBlockPointerType()) {
3380 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3381 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003382 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003383 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003384 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3385 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003386 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003387 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003388 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003389 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003390 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003391 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003392 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3393 << Fn->getType() << Fn->getSourceRange());
3394
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003395 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003396 if (CheckCallReturnType(FuncT->getResultType(),
3397 Fn->getSourceRange().getBegin(), TheCall.get(),
3398 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003399 return ExprError();
3400
Chris Lattner925e60d2007-12-28 05:29:59 +00003401 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003402 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003403
Douglas Gregor72564e72009-02-26 23:50:07 +00003404 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003405 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003406 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003407 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003408 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003409 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003410
Douglas Gregor74734d52009-04-02 15:37:10 +00003411 if (FDecl) {
3412 // Check if we have too few/too many template arguments, based
3413 // on our knowledge of the function definition.
3414 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003415 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003416 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003417 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003418 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3419 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3420 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3421 }
3422 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003423 }
3424
Steve Naroffb291ab62007-08-28 23:30:39 +00003425 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003426 for (unsigned i = 0; i != NumArgs; i++) {
3427 Expr *Arg = Args[i];
3428 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003429 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3430 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003431 PDiag(diag::err_call_incomplete_argument)
3432 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003433 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003434 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003435 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003436 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003437
Douglas Gregor88a35142008-12-22 05:46:06 +00003438 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3439 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003440 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3441 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003442
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003443 // Check for sentinels
3444 if (NDecl)
3445 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Chris Lattner59907c42007-08-10 20:18:51 +00003447 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003448 if (FDecl) {
3449 if (CheckFunctionCall(FDecl, TheCall.get()))
3450 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003452 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003453 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3454 } else if (NDecl) {
3455 if (CheckBlockCall(NDecl, TheCall.get()))
3456 return ExprError();
3457 }
Chris Lattner59907c42007-08-10 20:18:51 +00003458
Anders Carlssonec74c592009-08-16 03:06:32 +00003459 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003460}
3461
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003462Action::OwningExprResult
3463Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3464 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003465 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003466 //FIXME: Preserve type source info.
3467 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003468 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003469 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003470 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003471
Eli Friedman6223c222008-05-20 05:22:08 +00003472 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003473 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003474 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3475 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003476 } else if (!literalType->isDependentType() &&
3477 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003478 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003479 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003480 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003481 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003482
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003483 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003484 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003485 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003486
Chris Lattner371f2582008-12-04 23:50:19 +00003487 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003488 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003489 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003490 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003491 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003492 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003493 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003494 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003495}
3496
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003497Action::OwningExprResult
3498Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003499 SourceLocation RBraceLoc) {
3500 unsigned NumInit = initlist.size();
3501 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003502
Steve Naroff08d92e42007-09-15 18:49:24 +00003503 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003504 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003505
Mike Stumpeed9cac2009-02-19 03:04:26 +00003506 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003507 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003508 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003509 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003510}
3511
Anders Carlsson82debc72009-10-18 18:12:03 +00003512static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3513 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003514 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003515 return CastExpr::CK_NoOp;
3516
3517 if (SrcTy->hasPointerRepresentation()) {
3518 if (DestTy->hasPointerRepresentation())
3519 return CastExpr::CK_BitCast;
3520 if (DestTy->isIntegerType())
3521 return CastExpr::CK_PointerToIntegral;
3522 }
3523
3524 if (SrcTy->isIntegerType()) {
3525 if (DestTy->isIntegerType())
3526 return CastExpr::CK_IntegralCast;
3527 if (DestTy->hasPointerRepresentation())
3528 return CastExpr::CK_IntegralToPointer;
3529 if (DestTy->isRealFloatingType())
3530 return CastExpr::CK_IntegralToFloating;
3531 }
3532
3533 if (SrcTy->isRealFloatingType()) {
3534 if (DestTy->isRealFloatingType())
3535 return CastExpr::CK_FloatingCast;
3536 if (DestTy->isIntegerType())
3537 return CastExpr::CK_FloatingToIntegral;
3538 }
3539
3540 // FIXME: Assert here.
3541 // assert(false && "Unhandled cast combination!");
3542 return CastExpr::CK_Unknown;
3543}
3544
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003545/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003546bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003547 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003548 CXXMethodDecl *& ConversionDecl,
3549 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003550 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003551 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3552 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003553
Eli Friedman199ea952009-08-15 19:02:19 +00003554 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003555
3556 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3557 // type needs to be scalar.
3558 if (castType->isVoidType()) {
3559 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003560 Kind = CastExpr::CK_ToVoid;
3561 return false;
3562 }
3563
3564 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003565 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003566 (castType->isStructureType() || castType->isUnionType())) {
3567 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003568 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003569 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3570 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003571 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003572 return false;
3573 }
3574
3575 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003576 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003577 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003578 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003579 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003580 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003581 if (Context.hasSameUnqualifiedType(Field->getType(),
3582 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003583 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3584 << castExpr->getSourceRange();
3585 break;
3586 }
3587 }
3588 if (Field == FieldEnd)
3589 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3590 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003591 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003592 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003593 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003594
3595 // Reject any other conversions to non-scalar types.
3596 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3597 << castType << castExpr->getSourceRange();
3598 }
3599
3600 if (!castExpr->getType()->isScalarType() &&
3601 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003602 return Diag(castExpr->getLocStart(),
3603 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003604 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003605 }
3606
Anders Carlsson16a89042009-10-16 05:23:41 +00003607 if (castType->isExtVectorType())
3608 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3609
Anders Carlssonc3516322009-10-16 02:48:28 +00003610 if (castType->isVectorType())
3611 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3612 if (castExpr->getType()->isVectorType())
3613 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3614
3615 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003616 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003617
Anders Carlsson16a89042009-10-16 05:23:41 +00003618 if (isa<ObjCSelectorExpr>(castExpr))
3619 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3620
Anders Carlssonc3516322009-10-16 02:48:28 +00003621 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003622 QualType castExprType = castExpr->getType();
3623 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3624 return Diag(castExpr->getLocStart(),
3625 diag::err_cast_pointer_from_non_pointer_int)
3626 << castExprType << castExpr->getSourceRange();
3627 } else if (!castExpr->getType()->isArithmeticType()) {
3628 if (!castType->isIntegralType() && castType->isArithmeticType())
3629 return Diag(castExpr->getLocStart(),
3630 diag::err_cast_pointer_to_non_pointer_int)
3631 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003632 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003633
3634 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003635 return false;
3636}
3637
Anders Carlssonc3516322009-10-16 02:48:28 +00003638bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3639 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003640 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003641
Anders Carlssona64db8f2007-11-27 05:51:55 +00003642 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003643 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003644 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003645 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003646 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003647 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003648 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003649 } else
3650 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003651 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003652 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003653
Anders Carlssonc3516322009-10-16 02:48:28 +00003654 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003655 return false;
3656}
3657
Anders Carlsson16a89042009-10-16 05:23:41 +00003658bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3659 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003660 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003661
3662 QualType SrcTy = CastExpr->getType();
3663
Nate Begeman9b10da62009-06-27 22:05:55 +00003664 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3665 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003666 if (SrcTy->isVectorType()) {
3667 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3668 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3669 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003670 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003671 return false;
3672 }
3673
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003674 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003675 // conversion will take place first from scalar to elt type, and then
3676 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003677 if (SrcTy->isPointerType())
3678 return Diag(R.getBegin(),
3679 diag::err_invalid_conversion_between_vector_and_scalar)
3680 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003681
3682 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3683 ImpCastExprToType(CastExpr, DestElemTy,
3684 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003685
3686 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003687 return false;
3688}
3689
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003690Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003691Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003692 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003693 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003695 assert((Ty != 0) && (Op.get() != 0) &&
3696 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003697
Nate Begeman2ef13e52009-08-10 23:49:36 +00003698 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003699 //FIXME: Preserve type source info.
3700 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Nate Begeman2ef13e52009-08-10 23:49:36 +00003702 // If the Expr being casted is a ParenListExpr, handle it specially.
3703 if (isa<ParenListExpr>(castExpr))
3704 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003705 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003706 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003707 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003708 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003709
3710 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003711 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003712 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003713
Anders Carlsson0aebc812009-09-09 21:33:21 +00003714 if (CastArg.isInvalid())
3715 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003716
Anders Carlsson0aebc812009-09-09 21:33:21 +00003717 castExpr = CastArg.takeAs<Expr>();
3718 } else {
3719 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003720 }
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003722 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003723 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003724 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003725}
3726
Nate Begeman2ef13e52009-08-10 23:49:36 +00003727/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3728/// of comma binary operators.
3729Action::OwningExprResult
3730Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3731 Expr *expr = EA.takeAs<Expr>();
3732 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3733 if (!E)
3734 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003735
Nate Begeman2ef13e52009-08-10 23:49:36 +00003736 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Nate Begeman2ef13e52009-08-10 23:49:36 +00003738 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3739 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3740 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003741
Nate Begeman2ef13e52009-08-10 23:49:36 +00003742 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3743}
3744
3745Action::OwningExprResult
3746Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3747 SourceLocation RParenLoc, ExprArg Op,
3748 QualType Ty) {
3749 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003750
3751 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003752 // then handle it as such.
3753 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3754 if (PE->getNumExprs() == 0) {
3755 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3756 return ExprError();
3757 }
3758
3759 llvm::SmallVector<Expr *, 8> initExprs;
3760 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3761 initExprs.push_back(PE->getExpr(i));
3762
3763 // FIXME: This means that pretty-printing the final AST will produce curly
3764 // braces instead of the original commas.
3765 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003766 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003767 initExprs.size(), RParenLoc);
3768 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003769 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003770 Owned(E));
3771 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003772 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003773 // sequence of BinOp comma operators.
3774 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3775 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3776 }
3777}
3778
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003779Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003780 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003781 MultiExprArg Val,
3782 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003783 unsigned nexprs = Val.size();
3784 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003785 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3786 Expr *expr;
3787 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3788 expr = new (Context) ParenExpr(L, R, exprs[0]);
3789 else
3790 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003791 return Owned(expr);
3792}
3793
Sebastian Redl28507842009-02-26 14:39:58 +00003794/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3795/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003796/// C99 6.5.15
3797QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3798 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003799 // C++ is sufficiently different to merit its own checker.
3800 if (getLangOptions().CPlusPlus)
3801 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3802
John McCallb13c87f2009-11-05 09:23:39 +00003803 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3804
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003805 UsualUnaryConversions(Cond);
3806 UsualUnaryConversions(LHS);
3807 UsualUnaryConversions(RHS);
3808 QualType CondTy = Cond->getType();
3809 QualType LHSTy = LHS->getType();
3810 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003811
Reid Spencer5f016e22007-07-11 17:01:13 +00003812 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003813 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3814 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3815 << CondTy;
3816 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003817 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003818
Chris Lattner70d67a92008-01-06 22:42:25 +00003819 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003820 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3821 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003822
Chris Lattner70d67a92008-01-06 22:42:25 +00003823 // If both operands have arithmetic type, do the usual arithmetic conversions
3824 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003825 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3826 UsualArithmeticConversions(LHS, RHS);
3827 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003828 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003829
Chris Lattner70d67a92008-01-06 22:42:25 +00003830 // If both operands are the same structure or union type, the result is that
3831 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003832 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3833 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003834 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003835 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003836 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003837 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003838 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003839 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003840
Chris Lattner70d67a92008-01-06 22:42:25 +00003841 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003842 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003843 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3844 if (!LHSTy->isVoidType())
3845 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3846 << RHS->getSourceRange();
3847 if (!RHSTy->isVoidType())
3848 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3849 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003850 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3851 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003852 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003853 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003854 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3855 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003856 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003857 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003858 // promote the null to a pointer.
3859 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003860 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003861 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003862 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003863 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003864 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003865 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003866 }
David Chisnall0f436562009-08-17 16:35:33 +00003867 // Handle things like Class and struct objc_class*. Here we case the result
3868 // to the pseudo-builtin, because that will be implicitly cast back to the
3869 // redefinition type if an attempt is made to access its fields.
3870 if (LHSTy->isObjCClassType() &&
3871 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003872 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003873 return LHSTy;
3874 }
3875 if (RHSTy->isObjCClassType() &&
3876 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003877 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003878 return RHSTy;
3879 }
3880 // And the same for struct objc_object* / id
3881 if (LHSTy->isObjCIdType() &&
3882 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003883 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003884 return LHSTy;
3885 }
3886 if (RHSTy->isObjCIdType() &&
3887 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003888 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003889 return RHSTy;
3890 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003891 // And the same for struct objc_selector* / SEL
3892 if (Context.isObjCSelType(LHSTy) &&
3893 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3894 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3895 return LHSTy;
3896 }
3897 if (Context.isObjCSelType(RHSTy) &&
3898 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3899 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3900 return RHSTy;
3901 }
Steve Naroff7154a772009-07-01 14:36:47 +00003902 // Handle block pointer types.
3903 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3904 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3905 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3906 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003907 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3908 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003909 return destType;
3910 }
3911 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3912 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3913 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003914 }
Steve Naroff7154a772009-07-01 14:36:47 +00003915 // We have 2 block pointer types.
3916 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3917 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003918 return LHSTy;
3919 }
Steve Naroff7154a772009-07-01 14:36:47 +00003920 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003921 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3922 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003923
Steve Naroff7154a772009-07-01 14:36:47 +00003924 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3925 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003926 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3927 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3928 // In this situation, we assume void* type. No especially good
3929 // reason, but this is what gcc does, and we do have to pick
3930 // to get a consistent AST.
3931 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003932 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3933 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003934 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003935 }
Steve Naroff7154a772009-07-01 14:36:47 +00003936 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003937 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3938 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003939 return LHSTy;
3940 }
Steve Naroff7154a772009-07-01 14:36:47 +00003941 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003942 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003943
Steve Naroff7154a772009-07-01 14:36:47 +00003944 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3945 // Two identical object pointer types are always compatible.
3946 return LHSTy;
3947 }
John McCall183700f2009-09-21 23:43:11 +00003948 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3949 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003950 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003951
Steve Naroff7154a772009-07-01 14:36:47 +00003952 // If both operands are interfaces and either operand can be
3953 // assigned to the other, use that type as the composite
3954 // type. This allows
3955 // xxx ? (A*) a : (B*) b
3956 // where B is a subclass of A.
3957 //
3958 // Additionally, as for assignment, if either type is 'id'
3959 // allow silent coercion. Finally, if the types are
3960 // incompatible then make sure to use 'id' as the composite
3961 // type so the result is acceptable for sending messages to.
3962
3963 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3964 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003965 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003966 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003967 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003968 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003969 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003970 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003971 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003972 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003973 // GCC allows qualified id and any Objective-C type to devolve to
3974 // id. Currently localizing to here until clear this should be
3975 // part of ObjCQualifiedIdTypesAreCompatible.
3976 compositeType = Context.getObjCIdType();
3977 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003978 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003979 } else if (!(compositeType =
3980 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3981 ;
3982 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003983 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3984 << LHSTy << RHSTy
3985 << LHS->getSourceRange() << RHS->getSourceRange();
3986 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003987 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3988 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003989 return incompatTy;
3990 }
3991 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003992 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3993 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003994 return compositeType;
3995 }
Steve Naroffc715e782009-07-29 15:09:39 +00003996 // Check Objective-C object pointer types and 'void *'
3997 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003998 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003999 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00004000 QualType destPointee
4001 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00004002 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004003 // Add qualifiers if necessary.
4004 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4005 // Promote to void*.
4006 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00004007 return destType;
4008 }
4009 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00004010 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004011 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00004012 QualType destPointee
4013 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00004014 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004015 // Add qualifiers if necessary.
4016 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4017 // Promote to void*.
4018 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00004019 return destType;
4020 }
Steve Naroff7154a772009-07-01 14:36:47 +00004021 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4022 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4023 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004024 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4025 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004026
4027 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4028 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4029 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004030 QualType destPointee
4031 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004032 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004033 // Add qualifiers if necessary.
4034 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4035 // Promote to void*.
4036 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004037 return destType;
4038 }
4039 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004040 QualType destPointee
4041 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004042 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004043 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004044 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004045 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004046 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004047 return destType;
4048 }
4049
4050 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4051 // Two identical pointer types are always compatible.
4052 return LHSTy;
4053 }
4054 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4055 rhptee.getUnqualifiedType())) {
4056 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4057 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4058 // In this situation, we assume void* type. No especially good
4059 // reason, but this is what gcc does, and we do have to pick
4060 // to get a consistent AST.
4061 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004062 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4063 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004064 return incompatTy;
4065 }
4066 // The pointer types are compatible.
4067 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4068 // differently qualified versions of compatible types, the result type is
4069 // a pointer to an appropriately qualified version of the *composite*
4070 // type.
4071 // FIXME: Need to calculate the composite type.
4072 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004073 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4074 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004075 return LHSTy;
4076 }
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Steve Naroff7154a772009-07-01 14:36:47 +00004078 // GCC compatibility: soften pointer/integer mismatch.
4079 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4080 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4081 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004082 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004083 return RHSTy;
4084 }
4085 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4086 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4087 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004088 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004089 return LHSTy;
4090 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004091
Chris Lattner70d67a92008-01-06 22:42:25 +00004092 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004093 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4094 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004095 return QualType();
4096}
4097
Steve Narofff69936d2007-09-16 03:34:24 +00004098/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004099/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004100Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4101 SourceLocation ColonLoc,
4102 ExprArg Cond, ExprArg LHS,
4103 ExprArg RHS) {
4104 Expr *CondExpr = (Expr *) Cond.get();
4105 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004106
4107 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4108 // was the condition.
4109 bool isLHSNull = LHSExpr == 0;
4110 if (isLHSNull)
4111 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004112
4113 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004114 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004115 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004116 return ExprError();
4117
4118 Cond.release();
4119 LHS.release();
4120 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004121 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004122 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004123 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004124}
4125
Reid Spencer5f016e22007-07-11 17:01:13 +00004126// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004127// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004128// routine is it effectively iqnores the qualifiers on the top level pointee.
4129// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4130// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004131Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004132Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4133 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004134
David Chisnall0f436562009-08-17 16:35:33 +00004135 if ((lhsType->isObjCClassType() &&
4136 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4137 (rhsType->isObjCClassType() &&
4138 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4139 return Compatible;
4140 }
4141
Reid Spencer5f016e22007-07-11 17:01:13 +00004142 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004143 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4144 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004145
Reid Spencer5f016e22007-07-11 17:01:13 +00004146 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004147 lhptee = Context.getCanonicalType(lhptee);
4148 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004149
Chris Lattner5cf216b2008-01-04 18:04:52 +00004150 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004151
4152 // C99 6.5.16.1p1: This following citation is common to constraints
4153 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4154 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004155 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004156 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004157 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004158
Mike Stumpeed9cac2009-02-19 03:04:26 +00004159 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4160 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004161 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004162 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004163 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004164 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004165
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004166 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004167 assert(rhptee->isFunctionType());
4168 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004169 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004170
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004171 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004172 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004173 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004174
4175 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004176 assert(lhptee->isFunctionType());
4177 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004178 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004179 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004180 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004181 lhptee = lhptee.getUnqualifiedType();
4182 rhptee = rhptee.getUnqualifiedType();
4183 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4184 // Check if the pointee types are compatible ignoring the sign.
4185 // We explicitly check for char so that we catch "char" vs
4186 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004187 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004188 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004189 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004190 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004191
4192 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004193 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004194 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004195 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004196
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004197 if (lhptee == rhptee) {
4198 // Types are compatible ignoring the sign. Qualifier incompatibility
4199 // takes priority over sign incompatibility because the sign
4200 // warning can be disabled.
4201 if (ConvTy != Compatible)
4202 return ConvTy;
4203 return IncompatiblePointerSign;
4204 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004205
4206 // If we are a multi-level pointer, it's possible that our issue is simply
4207 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4208 // the eventual target type is the same and the pointers have the same
4209 // level of indirection, this must be the issue.
4210 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4211 do {
4212 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4213 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4214
4215 lhptee = Context.getCanonicalType(lhptee);
4216 rhptee = Context.getCanonicalType(rhptee);
4217 } while (lhptee->isPointerType() && rhptee->isPointerType());
4218
Douglas Gregora4923eb2009-11-16 21:35:15 +00004219 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004220 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004221 }
4222
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004223 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004224 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004225 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004226 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004227}
4228
Steve Naroff1c7d0672008-09-04 15:10:53 +00004229/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4230/// block pointer types are compatible or whether a block and normal pointer
4231/// are compatible. It is more restrict than comparing two function pointer
4232// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004233Sema::AssignConvertType
4234Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004235 QualType rhsType) {
4236 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004237
Steve Naroff1c7d0672008-09-04 15:10:53 +00004238 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004239 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4240 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004241
Steve Naroff1c7d0672008-09-04 15:10:53 +00004242 // make sure we operate on the canonical type
4243 lhptee = Context.getCanonicalType(lhptee);
4244 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004245
Steve Naroff1c7d0672008-09-04 15:10:53 +00004246 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004247
Steve Naroff1c7d0672008-09-04 15:10:53 +00004248 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004249 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004250 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004251
Eli Friedman26784c12009-06-08 05:08:54 +00004252 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004253 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004254 return ConvTy;
4255}
4256
Mike Stumpeed9cac2009-02-19 03:04:26 +00004257/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4258/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004259/// pointers. Here are some objectionable examples that GCC considers warnings:
4260///
4261/// int a, *pint;
4262/// short *pshort;
4263/// struct foo *pfoo;
4264///
4265/// pint = pshort; // warning: assignment from incompatible pointer type
4266/// a = pint; // warning: assignment makes integer from pointer without a cast
4267/// pint = a; // warning: assignment makes pointer from integer without a cast
4268/// pint = pfoo; // warning: assignment from incompatible pointer type
4269///
4270/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004271/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004272///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004273Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004274Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004275 // Get canonical types. We're not formatting these types, just comparing
4276 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004277 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4278 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004279
4280 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004281 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004282
David Chisnall0f436562009-08-17 16:35:33 +00004283 if ((lhsType->isObjCClassType() &&
4284 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4285 (rhsType->isObjCClassType() &&
4286 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4287 return Compatible;
4288 }
4289
Douglas Gregor9d293df2008-10-28 00:22:11 +00004290 // If the left-hand side is a reference type, then we are in a
4291 // (rare!) case where we've allowed the use of references in C,
4292 // e.g., as a parameter type in a built-in function. In this case,
4293 // just make sure that the type referenced is compatible with the
4294 // right-hand side type. The caller is responsible for adjusting
4295 // lhsType so that the resulting expression does not have reference
4296 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004297 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004298 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004299 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004300 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004301 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004302 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4303 // to the same ExtVector type.
4304 if (lhsType->isExtVectorType()) {
4305 if (rhsType->isExtVectorType())
4306 return lhsType == rhsType ? Compatible : Incompatible;
4307 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4308 return Compatible;
4309 }
Mike Stump1eb44332009-09-09 15:08:12 +00004310
Nate Begemanbe2341d2008-07-14 18:02:46 +00004311 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004312 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004313 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004314 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004315 if (getLangOptions().LaxVectorConversions &&
4316 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004317 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004318 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004319 }
4320 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004321 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004322
Chris Lattnere8b3e962008-01-04 23:32:24 +00004323 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004324 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004325
Chris Lattner78eca282008-04-07 06:49:41 +00004326 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004327 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004328 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004329
Chris Lattner78eca282008-04-07 06:49:41 +00004330 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004331 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004332
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004333 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004334 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004335 if (lhsType->isVoidPointerType()) // an exception to the rule.
4336 return Compatible;
4337 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004338 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004339 if (rhsType->getAs<BlockPointerType>()) {
4340 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004341 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004342
4343 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004344 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004345 return Compatible;
4346 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004347 return Incompatible;
4348 }
4349
4350 if (isa<BlockPointerType>(lhsType)) {
4351 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004352 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004353
Steve Naroffb4406862008-09-29 18:10:17 +00004354 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004355 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004356 return Compatible;
4357
Steve Naroff1c7d0672008-09-04 15:10:53 +00004358 if (rhsType->isBlockPointerType())
4359 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004360
Ted Kremenek6217b802009-07-29 21:53:49 +00004361 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004362 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004363 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004364 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004365 return Incompatible;
4366 }
4367
Steve Naroff14108da2009-07-10 23:34:53 +00004368 if (isa<ObjCObjectPointerType>(lhsType)) {
4369 if (rhsType->isIntegerType())
4370 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004372 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004373 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004374 if (rhsType->isVoidPointerType()) // an exception to the rule.
4375 return Compatible;
4376 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004377 }
4378 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004379 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4380 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004381 if (Context.typesAreCompatible(lhsType, rhsType))
4382 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00004383 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4384 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004385 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004386 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004387 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004388 if (RHSPT->getPointeeType()->isVoidType())
4389 return Compatible;
4390 }
4391 // Treat block pointers as objects.
4392 if (rhsType->isBlockPointerType())
4393 return Compatible;
4394 return Incompatible;
4395 }
Chris Lattner78eca282008-04-07 06:49:41 +00004396 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004397 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004398 if (lhsType == Context.BoolTy)
4399 return Compatible;
4400
4401 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004402 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004403
Mike Stumpeed9cac2009-02-19 03:04:26 +00004404 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004405 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004406
4407 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004408 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004409 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004410 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004411 }
Steve Naroff14108da2009-07-10 23:34:53 +00004412 if (isa<ObjCObjectPointerType>(rhsType)) {
4413 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4414 if (lhsType == Context.BoolTy)
4415 return Compatible;
4416
4417 if (lhsType->isIntegerType())
4418 return PointerToInt;
4419
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004420 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004421 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004422 if (lhsType->isVoidPointerType()) // an exception to the rule.
4423 return Compatible;
4424 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004425 }
4426 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004427 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004428 return Compatible;
4429 return Incompatible;
4430 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004431
Chris Lattnerfc144e22008-01-04 23:18:45 +00004432 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004433 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004434 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004435 }
4436 return Incompatible;
4437}
4438
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004439/// \brief Constructs a transparent union from an expression that is
4440/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004441static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004442 QualType UnionType, FieldDecl *Field) {
4443 // Build an initializer list that designates the appropriate member
4444 // of the transparent union.
4445 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4446 &E, 1,
4447 SourceLocation());
4448 Initializer->setType(UnionType);
4449 Initializer->setInitializedFieldInUnion(Field);
4450
4451 // Build a compound literal constructing a value of the transparent
4452 // union type from this initializer list.
4453 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4454 false);
4455}
4456
4457Sema::AssignConvertType
4458Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4459 QualType FromType = rExpr->getType();
4460
Mike Stump1eb44332009-09-09 15:08:12 +00004461 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004462 // transparent_union GCC extension.
4463 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004464 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004465 return Incompatible;
4466
4467 // The field to initialize within the transparent union.
4468 RecordDecl *UD = UT->getDecl();
4469 FieldDecl *InitField = 0;
4470 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004471 for (RecordDecl::field_iterator it = UD->field_begin(),
4472 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004473 it != itend; ++it) {
4474 if (it->getType()->isPointerType()) {
4475 // If the transparent union contains a pointer type, we allow:
4476 // 1) void pointer
4477 // 2) null pointer constant
4478 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004479 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004480 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004481 InitField = *it;
4482 break;
4483 }
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Douglas Gregorce940492009-09-25 04:25:58 +00004485 if (rExpr->isNullPointerConstant(Context,
4486 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004487 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004488 InitField = *it;
4489 break;
4490 }
4491 }
4492
4493 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4494 == Compatible) {
4495 InitField = *it;
4496 break;
4497 }
4498 }
4499
4500 if (!InitField)
4501 return Incompatible;
4502
4503 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4504 return Compatible;
4505}
4506
Chris Lattner5cf216b2008-01-04 18:04:52 +00004507Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004508Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004509 if (getLangOptions().CPlusPlus) {
4510 if (!lhsType->isRecordType()) {
4511 // C++ 5.17p3: If the left operand is not of class type, the
4512 // expression is implicitly converted (C++ 4) to the
4513 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004514 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4515 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004516 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004517 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004518 }
4519
4520 // FIXME: Currently, we fall through and treat C++ classes like C
4521 // structures.
4522 }
4523
Steve Naroff529a4ad2007-11-27 17:58:44 +00004524 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4525 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004526 if ((lhsType->isPointerType() ||
4527 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004528 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004529 && rExpr->isNullPointerConstant(Context,
4530 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004531 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004532 return Compatible;
4533 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004534
Chris Lattner943140e2007-10-16 02:55:40 +00004535 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004536 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004537 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004538 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004539 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004540 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004541 if (!lhsType->isReferenceType())
4542 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004543
Chris Lattner5cf216b2008-01-04 18:04:52 +00004544 Sema::AssignConvertType result =
4545 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004546
Steve Narofff1120de2007-08-24 22:33:52 +00004547 // C99 6.5.16.1p2: The value of the right operand is converted to the
4548 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004549 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4550 // so that we can use references in built-in functions even in C.
4551 // The getNonReferenceType() call makes sure that the resulting expression
4552 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004553 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004554 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4555 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004556 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004557}
4558
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004559QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004560 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004561 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004562 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004563 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004564}
4565
Mike Stumpeed9cac2009-02-19 03:04:26 +00004566inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004567 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004568 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004569 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004570 QualType lhsType =
4571 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4572 QualType rhsType =
4573 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004574
Nate Begemanbe2341d2008-07-14 18:02:46 +00004575 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004576 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004577 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004578
Nate Begemanbe2341d2008-07-14 18:02:46 +00004579 // Handle the case of a vector & extvector type of the same size and element
4580 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004581 if (getLangOptions().LaxVectorConversions) {
4582 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004583 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4584 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004585 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004586 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004587 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004588 }
4589 }
4590 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004591
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004592 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4593 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4594 bool swapped = false;
4595 if (rhsType->isExtVectorType()) {
4596 swapped = true;
4597 std::swap(rex, lex);
4598 std::swap(rhsType, lhsType);
4599 }
Mike Stump1eb44332009-09-09 15:08:12 +00004600
Nate Begemandde25982009-06-28 19:12:57 +00004601 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004602 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004603 QualType EltTy = LV->getElementType();
4604 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4605 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004606 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004607 if (swapped) std::swap(rex, lex);
4608 return lhsType;
4609 }
4610 }
4611 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4612 rhsType->isRealFloatingType()) {
4613 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004614 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004615 if (swapped) std::swap(rex, lex);
4616 return lhsType;
4617 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004618 }
4619 }
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Nate Begemandde25982009-06-28 19:12:57 +00004621 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004622 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004623 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004624 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004625 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004626}
4627
Reid Spencer5f016e22007-07-11 17:01:13 +00004628inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004629 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004630 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004631 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004632
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004633 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004634
Steve Naroffa4332e22007-07-17 00:58:39 +00004635 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004636 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004637 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004638}
4639
4640inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004641 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004642 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4643 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4644 return CheckVectorOperands(Loc, lex, rex);
4645 return InvalidOperands(Loc, lex, rex);
4646 }
Steve Naroff90045e82007-07-13 23:32:42 +00004647
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004648 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004649
Steve Naroffa4332e22007-07-17 00:58:39 +00004650 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004651 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004652 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004653}
4654
4655inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004656 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004657 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4658 QualType compType = CheckVectorOperands(Loc, lex, rex);
4659 if (CompLHSTy) *CompLHSTy = compType;
4660 return compType;
4661 }
Steve Naroff49b45262007-07-13 16:58:59 +00004662
Eli Friedmanab3a8522009-03-28 01:22:36 +00004663 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004664
Reid Spencer5f016e22007-07-11 17:01:13 +00004665 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004666 if (lex->getType()->isArithmeticType() &&
4667 rex->getType()->isArithmeticType()) {
4668 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004669 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004671
Eli Friedmand72d16e2008-05-18 18:08:51 +00004672 // Put any potential pointer into PExp
4673 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004674 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004675 std::swap(PExp, IExp);
4676
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004677 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Eli Friedmand72d16e2008-05-18 18:08:51 +00004679 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004680 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Chris Lattnerb5f15622009-04-24 23:50:08 +00004682 // Check for arithmetic on pointers to incomplete types.
4683 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004684 if (getLangOptions().CPlusPlus) {
4685 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004686 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004687 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004688 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004689
4690 // GNU extension: arithmetic on pointer to void
4691 Diag(Loc, diag::ext_gnu_void_ptr)
4692 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004693 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004694 if (getLangOptions().CPlusPlus) {
4695 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4696 << lex->getType() << lex->getSourceRange();
4697 return QualType();
4698 }
4699
4700 // GNU extension: arithmetic on pointer to function
4701 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4702 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004703 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004704 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004705 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004706 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004707 PExp->getType()->isObjCObjectPointerType()) &&
4708 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004709 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4710 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004711 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004712 return QualType();
4713 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004714 // Diagnose bad cases where we step over interface counts.
4715 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4716 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4717 << PointeeTy << PExp->getSourceRange();
4718 return QualType();
4719 }
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Eli Friedmanab3a8522009-03-28 01:22:36 +00004721 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004722 QualType LHSTy = Context.isPromotableBitField(lex);
4723 if (LHSTy.isNull()) {
4724 LHSTy = lex->getType();
4725 if (LHSTy->isPromotableIntegerType())
4726 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004727 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004728 *CompLHSTy = LHSTy;
4729 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004730 return PExp->getType();
4731 }
4732 }
4733
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004734 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004735}
4736
Chris Lattnereca7be62008-04-07 05:30:13 +00004737// C99 6.5.6
4738QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004739 SourceLocation Loc, QualType* CompLHSTy) {
4740 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4741 QualType compType = CheckVectorOperands(Loc, lex, rex);
4742 if (CompLHSTy) *CompLHSTy = compType;
4743 return compType;
4744 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004745
Eli Friedmanab3a8522009-03-28 01:22:36 +00004746 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004747
Chris Lattner6e4ab612007-12-09 21:53:25 +00004748 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004749
Chris Lattner6e4ab612007-12-09 21:53:25 +00004750 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004751 if (lex->getType()->isArithmeticType()
4752 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004753 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004754 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004755 }
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Chris Lattner6e4ab612007-12-09 21:53:25 +00004757 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004758 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004759 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004760
Douglas Gregore7450f52009-03-24 19:52:54 +00004761 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004762
Douglas Gregore7450f52009-03-24 19:52:54 +00004763 bool ComplainAboutVoid = false;
4764 Expr *ComplainAboutFunc = 0;
4765 if (lpointee->isVoidType()) {
4766 if (getLangOptions().CPlusPlus) {
4767 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4768 << lex->getSourceRange() << rex->getSourceRange();
4769 return QualType();
4770 }
4771
4772 // GNU C extension: arithmetic on pointer to void
4773 ComplainAboutVoid = true;
4774 } else if (lpointee->isFunctionType()) {
4775 if (getLangOptions().CPlusPlus) {
4776 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004777 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004778 return QualType();
4779 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004780
4781 // GNU C extension: arithmetic on pointer to function
4782 ComplainAboutFunc = lex;
4783 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004784 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004785 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004786 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004787 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004788 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004789
Chris Lattnerb5f15622009-04-24 23:50:08 +00004790 // Diagnose bad cases where we step over interface counts.
4791 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4792 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4793 << lpointee << lex->getSourceRange();
4794 return QualType();
4795 }
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Chris Lattner6e4ab612007-12-09 21:53:25 +00004797 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004798 if (rex->getType()->isIntegerType()) {
4799 if (ComplainAboutVoid)
4800 Diag(Loc, diag::ext_gnu_void_ptr)
4801 << lex->getSourceRange() << rex->getSourceRange();
4802 if (ComplainAboutFunc)
4803 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004804 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004805 << ComplainAboutFunc->getSourceRange();
4806
Eli Friedmanab3a8522009-03-28 01:22:36 +00004807 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004808 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004809 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004810
Chris Lattner6e4ab612007-12-09 21:53:25 +00004811 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004812 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004813 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004814
Douglas Gregore7450f52009-03-24 19:52:54 +00004815 // RHS must be a completely-type object type.
4816 // Handle the GNU void* extension.
4817 if (rpointee->isVoidType()) {
4818 if (getLangOptions().CPlusPlus) {
4819 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4820 << lex->getSourceRange() << rex->getSourceRange();
4821 return QualType();
4822 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004823
Douglas Gregore7450f52009-03-24 19:52:54 +00004824 ComplainAboutVoid = true;
4825 } else if (rpointee->isFunctionType()) {
4826 if (getLangOptions().CPlusPlus) {
4827 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004828 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004829 return QualType();
4830 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004831
4832 // GNU extension: arithmetic on pointer to function
4833 if (!ComplainAboutFunc)
4834 ComplainAboutFunc = rex;
4835 } else if (!rpointee->isDependentType() &&
4836 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004837 PDiag(diag::err_typecheck_sub_ptr_object)
4838 << rex->getSourceRange()
4839 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004840 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004841
Eli Friedman88d936b2009-05-16 13:54:38 +00004842 if (getLangOptions().CPlusPlus) {
4843 // Pointee types must be the same: C++ [expr.add]
4844 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4845 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4846 << lex->getType() << rex->getType()
4847 << lex->getSourceRange() << rex->getSourceRange();
4848 return QualType();
4849 }
4850 } else {
4851 // Pointee types must be compatible C99 6.5.6p3
4852 if (!Context.typesAreCompatible(
4853 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4854 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4855 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4856 << lex->getType() << rex->getType()
4857 << lex->getSourceRange() << rex->getSourceRange();
4858 return QualType();
4859 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004860 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004861
Douglas Gregore7450f52009-03-24 19:52:54 +00004862 if (ComplainAboutVoid)
4863 Diag(Loc, diag::ext_gnu_void_ptr)
4864 << lex->getSourceRange() << rex->getSourceRange();
4865 if (ComplainAboutFunc)
4866 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004867 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004868 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004869
4870 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004871 return Context.getPointerDiffType();
4872 }
4873 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004874
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004875 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004876}
4877
Chris Lattnereca7be62008-04-07 05:30:13 +00004878// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004879QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004880 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004881 // C99 6.5.7p2: Each of the operands shall have integer type.
4882 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004883 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004884
Nate Begeman2207d792009-10-25 02:26:48 +00004885 // Vector shifts promote their scalar inputs to vector type.
4886 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4887 return CheckVectorOperands(Loc, lex, rex);
4888
Chris Lattnerca5eede2007-12-12 05:47:28 +00004889 // Shifts don't perform usual arithmetic conversions, they just do integer
4890 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004891 QualType LHSTy = Context.isPromotableBitField(lex);
4892 if (LHSTy.isNull()) {
4893 LHSTy = lex->getType();
4894 if (LHSTy->isPromotableIntegerType())
4895 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004896 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004897 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004898 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004899
Chris Lattnerca5eede2007-12-12 05:47:28 +00004900 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004901
Ryan Flynnd0439682009-08-07 16:20:20 +00004902 // Sanity-check shift operands
4903 llvm::APSInt Right;
4904 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004905 if (!rex->isValueDependent() &&
4906 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004907 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004908 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4909 else {
4910 llvm::APInt LeftBits(Right.getBitWidth(),
4911 Context.getTypeSize(lex->getType()));
4912 if (Right.uge(LeftBits))
4913 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4914 }
4915 }
4916
Chris Lattnerca5eede2007-12-12 05:47:28 +00004917 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004918 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004919}
4920
John McCall5dbad3d2009-11-06 08:49:08 +00004921/// \brief Implements -Wsign-compare.
4922///
4923/// \param lex the left-hand expression
4924/// \param rex the right-hand expression
4925/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004926/// \param Equality whether this is an "equality-like" join, which
4927/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004928void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004929 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004930 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004931 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004932 return;
4933
John McCall45aa4552009-11-05 00:40:04 +00004934 QualType lt = lex->getType(), rt = rex->getType();
4935
4936 // Only warn if both operands are integral.
4937 if (!lt->isIntegerType() || !rt->isIntegerType())
4938 return;
4939
Sebastian Redl732429c2009-11-05 21:09:23 +00004940 // If either expression is value-dependent, don't warn. We'll get another
4941 // chance at instantiation time.
4942 if (lex->isValueDependent() || rex->isValueDependent())
4943 return;
4944
John McCall45aa4552009-11-05 00:40:04 +00004945 // The rule is that the signed operand becomes unsigned, so isolate the
4946 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004947 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004948 if (lt->isSignedIntegerType()) {
4949 if (rt->isSignedIntegerType()) return;
4950 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004951 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004952 } else {
4953 if (!rt->isSignedIntegerType()) return;
4954 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004955 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004956 }
4957
John McCall5dbad3d2009-11-06 08:49:08 +00004958 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004959 // then (1) the result type will be signed and (2) the unsigned
4960 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004961 // of the comparison will be exact.
4962 if (Context.getIntWidth(signedOperand->getType()) >
4963 Context.getIntWidth(unsignedOperand->getType()))
4964 return;
4965
John McCall45aa4552009-11-05 00:40:04 +00004966 // If the value is a non-negative integer constant, then the
4967 // signed->unsigned conversion won't change it.
4968 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004969 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004970 assert(value.isSigned() && "result of signed expression not signed");
4971
4972 if (value.isNonNegative())
4973 return;
4974 }
4975
John McCall5dbad3d2009-11-06 08:49:08 +00004976 if (Equality) {
4977 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004978 // constant which cannot collide with a overflowed signed operand,
4979 // then reinterpreting the signed operand as unsigned will not
4980 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004981 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4982 assert(!value.isSigned() && "result of unsigned expression is signed");
4983
4984 // 2's complement: test the top bit.
4985 if (value.isNonNegative())
4986 return;
4987 }
4988 }
4989
John McCallb13c87f2009-11-05 09:23:39 +00004990 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004991 << lex->getType() << rex->getType()
4992 << lex->getSourceRange() << rex->getSourceRange();
4993}
4994
Douglas Gregor0c6db942009-05-04 06:07:12 +00004995// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004996QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004997 unsigned OpaqueOpc, bool isRelational) {
4998 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4999
Nate Begemanbe2341d2008-07-14 18:02:46 +00005000 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005001 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005002
John McCall5dbad3d2009-11-06 08:49:08 +00005003 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5004 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005005
Chris Lattnera5937dd2007-08-26 01:18:55 +00005006 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005007 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5008 UsualArithmeticConversions(lex, rex);
5009 else {
5010 UsualUnaryConversions(lex);
5011 UsualUnaryConversions(rex);
5012 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005013 QualType lType = lex->getType();
5014 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005015
Mike Stumpaf199f32009-05-07 18:43:07 +00005016 if (!lType->isFloatingType()
5017 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005018 // For non-floating point types, check for self-comparisons of the form
5019 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5020 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005021 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005022 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005023 Expr *LHSStripped = lex->IgnoreParens();
5024 Expr *RHSStripped = rex->IgnoreParens();
5025 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5026 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005027 if (DRL->getDecl() == DRR->getDecl() &&
5028 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005029 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005030
Chris Lattner55660a72009-03-08 19:39:53 +00005031 if (isa<CastExpr>(LHSStripped))
5032 LHSStripped = LHSStripped->IgnoreParenCasts();
5033 if (isa<CastExpr>(RHSStripped))
5034 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005035
Chris Lattner55660a72009-03-08 19:39:53 +00005036 // Warn about comparisons against a string constant (unless the other
5037 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005038 Expr *literalString = 0;
5039 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005040 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005041 !RHSStripped->isNullPointerConstant(Context,
5042 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005043 literalString = lex;
5044 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005045 } else if ((isa<StringLiteral>(RHSStripped) ||
5046 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005047 !LHSStripped->isNullPointerConstant(Context,
5048 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005049 literalString = rex;
5050 literalStringStripped = RHSStripped;
5051 }
5052
5053 if (literalString) {
5054 std::string resultComparison;
5055 switch (Opc) {
5056 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5057 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5058 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5059 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5060 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5061 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5062 default: assert(false && "Invalid comparison operator");
5063 }
5064 Diag(Loc, diag::warn_stringcompare)
5065 << isa<ObjCEncodeExpr>(literalStringStripped)
5066 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005067 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5068 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5069 "strcmp(")
5070 << CodeModificationHint::CreateInsertion(
5071 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005072 resultComparison);
5073 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005074 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005075
Douglas Gregor447b69e2008-11-19 03:25:36 +00005076 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00005077 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005078
Chris Lattnera5937dd2007-08-26 01:18:55 +00005079 if (isRelational) {
5080 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005081 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005082 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005083 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005084 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00005085 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005086 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00005087 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005088
Chris Lattnera5937dd2007-08-26 01:18:55 +00005089 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005090 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005091 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005092
Douglas Gregorce940492009-09-25 04:25:58 +00005093 bool LHSIsNull = lex->isNullPointerConstant(Context,
5094 Expr::NPC_ValueDependentIsNull);
5095 bool RHSIsNull = rex->isNullPointerConstant(Context,
5096 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005097
Chris Lattnera5937dd2007-08-26 01:18:55 +00005098 // All of the following pointer related warnings are GCC extensions, except
5099 // when handling null pointer constants. One day, we can consider making them
5100 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005101 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005102 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005103 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005104 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005105 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005106
Douglas Gregor0c6db942009-05-04 06:07:12 +00005107 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005108 if (LCanPointeeTy == RCanPointeeTy)
5109 return ResultTy;
5110
Douglas Gregor0c6db942009-05-04 06:07:12 +00005111 // C++ [expr.rel]p2:
5112 // [...] Pointer conversions (4.10) and qualification
5113 // conversions (4.4) are performed on pointer operands (or on
5114 // a pointer operand and a null pointer constant) to bring
5115 // them to their composite pointer type. [...]
5116 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005117 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005118 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005119 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005120 if (T.isNull()) {
5121 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5122 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5123 return QualType();
5124 }
5125
Eli Friedman73c39ab2009-10-20 08:27:19 +00005126 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5127 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005128 return ResultTy;
5129 }
Eli Friedman3075e762009-08-23 00:27:47 +00005130 // C99 6.5.9p2 and C99 6.5.8p2
5131 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5132 RCanPointeeTy.getUnqualifiedType())) {
5133 // Valid unless a relational comparison of function pointers
5134 if (isRelational && LCanPointeeTy->isFunctionType()) {
5135 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5136 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5137 }
5138 } else if (!isRelational &&
5139 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5140 // Valid unless comparison between non-null pointer and function pointer
5141 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5142 && !LHSIsNull && !RHSIsNull) {
5143 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5144 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5145 }
5146 } else {
5147 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005148 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005149 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005150 }
Eli Friedman3075e762009-08-23 00:27:47 +00005151 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005152 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005153 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005154 }
Mike Stump1eb44332009-09-09 15:08:12 +00005155
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005156 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005157 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005158 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005159 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005160 (lType->isPointerType() ||
5161 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005162 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005163 return ResultTy;
5164 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005165 if (LHSIsNull &&
5166 (rType->isPointerType() ||
5167 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005168 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005169 return ResultTy;
5170 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005171
5172 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005173 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005174 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5175 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005176 // In addition, pointers to members can be compared, or a pointer to
5177 // member and a null pointer constant. Pointer to member conversions
5178 // (4.11) and qualification conversions (4.4) are performed to bring
5179 // them to a common type. If one operand is a null pointer constant,
5180 // the common type is the type of the other operand. Otherwise, the
5181 // common type is a pointer to member type similar (4.4) to the type
5182 // of one of the operands, with a cv-qualification signature (4.4)
5183 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005184 // types.
5185 QualType T = FindCompositePointerType(lex, rex);
5186 if (T.isNull()) {
5187 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5188 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5189 return QualType();
5190 }
Mike Stump1eb44332009-09-09 15:08:12 +00005191
Eli Friedman73c39ab2009-10-20 08:27:19 +00005192 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5193 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005194 return ResultTy;
5195 }
Mike Stump1eb44332009-09-09 15:08:12 +00005196
Douglas Gregor20b3e992009-08-24 17:42:35 +00005197 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005198 if (lType->isNullPtrType() && rType->isNullPtrType())
5199 return ResultTy;
5200 }
Mike Stump1eb44332009-09-09 15:08:12 +00005201
Steve Naroff1c7d0672008-09-04 15:10:53 +00005202 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005203 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005204 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5205 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005206
Steve Naroff1c7d0672008-09-04 15:10:53 +00005207 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005208 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005209 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005210 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005211 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005212 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005213 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005214 }
Steve Naroff59f53942008-09-28 01:11:11 +00005215 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005216 if (!isRelational
5217 && ((lType->isBlockPointerType() && rType->isPointerType())
5218 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005219 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005220 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005221 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005222 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005223 ->getPointeeType()->isVoidType())))
5224 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5225 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005226 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005227 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005228 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005229 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005230
Steve Naroff14108da2009-07-10 23:34:53 +00005231 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005232 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005233 const PointerType *LPT = lType->getAs<PointerType>();
5234 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005235 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005236 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005237 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005238 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005239
Steve Naroffa8069f12008-11-17 19:49:16 +00005240 if (!LPtrToVoid && !RPtrToVoid &&
5241 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005242 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005243 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005244 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005245 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005246 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005247 }
Steve Naroff14108da2009-07-10 23:34:53 +00005248 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005249 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005250 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5251 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005252 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005253 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005254 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005255 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005256 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005257 unsigned DiagID = 0;
5258 if (RHSIsNull) {
5259 if (isRelational)
5260 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5261 } else if (isRelational)
5262 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5263 else
5264 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005265
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005266 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005267 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005268 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005269 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005270 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005271 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005272 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005273 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005274 unsigned DiagID = 0;
5275 if (LHSIsNull) {
5276 if (isRelational)
5277 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5278 } else if (isRelational)
5279 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5280 else
5281 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005283 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005284 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005285 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005286 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005287 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005288 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005289 }
Steve Naroff39218df2008-09-04 16:56:14 +00005290 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005291 if (!isRelational && RHSIsNull
5292 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005293 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005294 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005295 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005296 if (!isRelational && LHSIsNull
5297 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005298 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005299 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005300 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005301 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005302}
5303
Nate Begemanbe2341d2008-07-14 18:02:46 +00005304/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005305/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005306/// like a scalar comparison, a vector comparison produces a vector of integer
5307/// types.
5308QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005309 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005310 bool isRelational) {
5311 // Check to make sure we're operating on vectors of the same type and width,
5312 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005313 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005314 if (vType.isNull())
5315 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005316
Nate Begemanbe2341d2008-07-14 18:02:46 +00005317 QualType lType = lex->getType();
5318 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005319
Nate Begemanbe2341d2008-07-14 18:02:46 +00005320 // For non-floating point types, check for self-comparisons of the form
5321 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5322 // often indicate logic errors in the program.
5323 if (!lType->isFloatingType()) {
5324 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5325 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5326 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005327 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005328 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005329
Nate Begemanbe2341d2008-07-14 18:02:46 +00005330 // Check for comparisons of floating point operands using != and ==.
5331 if (!isRelational && lType->isFloatingType()) {
5332 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005333 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005334 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005335
Nate Begemanbe2341d2008-07-14 18:02:46 +00005336 // Return the type for the comparison, which is the same as vector type for
5337 // integer vectors, or an integer type of identical size and number of
5338 // elements for floating point vectors.
5339 if (lType->isIntegerType())
5340 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005341
John McCall183700f2009-09-21 23:43:11 +00005342 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005343 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005344 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005345 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005346 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005347 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5348
Mike Stumpeed9cac2009-02-19 03:04:26 +00005349 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005350 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005351 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5352}
5353
Reid Spencer5f016e22007-07-11 17:01:13 +00005354inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005355 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005356 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005357 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005358
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005359 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005360
Steve Naroffa4332e22007-07-17 00:58:39 +00005361 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005362 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005363 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005364}
5365
5366inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005367 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005368 if (!Context.getLangOptions().CPlusPlus) {
5369 UsualUnaryConversions(lex);
5370 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005371
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005372 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5373 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005374
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005375 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005376 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005377
5378 // C++ [expr.log.and]p1
5379 // C++ [expr.log.or]p1
5380 // The operands are both implicitly converted to type bool (clause 4).
5381 StandardConversionSequence LHS;
5382 if (!IsStandardConversion(lex, Context.BoolTy,
5383 /*InOverloadResolution=*/false, LHS))
5384 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005385
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005386 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5387 "passing", /*IgnoreBaseAccess=*/false))
5388 return InvalidOperands(Loc, lex, rex);
5389
5390 StandardConversionSequence RHS;
5391 if (!IsStandardConversion(rex, Context.BoolTy,
5392 /*InOverloadResolution=*/false, RHS))
5393 return InvalidOperands(Loc, lex, rex);
5394
5395 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5396 "passing", /*IgnoreBaseAccess=*/false))
5397 return InvalidOperands(Loc, lex, rex);
5398
5399 // C++ [expr.log.and]p2
5400 // C++ [expr.log.or]p2
5401 // The result is a bool.
5402 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005403}
5404
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005405/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5406/// is a read-only property; return true if so. A readonly property expression
5407/// depends on various declarations and thus must be treated specially.
5408///
Mike Stump1eb44332009-09-09 15:08:12 +00005409static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005410 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5411 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5412 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5413 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005414 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005415 BaseType->getAsObjCInterfacePointerType())
5416 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5417 if (S.isPropertyReadonly(PDecl, IFace))
5418 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005419 }
5420 }
5421 return false;
5422}
5423
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005424/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5425/// emit an error and return true. If so, return false.
5426static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005427 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005428 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005429 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005430 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5431 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005432 if (IsLV == Expr::MLV_Valid)
5433 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005435 unsigned Diag = 0;
5436 bool NeedType = false;
5437 switch (IsLV) { // C99 6.5.16p2
5438 default: assert(0 && "Unknown result from isModifiableLvalue!");
5439 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005440 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005441 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5442 NeedType = true;
5443 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005444 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005445 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5446 NeedType = true;
5447 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005448 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005449 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5450 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005451 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005452 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5453 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005454 case Expr::MLV_IncompleteType:
5455 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005456 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005457 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5458 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005459 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005460 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5461 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005462 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005463 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5464 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005465 case Expr::MLV_ReadonlyProperty:
5466 Diag = diag::error_readonly_property_assignment;
5467 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005468 case Expr::MLV_NoSetterProperty:
5469 Diag = diag::error_nosetter_property_assignment;
5470 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005471 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005472
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005473 SourceRange Assign;
5474 if (Loc != OrigLoc)
5475 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005476 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005477 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005478 else
Mike Stump1eb44332009-09-09 15:08:12 +00005479 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005480 return true;
5481}
5482
5483
5484
5485// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005486QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5487 SourceLocation Loc,
5488 QualType CompoundType) {
5489 // Verify that LHS is a modifiable lvalue, and emit error if not.
5490 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005491 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005492
5493 QualType LHSType = LHS->getType();
5494 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005495
Chris Lattner5cf216b2008-01-04 18:04:52 +00005496 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005497 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005498 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005499 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005500 // Special case of NSObject attributes on c-style pointer types.
5501 if (ConvTy == IncompatiblePointer &&
5502 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005503 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005504 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005505 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005506 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005507
Chris Lattner2c156472008-08-21 18:04:13 +00005508 // If the RHS is a unary plus or minus, check to see if they = and + are
5509 // right next to each other. If so, the user may have typo'd "x =+ 4"
5510 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005511 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005512 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5513 RHSCheck = ICE->getSubExpr();
5514 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5515 if ((UO->getOpcode() == UnaryOperator::Plus ||
5516 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005517 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005518 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005519 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5520 // And there is a space or other character before the subexpr of the
5521 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005522 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5523 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005524 Diag(Loc, diag::warn_not_compound_assign)
5525 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5526 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005527 }
Chris Lattner2c156472008-08-21 18:04:13 +00005528 }
5529 } else {
5530 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005531 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005532 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005533
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005534 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5535 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005536 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005537
Reid Spencer5f016e22007-07-11 17:01:13 +00005538 // C99 6.5.16p3: The type of an assignment expression is the type of the
5539 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005540 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005541 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5542 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005543 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005544 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005545 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005546}
5547
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005548// C99 6.5.17
5549QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005550 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005551 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005552
5553 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5554 // incomplete in C++).
5555
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005556 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005557}
5558
Steve Naroff49b45262007-07-13 16:58:59 +00005559/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5560/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005561QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5562 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005563 if (Op->isTypeDependent())
5564 return Context.DependentTy;
5565
Chris Lattner3528d352008-11-21 07:05:48 +00005566 QualType ResType = Op->getType();
5567 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005568
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005569 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5570 // Decrement of bool is not allowed.
5571 if (!isInc) {
5572 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5573 return QualType();
5574 }
5575 // Increment of bool sets it to true, but is deprecated.
5576 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5577 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005578 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005579 } else if (ResType->isAnyPointerType()) {
5580 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005581
Chris Lattner3528d352008-11-21 07:05:48 +00005582 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005583 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005584 if (getLangOptions().CPlusPlus) {
5585 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5586 << Op->getSourceRange();
5587 return QualType();
5588 }
5589
5590 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005591 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005592 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005593 if (getLangOptions().CPlusPlus) {
5594 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5595 << Op->getType() << Op->getSourceRange();
5596 return QualType();
5597 }
5598
5599 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005600 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005601 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005602 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005603 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005604 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005605 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005606 // Diagnose bad cases where we step over interface counts.
5607 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5608 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5609 << PointeeTy << Op->getSourceRange();
5610 return QualType();
5611 }
Chris Lattner3528d352008-11-21 07:05:48 +00005612 } else if (ResType->isComplexType()) {
5613 // C99 does not support ++/-- on complex types, we allow as an extension.
5614 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005615 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005616 } else {
5617 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005618 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005619 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005620 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005621 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005622 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005623 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005624 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005625 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005626}
5627
Anders Carlsson369dee42008-02-01 07:15:58 +00005628/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005629/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005630/// where the declaration is needed for type checking. We only need to
5631/// handle cases when the expression references a function designator
5632/// or is an lvalue. Here are some examples:
5633/// - &(x) => x
5634/// - &*****f => f for f a function designator.
5635/// - &s.xx => s
5636/// - &s.zz[1].yy -> s, if zz is an array
5637/// - *(x + 1) -> x, if x is an array
5638/// - &"123"[2] -> 0
5639/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005640static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005641 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005642 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005643 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005644 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005645 // If this is an arrow operator, the address is an offset from
5646 // the base's value, so the object the base refers to is
5647 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005648 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005649 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005650 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005651 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005652 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005653 // FIXME: This code shouldn't be necessary! We should catch the implicit
5654 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005655 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5656 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5657 if (ICE->getSubExpr()->getType()->isArrayType())
5658 return getPrimaryDecl(ICE->getSubExpr());
5659 }
5660 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005661 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005662 case Stmt::UnaryOperatorClass: {
5663 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005664
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005665 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005666 case UnaryOperator::Real:
5667 case UnaryOperator::Imag:
5668 case UnaryOperator::Extension:
5669 return getPrimaryDecl(UO->getSubExpr());
5670 default:
5671 return 0;
5672 }
5673 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005674 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005675 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005676 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005677 // If the result of an implicit cast is an l-value, we care about
5678 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005679 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005680 default:
5681 return 0;
5682 }
5683}
5684
5685/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005687/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005688/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005689/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005690/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005691/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005692QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005693 // Make sure to ignore parentheses in subsequent checks
5694 op = op->IgnoreParens();
5695
Douglas Gregor9103bb22008-12-17 22:52:20 +00005696 if (op->isTypeDependent())
5697 return Context.DependentTy;
5698
Steve Naroff08f19672008-01-13 17:10:08 +00005699 if (getLangOptions().C99) {
5700 // Implement C99-only parts of addressof rules.
5701 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5702 if (uOp->getOpcode() == UnaryOperator::Deref)
5703 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5704 // (assuming the deref expression is valid).
5705 return uOp->getSubExpr()->getType();
5706 }
5707 // Technically, there should be a check for array subscript
5708 // expressions here, but the result of one is always an lvalue anyway.
5709 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005710 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005711 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005712
Eli Friedman441cf102009-05-16 23:27:50 +00005713 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5714 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005715 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005716 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005717 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005718 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5719 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005720 return QualType();
5721 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005722 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005723 // The operand cannot be a bit-field
5724 Diag(OpLoc, diag::err_typecheck_address_of)
5725 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005726 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005727 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5728 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005729 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005730 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005731 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005732 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005733 } else if (isa<ObjCPropertyRefExpr>(op)) {
5734 // cannot take address of a property expression.
5735 Diag(OpLoc, diag::err_typecheck_address_of)
5736 << "property expression" << op->getSourceRange();
5737 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005738 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5739 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005740 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5741 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005742 } else if (isa<UnresolvedLookupExpr>(op)) {
5743 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005744 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005745 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005746 // with the register storage-class specifier.
5747 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5748 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005749 Diag(OpLoc, diag::err_typecheck_address_of)
5750 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005751 return QualType();
5752 }
John McCallba135432009-11-21 08:51:07 +00005753 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005754 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005755 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005756 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005757 // Could be a pointer to member, though, if there is an explicit
5758 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005759 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005760 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005761 if (Ctx && Ctx->isRecord()) {
5762 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005763 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005764 diag::err_cannot_form_pointer_to_member_of_reference_type)
5765 << FD->getDeclName() << FD->getType();
5766 return QualType();
5767 }
Mike Stump1eb44332009-09-09 15:08:12 +00005768
Sebastian Redlebc07d52009-02-03 20:19:35 +00005769 return Context.getMemberPointerType(op->getType(),
5770 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005771 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005772 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005773 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005774 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005775 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005776 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5777 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005778 return Context.getMemberPointerType(op->getType(),
5779 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5780 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005781 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005782 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005783
Eli Friedman441cf102009-05-16 23:27:50 +00005784 if (lval == Expr::LV_IncompleteVoidType) {
5785 // Taking the address of a void variable is technically illegal, but we
5786 // allow it in cases which are otherwise valid.
5787 // Example: "extern void x; void* y = &x;".
5788 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5789 }
5790
Reid Spencer5f016e22007-07-11 17:01:13 +00005791 // If the operand has type "type", the result has type "pointer to type".
5792 return Context.getPointerType(op->getType());
5793}
5794
Chris Lattner22caddc2008-11-23 09:13:29 +00005795QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005796 if (Op->isTypeDependent())
5797 return Context.DependentTy;
5798
Chris Lattner22caddc2008-11-23 09:13:29 +00005799 UsualUnaryConversions(Op);
5800 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005801
Chris Lattner22caddc2008-11-23 09:13:29 +00005802 // Note that per both C89 and C99, this is always legal, even if ptype is an
5803 // incomplete type or void. It would be possible to warn about dereferencing
5804 // a void pointer, but it's completely well-defined, and such a warning is
5805 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005806 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005807 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005808
John McCall183700f2009-09-21 23:43:11 +00005809 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005810 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005811
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005812 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005813 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005814 return QualType();
5815}
5816
5817static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5818 tok::TokenKind Kind) {
5819 BinaryOperator::Opcode Opc;
5820 switch (Kind) {
5821 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005822 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5823 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005824 case tok::star: Opc = BinaryOperator::Mul; break;
5825 case tok::slash: Opc = BinaryOperator::Div; break;
5826 case tok::percent: Opc = BinaryOperator::Rem; break;
5827 case tok::plus: Opc = BinaryOperator::Add; break;
5828 case tok::minus: Opc = BinaryOperator::Sub; break;
5829 case tok::lessless: Opc = BinaryOperator::Shl; break;
5830 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5831 case tok::lessequal: Opc = BinaryOperator::LE; break;
5832 case tok::less: Opc = BinaryOperator::LT; break;
5833 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5834 case tok::greater: Opc = BinaryOperator::GT; break;
5835 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5836 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5837 case tok::amp: Opc = BinaryOperator::And; break;
5838 case tok::caret: Opc = BinaryOperator::Xor; break;
5839 case tok::pipe: Opc = BinaryOperator::Or; break;
5840 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5841 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5842 case tok::equal: Opc = BinaryOperator::Assign; break;
5843 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5844 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5845 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5846 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5847 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5848 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5849 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5850 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5851 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5852 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5853 case tok::comma: Opc = BinaryOperator::Comma; break;
5854 }
5855 return Opc;
5856}
5857
5858static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5859 tok::TokenKind Kind) {
5860 UnaryOperator::Opcode Opc;
5861 switch (Kind) {
5862 default: assert(0 && "Unknown unary op!");
5863 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5864 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5865 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5866 case tok::star: Opc = UnaryOperator::Deref; break;
5867 case tok::plus: Opc = UnaryOperator::Plus; break;
5868 case tok::minus: Opc = UnaryOperator::Minus; break;
5869 case tok::tilde: Opc = UnaryOperator::Not; break;
5870 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005871 case tok::kw___real: Opc = UnaryOperator::Real; break;
5872 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5873 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5874 }
5875 return Opc;
5876}
5877
Douglas Gregoreaebc752008-11-06 23:29:22 +00005878/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5879/// operator @p Opc at location @c TokLoc. This routine only supports
5880/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005881Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5882 unsigned Op,
5883 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005884 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005885 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005886 // The following two variables are used for compound assignment operators
5887 QualType CompLHSTy; // Type of LHS after promotions for computation
5888 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005889
5890 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005891 case BinaryOperator::Assign:
5892 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5893 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005894 case BinaryOperator::PtrMemD:
5895 case BinaryOperator::PtrMemI:
5896 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5897 Opc == BinaryOperator::PtrMemI);
5898 break;
5899 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005900 case BinaryOperator::Div:
5901 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5902 break;
5903 case BinaryOperator::Rem:
5904 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5905 break;
5906 case BinaryOperator::Add:
5907 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5908 break;
5909 case BinaryOperator::Sub:
5910 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5911 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005912 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005913 case BinaryOperator::Shr:
5914 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5915 break;
5916 case BinaryOperator::LE:
5917 case BinaryOperator::LT:
5918 case BinaryOperator::GE:
5919 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005920 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005921 break;
5922 case BinaryOperator::EQ:
5923 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005924 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005925 break;
5926 case BinaryOperator::And:
5927 case BinaryOperator::Xor:
5928 case BinaryOperator::Or:
5929 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5930 break;
5931 case BinaryOperator::LAnd:
5932 case BinaryOperator::LOr:
5933 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5934 break;
5935 case BinaryOperator::MulAssign:
5936 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005937 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5938 CompLHSTy = CompResultTy;
5939 if (!CompResultTy.isNull())
5940 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005941 break;
5942 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005943 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5944 CompLHSTy = CompResultTy;
5945 if (!CompResultTy.isNull())
5946 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005947 break;
5948 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005949 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5950 if (!CompResultTy.isNull())
5951 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005952 break;
5953 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005954 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5955 if (!CompResultTy.isNull())
5956 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005957 break;
5958 case BinaryOperator::ShlAssign:
5959 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005960 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5961 CompLHSTy = CompResultTy;
5962 if (!CompResultTy.isNull())
5963 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005964 break;
5965 case BinaryOperator::AndAssign:
5966 case BinaryOperator::XorAssign:
5967 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005968 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5969 CompLHSTy = CompResultTy;
5970 if (!CompResultTy.isNull())
5971 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005972 break;
5973 case BinaryOperator::Comma:
5974 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5975 break;
5976 }
5977 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005978 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005979 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005980 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5981 else
5982 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005983 CompLHSTy, CompResultTy,
5984 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005985}
5986
Sebastian Redlaee3c932009-10-27 12:10:02 +00005987/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5988/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005989static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5990 const PartialDiagnostic &PD,
5991 SourceRange ParenRange)
5992{
5993 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5994 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5995 // We can't display the parentheses, so just dig the
5996 // warning/error and return.
5997 Self.Diag(Loc, PD);
5998 return;
5999 }
6000
6001 Self.Diag(Loc, PD)
6002 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6003 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6004}
6005
Sebastian Redlaee3c932009-10-27 12:10:02 +00006006/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6007/// operators are mixed in a way that suggests that the programmer forgot that
6008/// comparison operators have higher precedence. The most typical example of
6009/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006010static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6011 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006012 typedef BinaryOperator BinOp;
6013 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6014 rhsopc = static_cast<BinOp::Opcode>(-1);
6015 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006016 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006017 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006018 rhsopc = BO->getOpcode();
6019
6020 // Subs are not binary operators.
6021 if (lhsopc == -1 && rhsopc == -1)
6022 return;
6023
6024 // Bitwise operations are sometimes used as eager logical ops.
6025 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006026 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6027 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006028 return;
6029
Sebastian Redlaee3c932009-10-27 12:10:02 +00006030 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006031 SuggestParentheses(Self, OpLoc,
6032 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006033 << SourceRange(lhs->getLocStart(), OpLoc)
6034 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6035 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6036 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006037 SuggestParentheses(Self, OpLoc,
6038 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006039 << SourceRange(OpLoc, rhs->getLocEnd())
6040 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6041 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006042}
6043
6044/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6045/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6046/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6047static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6048 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006049 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006050 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6051}
6052
Reid Spencer5f016e22007-07-11 17:01:13 +00006053// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006054Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6055 tok::TokenKind Kind,
6056 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006057 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006058 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006059
Steve Narofff69936d2007-09-16 03:34:24 +00006060 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6061 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006062
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006063 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6064 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6065
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006066 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6067}
6068
6069Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6070 BinaryOperator::Opcode Opc,
6071 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006072 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006073 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006074 rhs->getType()->isOverloadableType())) {
6075 // Find all of the overloaded operators visible from this
6076 // point. We perform both an operator-name lookup from the local
6077 // scope and an argument-dependent lookup based on the types of
6078 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006079 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006080 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6081 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006082 if (S)
6083 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6084 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006085 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006086 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006087 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006088 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006089 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006090
Douglas Gregor063daf62009-03-13 18:40:31 +00006091 // Build the (potentially-overloaded, potentially-dependent)
6092 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006093 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006094 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006095
Douglas Gregoreaebc752008-11-06 23:29:22 +00006096 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006097 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006098}
6099
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006100Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006101 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006102 ExprArg InputArg) {
6103 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006104
Mike Stump390b4cc2009-05-16 07:39:55 +00006105 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006106 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006107 QualType resultType;
6108 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006109 case UnaryOperator::OffsetOf:
6110 assert(false && "Invalid unary operator");
6111 break;
6112
Reid Spencer5f016e22007-07-11 17:01:13 +00006113 case UnaryOperator::PreInc:
6114 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006115 case UnaryOperator::PostInc:
6116 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006117 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006118 Opc == UnaryOperator::PreInc ||
6119 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006120 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006121 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006122 resultType = CheckAddressOfOperand(Input, OpLoc);
6123 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006124 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006125 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006126 resultType = CheckIndirectionOperand(Input, OpLoc);
6127 break;
6128 case UnaryOperator::Plus:
6129 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006130 UsualUnaryConversions(Input);
6131 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006132 if (resultType->isDependentType())
6133 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006134 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6135 break;
6136 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6137 resultType->isEnumeralType())
6138 break;
6139 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6140 Opc == UnaryOperator::Plus &&
6141 resultType->isPointerType())
6142 break;
6143
Sebastian Redl0eb23302009-01-19 00:08:26 +00006144 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6145 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006146 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006147 UsualUnaryConversions(Input);
6148 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006149 if (resultType->isDependentType())
6150 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006151 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6152 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6153 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006154 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006155 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006156 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006157 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6158 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006159 break;
6160 case UnaryOperator::LNot: // logical negation
6161 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006162 DefaultFunctionArrayConversion(Input);
6163 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006164 if (resultType->isDependentType())
6165 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006166 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006167 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6168 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006169 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006170 // In C++, it's bool. C++ 5.3.1p8
6171 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006172 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006173 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006174 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006175 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006176 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006177 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006178 resultType = Input->getType();
6179 break;
6180 }
6181 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006182 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006183
6184 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006185 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006186}
6187
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006188Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6189 UnaryOperator::Opcode Opc,
6190 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006191 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006192 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6193 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006194 // Find all of the overloaded operators visible from this
6195 // point. We perform both an operator-name lookup from the local
6196 // scope and an argument-dependent lookup based on the types of
6197 // the arguments.
6198 FunctionSet Functions;
6199 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6200 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006201 if (S)
6202 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6203 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006204 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006205 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006206 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006207 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006208
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006209 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6210 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006211
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006212 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6213}
6214
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006215// Unary Operators. 'Tok' is the token for the operator.
6216Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6217 tok::TokenKind Op, ExprArg input) {
6218 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6219}
6220
Steve Naroff1b273c42007-09-16 14:56:35 +00006221/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006222Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6223 SourceLocation LabLoc,
6224 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006225 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006226 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006227
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006228 // If we haven't seen this label yet, create a forward reference. It
6229 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006230 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006231 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006232
Reid Spencer5f016e22007-07-11 17:01:13 +00006233 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006234 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6235 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006236}
6237
Sebastian Redlf53597f2009-03-15 17:47:39 +00006238Sema::OwningExprResult
6239Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6240 SourceLocation RPLoc) { // "({..})"
6241 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006242 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6243 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6244
Eli Friedmandca2b732009-01-24 23:09:00 +00006245 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006246 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006247 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006248
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006249 // FIXME: there are a variety of strange constraints to enforce here, for
6250 // example, it is not possible to goto into a stmt expression apparently.
6251 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006252
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006253 // If there are sub stmts in the compound stmt, take the type of the last one
6254 // as the type of the stmtexpr.
6255 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006256
Chris Lattner611b2ec2008-07-26 19:51:01 +00006257 if (!Compound->body_empty()) {
6258 Stmt *LastStmt = Compound->body_back();
6259 // If LastStmt is a label, skip down through into the body.
6260 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6261 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006262
Chris Lattner611b2ec2008-07-26 19:51:01 +00006263 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006264 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006265 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006266
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006267 // FIXME: Check that expression type is complete/non-abstract; statement
6268 // expressions are not lvalues.
6269
Sebastian Redlf53597f2009-03-15 17:47:39 +00006270 substmt.release();
6271 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006272}
Steve Naroffd34e9152007-08-01 22:05:33 +00006273
Sebastian Redlf53597f2009-03-15 17:47:39 +00006274Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6275 SourceLocation BuiltinLoc,
6276 SourceLocation TypeLoc,
6277 TypeTy *argty,
6278 OffsetOfComponent *CompPtr,
6279 unsigned NumComponents,
6280 SourceLocation RPLoc) {
6281 // FIXME: This function leaks all expressions in the offset components on
6282 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006283 // FIXME: Preserve type source info.
6284 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006285 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006286
Sebastian Redl28507842009-02-26 14:39:58 +00006287 bool Dependent = ArgTy->isDependentType();
6288
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006289 // We must have at least one component that refers to the type, and the first
6290 // one is known to be a field designator. Verify that the ArgTy represents
6291 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006292 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006293 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006294
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006295 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6296 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006297
Eli Friedman35183ac2009-02-27 06:44:11 +00006298 // Otherwise, create a null pointer as the base, and iteratively process
6299 // the offsetof designators.
6300 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6301 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006302 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006303 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006304
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006305 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6306 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006307 // FIXME: This diagnostic isn't actually visible because the location is in
6308 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006309 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006310 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6311 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006312
Sebastian Redl28507842009-02-26 14:39:58 +00006313 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006314 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006315
John McCalld00f2002009-11-04 03:03:43 +00006316 if (RequireCompleteType(TypeLoc, Res->getType(),
6317 diag::err_offsetof_incomplete_type))
6318 return ExprError();
6319
Sebastian Redl28507842009-02-26 14:39:58 +00006320 // FIXME: Dependent case loses a lot of information here. And probably
6321 // leaks like a sieve.
6322 for (unsigned i = 0; i != NumComponents; ++i) {
6323 const OffsetOfComponent &OC = CompPtr[i];
6324 if (OC.isBrackets) {
6325 // Offset of an array sub-field. TODO: Should we allow vector elements?
6326 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6327 if (!AT) {
6328 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006329 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6330 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006331 }
6332
6333 // FIXME: C++: Verify that operator[] isn't overloaded.
6334
Eli Friedman35183ac2009-02-27 06:44:11 +00006335 // Promote the array so it looks more like a normal array subscript
6336 // expression.
6337 DefaultFunctionArrayConversion(Res);
6338
Sebastian Redl28507842009-02-26 14:39:58 +00006339 // C99 6.5.2.1p1
6340 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006341 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006342 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006343 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006344 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006345 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006346
6347 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6348 OC.LocEnd);
6349 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006350 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006351
Ted Kremenek6217b802009-07-29 21:53:49 +00006352 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006353 if (!RC) {
6354 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006355 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6356 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006357 }
Chris Lattner704fe352007-08-30 17:59:59 +00006358
Sebastian Redl28507842009-02-26 14:39:58 +00006359 // Get the decl corresponding to this.
6360 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006361 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006362 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00006363 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6364 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6365 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006366 DidWarnAboutNonPOD = true;
6367 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006368 }
Mike Stump1eb44332009-09-09 15:08:12 +00006369
John McCalla24dc2e2009-11-17 02:14:36 +00006370 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6371 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006372
John McCall1bcee0a2009-12-02 08:25:40 +00006373 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006374 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006375 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006376 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6377 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006378
Sebastian Redl28507842009-02-26 14:39:58 +00006379 // FIXME: C++: Verify that MemberDecl isn't a static field.
6380 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006381 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006382 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006383 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006384 } else {
6385 // MemberDecl->getType() doesn't get the right qualifiers, but it
6386 // doesn't matter here.
6387 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6388 MemberDecl->getType().getNonReferenceType());
6389 }
Sebastian Redl28507842009-02-26 14:39:58 +00006390 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006391 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006392
Sebastian Redlf53597f2009-03-15 17:47:39 +00006393 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6394 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006395}
6396
6397
Sebastian Redlf53597f2009-03-15 17:47:39 +00006398Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6399 TypeTy *arg1,TypeTy *arg2,
6400 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006401 // FIXME: Preserve type source info.
6402 QualType argT1 = GetTypeFromParser(arg1);
6403 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006404
Steve Naroffd34e9152007-08-01 22:05:33 +00006405 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006406
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006407 if (getLangOptions().CPlusPlus) {
6408 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6409 << SourceRange(BuiltinLoc, RPLoc);
6410 return ExprError();
6411 }
6412
Sebastian Redlf53597f2009-03-15 17:47:39 +00006413 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6414 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006415}
6416
Sebastian Redlf53597f2009-03-15 17:47:39 +00006417Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6418 ExprArg cond,
6419 ExprArg expr1, ExprArg expr2,
6420 SourceLocation RPLoc) {
6421 Expr *CondExpr = static_cast<Expr*>(cond.get());
6422 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6423 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006424
Steve Naroffd04fdd52007-08-03 21:21:27 +00006425 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6426
Sebastian Redl28507842009-02-26 14:39:58 +00006427 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006428 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006429 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006430 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006431 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006432 } else {
6433 // The conditional expression is required to be a constant expression.
6434 llvm::APSInt condEval(32);
6435 SourceLocation ExpLoc;
6436 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006437 return ExprError(Diag(ExpLoc,
6438 diag::err_typecheck_choose_expr_requires_constant)
6439 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006440
Sebastian Redl28507842009-02-26 14:39:58 +00006441 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6442 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006443 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6444 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006445 }
6446
Sebastian Redlf53597f2009-03-15 17:47:39 +00006447 cond.release(); expr1.release(); expr2.release();
6448 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006449 resType, RPLoc,
6450 resType->isDependentType(),
6451 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006452}
6453
Steve Naroff4eb206b2008-09-03 18:15:37 +00006454//===----------------------------------------------------------------------===//
6455// Clang Extensions.
6456//===----------------------------------------------------------------------===//
6457
6458/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006459void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006460 // Analyze block parameters.
6461 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006462
Steve Naroff4eb206b2008-09-03 18:15:37 +00006463 // Add BSI to CurBlock.
6464 BSI->PrevBlockInfo = CurBlock;
6465 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006466
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006467 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006468 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006469 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006470 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006471 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6472 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006473
Steve Naroff090276f2008-10-10 01:28:17 +00006474 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006475 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006476}
6477
Mike Stump98eb8a72009-02-04 22:31:32 +00006478void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006479 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006480
6481 if (ParamInfo.getNumTypeObjects() == 0
6482 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006483 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006484 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6485
Mike Stump4eeab842009-04-28 01:10:27 +00006486 if (T->isArrayType()) {
6487 Diag(ParamInfo.getSourceRange().getBegin(),
6488 diag::err_block_returns_array);
6489 return;
6490 }
6491
Mike Stump98eb8a72009-02-04 22:31:32 +00006492 // The parameter list is optional, if there was none, assume ().
6493 if (!T->isFunctionType())
6494 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6495
6496 CurBlock->hasPrototype = true;
6497 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006498 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006499 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006500 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006501 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006502 // FIXME: remove the attribute.
6503 }
John McCall183700f2009-09-21 23:43:11 +00006504 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006505
Chris Lattner9097af12009-04-11 19:27:54 +00006506 // Do not allow returning a objc interface by-value.
6507 if (RetTy->isObjCInterfaceType()) {
6508 Diag(ParamInfo.getSourceRange().getBegin(),
6509 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6510 return;
6511 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006512 return;
6513 }
6514
Steve Naroff4eb206b2008-09-03 18:15:37 +00006515 // Analyze arguments to block.
6516 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6517 "Not a function declarator!");
6518 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006519
Steve Naroff090276f2008-10-10 01:28:17 +00006520 CurBlock->hasPrototype = FTI.hasPrototype;
6521 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006522
Steve Naroff4eb206b2008-09-03 18:15:37 +00006523 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6524 // no arguments, not a function that takes a single void argument.
6525 if (FTI.hasPrototype &&
6526 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006527 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6528 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006529 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006530 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006531 } else if (FTI.hasPrototype) {
6532 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006533 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006534 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006535 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006536 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006537 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006538 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006539 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006540 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6541 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6542 // If this has an identifier, add it to the scope stack.
6543 if ((*AI)->getIdentifier())
6544 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006545
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006546 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006547 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006548 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006549 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006550 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006551 // FIXME: remove the attribute.
6552 }
Mike Stump1eb44332009-09-09 15:08:12 +00006553
Chris Lattner9097af12009-04-11 19:27:54 +00006554 // Analyze the return type.
6555 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006556 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006557
Chris Lattner9097af12009-04-11 19:27:54 +00006558 // Do not allow returning a objc interface by-value.
6559 if (RetTy->isObjCInterfaceType()) {
6560 Diag(ParamInfo.getSourceRange().getBegin(),
6561 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6562 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006563 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006564}
6565
6566/// ActOnBlockError - If there is an error parsing a block, this callback
6567/// is invoked to pop the information about the block from the action impl.
6568void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6569 // Ensure that CurBlock is deleted.
6570 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006571
Chris Lattner17a78302009-04-19 05:28:12 +00006572 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6573
Steve Naroff4eb206b2008-09-03 18:15:37 +00006574 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006575 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006576 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006577 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006578}
6579
6580/// ActOnBlockStmtExpr - This is called when the body of a block statement
6581/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006582Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6583 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006584 // If blocks are disabled, emit an error.
6585 if (!LangOpts.Blocks)
6586 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006587
Steve Naroff4eb206b2008-09-03 18:15:37 +00006588 // Ensure that CurBlock is deleted.
6589 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006590
Steve Naroff090276f2008-10-10 01:28:17 +00006591 PopDeclContext();
6592
Steve Naroff4eb206b2008-09-03 18:15:37 +00006593 // Pop off CurBlock, handle nested blocks.
6594 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006595
Steve Naroff4eb206b2008-09-03 18:15:37 +00006596 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006597 if (!BSI->ReturnType.isNull())
6598 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006599
Steve Naroff4eb206b2008-09-03 18:15:37 +00006600 llvm::SmallVector<QualType, 8> ArgTypes;
6601 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6602 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006603
Mike Stump56925862009-07-28 22:04:01 +00006604 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006605 QualType BlockTy;
6606 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006607 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6608 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006609 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006610 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006611 BSI->isVariadic, 0, false, false, 0, 0,
6612 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006613
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006614 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006615 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006616 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006617
Chris Lattner17a78302009-04-19 05:28:12 +00006618 // If needed, diagnose invalid gotos and switches in the block.
6619 if (CurFunctionNeedsScopeChecking)
6620 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6621 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006622
Anders Carlssone9146f22009-05-01 19:49:17 +00006623 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006624 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006625 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6626 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006627}
6628
Sebastian Redlf53597f2009-03-15 17:47:39 +00006629Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6630 ExprArg expr, TypeTy *type,
6631 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006632 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006633 Expr *E = static_cast<Expr*>(expr.get());
6634 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006635
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006636 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006637
6638 // Get the va_list type
6639 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006640 if (VaListType->isArrayType()) {
6641 // Deal with implicit array decay; for example, on x86-64,
6642 // va_list is an array, but it's supposed to decay to
6643 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006644 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006645 // Make sure the input expression also decays appropriately.
6646 UsualUnaryConversions(E);
6647 } else {
6648 // Otherwise, the va_list argument must be an l-value because
6649 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006650 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006651 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006652 return ExprError();
6653 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006654
Douglas Gregordd027302009-05-19 23:10:31 +00006655 if (!E->isTypeDependent() &&
6656 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006657 return ExprError(Diag(E->getLocStart(),
6658 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006659 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006660 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006661
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006662 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006663 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006664
Sebastian Redlf53597f2009-03-15 17:47:39 +00006665 expr.release();
6666 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6667 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006668}
6669
Sebastian Redlf53597f2009-03-15 17:47:39 +00006670Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006671 // The type of __null will be int or long, depending on the size of
6672 // pointers on the target.
6673 QualType Ty;
6674 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6675 Ty = Context.IntTy;
6676 else
6677 Ty = Context.LongTy;
6678
Sebastian Redlf53597f2009-03-15 17:47:39 +00006679 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006680}
6681
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006682static void
6683MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6684 QualType DstType,
6685 Expr *SrcExpr,
6686 CodeModificationHint &Hint) {
6687 if (!SemaRef.getLangOptions().ObjC1)
6688 return;
6689
6690 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6691 if (!PT)
6692 return;
6693
6694 // Check if the destination is of type 'id'.
6695 if (!PT->isObjCIdType()) {
6696 // Check if the destination is the 'NSString' interface.
6697 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6698 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6699 return;
6700 }
6701
6702 // Strip off any parens and casts.
6703 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6704 if (!SL || SL->isWide())
6705 return;
6706
6707 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6708}
6709
Chris Lattner5cf216b2008-01-04 18:04:52 +00006710bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6711 SourceLocation Loc,
6712 QualType DstType, QualType SrcType,
6713 Expr *SrcExpr, const char *Flavor) {
6714 // Decode the result (notice that AST's are still created for extensions).
6715 bool isInvalid = false;
6716 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006717 CodeModificationHint Hint;
6718
Chris Lattner5cf216b2008-01-04 18:04:52 +00006719 switch (ConvTy) {
6720 default: assert(0 && "Unknown conversion type");
6721 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006722 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006723 DiagKind = diag::ext_typecheck_convert_pointer_int;
6724 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006725 case IntToPointer:
6726 DiagKind = diag::ext_typecheck_convert_int_pointer;
6727 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006728 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006729 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006730 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6731 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006732 case IncompatiblePointerSign:
6733 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6734 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006735 case FunctionVoidPointer:
6736 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6737 break;
6738 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006739 // If the qualifiers lost were because we were applying the
6740 // (deprecated) C++ conversion from a string literal to a char*
6741 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6742 // Ideally, this check would be performed in
6743 // CheckPointerTypesForAssignment. However, that would require a
6744 // bit of refactoring (so that the second argument is an
6745 // expression, rather than a type), which should be done as part
6746 // of a larger effort to fix CheckPointerTypesForAssignment for
6747 // C++ semantics.
6748 if (getLangOptions().CPlusPlus &&
6749 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6750 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006751 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6752 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006753 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006754 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006755 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006756 case IntToBlockPointer:
6757 DiagKind = diag::err_int_to_block_pointer;
6758 break;
6759 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006760 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006761 break;
Steve Naroff39579072008-10-14 22:18:38 +00006762 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006763 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006764 // it can give a more specific diagnostic.
6765 DiagKind = diag::warn_incompatible_qualified_id;
6766 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006767 case IncompatibleVectors:
6768 DiagKind = diag::warn_incompatible_vectors;
6769 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006770 case Incompatible:
6771 DiagKind = diag::err_typecheck_convert_incompatible;
6772 isInvalid = true;
6773 break;
6774 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006775
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006776 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006777 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006778 return isInvalid;
6779}
Anders Carlssone21555e2008-11-30 19:50:32 +00006780
Chris Lattner3bf68932009-04-25 21:59:05 +00006781bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006782 llvm::APSInt ICEResult;
6783 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6784 if (Result)
6785 *Result = ICEResult;
6786 return false;
6787 }
6788
Anders Carlssone21555e2008-11-30 19:50:32 +00006789 Expr::EvalResult EvalResult;
6790
Mike Stumpeed9cac2009-02-19 03:04:26 +00006791 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006792 EvalResult.HasSideEffects) {
6793 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6794
6795 if (EvalResult.Diag) {
6796 // We only show the note if it's not the usual "invalid subexpression"
6797 // or if it's actually in a subexpression.
6798 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6799 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6800 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6801 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006802
Anders Carlssone21555e2008-11-30 19:50:32 +00006803 return true;
6804 }
6805
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006806 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6807 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006808
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006809 if (EvalResult.Diag &&
6810 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6811 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006812
Anders Carlssone21555e2008-11-30 19:50:32 +00006813 if (Result)
6814 *Result = EvalResult.Val.getInt();
6815 return false;
6816}
Douglas Gregore0762c92009-06-19 23:52:42 +00006817
Douglas Gregor2afce722009-11-26 00:44:06 +00006818void
Mike Stump1eb44332009-09-09 15:08:12 +00006819Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006820 ExprEvalContexts.push_back(
6821 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006822}
6823
Mike Stump1eb44332009-09-09 15:08:12 +00006824void
Douglas Gregor2afce722009-11-26 00:44:06 +00006825Sema::PopExpressionEvaluationContext() {
6826 // Pop the current expression evaluation context off the stack.
6827 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6828 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006829
Douglas Gregor2afce722009-11-26 00:44:06 +00006830 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6831 Rec.PotentiallyReferenced) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006832 // Mark any remaining declarations in the current position of the stack
6833 // as "referenced". If they were not meant to be referenced, semantic
6834 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregor2afce722009-11-26 00:44:06 +00006835 for (PotentiallyReferencedDecls::iterator
6836 I = Rec.PotentiallyReferenced->begin(),
6837 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006838 I != IEnd; ++I)
6839 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregor2afce722009-11-26 00:44:06 +00006840 }
6841
6842 // When are coming out of an unevaluated context, clear out any
6843 // temporaries that we may have created as part of the evaluation of
6844 // the expression in that context: they aren't relevant because they
6845 // will never be constructed.
6846 if (Rec.Context == Unevaluated &&
6847 ExprTemporaries.size() > Rec.NumTemporaries)
6848 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6849 ExprTemporaries.end());
6850
6851 // Destroy the popped expression evaluation record.
6852 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006853}
Douglas Gregore0762c92009-06-19 23:52:42 +00006854
6855/// \brief Note that the given declaration was referenced in the source code.
6856///
6857/// This routine should be invoke whenever a given declaration is referenced
6858/// in the source code, and where that reference occurred. If this declaration
6859/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6860/// C99 6.9p3), then the declaration will be marked as used.
6861///
6862/// \param Loc the location where the declaration was referenced.
6863///
6864/// \param D the declaration that has been referenced by the source code.
6865void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6866 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006867
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006868 if (D->isUsed())
6869 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006870
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006871 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6872 // template or not. The reason for this is that unevaluated expressions
6873 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6874 // -Wunused-parameters)
6875 if (isa<ParmVarDecl>(D) ||
6876 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006877 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006878
Douglas Gregore0762c92009-06-19 23:52:42 +00006879 // Do not mark anything as "used" within a dependent context; wait for
6880 // an instantiation.
6881 if (CurContext->isDependentContext())
6882 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006883
Douglas Gregor2afce722009-11-26 00:44:06 +00006884 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006885 case Unevaluated:
6886 // We are in an expression that is not potentially evaluated; do nothing.
6887 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006888
Douglas Gregorac7610d2009-06-22 20:57:11 +00006889 case PotentiallyEvaluated:
6890 // We are in a potentially-evaluated expression, so this declaration is
6891 // "used"; handle this below.
6892 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006893
Douglas Gregorac7610d2009-06-22 20:57:11 +00006894 case PotentiallyPotentiallyEvaluated:
6895 // We are in an expression that may be potentially evaluated; queue this
6896 // declaration reference until we know whether the expression is
6897 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00006898 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00006899 return;
6900 }
Mike Stump1eb44332009-09-09 15:08:12 +00006901
Douglas Gregore0762c92009-06-19 23:52:42 +00006902 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006903 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006904 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006905 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6906 if (!Constructor->isUsed())
6907 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006908 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006909 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006910 if (!Constructor->isUsed())
6911 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6912 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006913 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6914 if (Destructor->isImplicit() && !Destructor->isUsed())
6915 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006916
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006917 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6918 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6919 MethodDecl->getOverloadedOperator() == OO_Equal) {
6920 if (!MethodDecl->isUsed())
6921 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6922 }
6923 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006924 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006925 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006926 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006927 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006928 bool AlreadyInstantiated = false;
6929 if (FunctionTemplateSpecializationInfo *SpecInfo
6930 = Function->getTemplateSpecializationInfo()) {
6931 if (SpecInfo->getPointOfInstantiation().isInvalid())
6932 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006933 else if (SpecInfo->getTemplateSpecializationKind()
6934 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006935 AlreadyInstantiated = true;
6936 } else if (MemberSpecializationInfo *MSInfo
6937 = Function->getMemberSpecializationInfo()) {
6938 if (MSInfo->getPointOfInstantiation().isInvalid())
6939 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006940 else if (MSInfo->getTemplateSpecializationKind()
6941 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006942 AlreadyInstantiated = true;
6943 }
6944
6945 if (!AlreadyInstantiated)
6946 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6947 }
6948
Douglas Gregore0762c92009-06-19 23:52:42 +00006949 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006950 Function->setUsed(true);
6951 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006952 }
Mike Stump1eb44332009-09-09 15:08:12 +00006953
Douglas Gregore0762c92009-06-19 23:52:42 +00006954 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006955 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006956 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006957 Var->getInstantiatedFromStaticDataMember()) {
6958 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6959 assert(MSInfo && "Missing member specialization information?");
6960 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6961 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6962 MSInfo->setPointOfInstantiation(Loc);
6963 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6964 }
6965 }
Mike Stump1eb44332009-09-09 15:08:12 +00006966
Douglas Gregore0762c92009-06-19 23:52:42 +00006967 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006968
Douglas Gregore0762c92009-06-19 23:52:42 +00006969 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006970 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006971 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006972}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006973
6974bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6975 CallExpr *CE, FunctionDecl *FD) {
6976 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6977 return false;
6978
6979 PartialDiagnostic Note =
6980 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6981 << FD->getDeclName() : PDiag();
6982 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6983
6984 if (RequireCompleteType(Loc, ReturnType,
6985 FD ?
6986 PDiag(diag::err_call_function_incomplete_return)
6987 << CE->getSourceRange() << FD->getDeclName() :
6988 PDiag(diag::err_call_incomplete_return)
6989 << CE->getSourceRange(),
6990 std::make_pair(NoteLoc, Note)))
6991 return true;
6992
6993 return false;
6994}
6995
John McCall5a881bb2009-10-12 21:59:07 +00006996// Diagnose the common s/=/==/ typo. Note that adding parentheses
6997// will prevent this condition from triggering, which is what we want.
6998void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6999 SourceLocation Loc;
7000
John McCalla52ef082009-11-11 02:41:58 +00007001 unsigned diagnostic = diag::warn_condition_is_assignment;
7002
John McCall5a881bb2009-10-12 21:59:07 +00007003 if (isa<BinaryOperator>(E)) {
7004 BinaryOperator *Op = cast<BinaryOperator>(E);
7005 if (Op->getOpcode() != BinaryOperator::Assign)
7006 return;
7007
John McCallc8d8ac52009-11-12 00:06:05 +00007008 // Greylist some idioms by putting them into a warning subcategory.
7009 if (ObjCMessageExpr *ME
7010 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7011 Selector Sel = ME->getSelector();
7012
John McCallc8d8ac52009-11-12 00:06:05 +00007013 // self = [<foo> init...]
7014 if (isSelfExpr(Op->getLHS())
7015 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7016 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7017
7018 // <foo> = [<bar> nextObject]
7019 else if (Sel.isUnarySelector() &&
7020 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7021 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7022 }
John McCalla52ef082009-11-11 02:41:58 +00007023
John McCall5a881bb2009-10-12 21:59:07 +00007024 Loc = Op->getOperatorLoc();
7025 } else if (isa<CXXOperatorCallExpr>(E)) {
7026 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7027 if (Op->getOperator() != OO_Equal)
7028 return;
7029
7030 Loc = Op->getOperatorLoc();
7031 } else {
7032 // Not an assignment.
7033 return;
7034 }
7035
John McCall5a881bb2009-10-12 21:59:07 +00007036 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007037 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007038
John McCalla52ef082009-11-11 02:41:58 +00007039 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007040 << E->getSourceRange()
7041 << CodeModificationHint::CreateInsertion(Open, "(")
7042 << CodeModificationHint::CreateInsertion(Close, ")");
7043}
7044
7045bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7046 DiagnoseAssignmentAsCondition(E);
7047
7048 if (!E->isTypeDependent()) {
7049 DefaultFunctionArrayConversion(E);
7050
7051 QualType T = E->getType();
7052
7053 if (getLangOptions().CPlusPlus) {
7054 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7055 return true;
7056 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7057 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7058 << T << E->getSourceRange();
7059 return true;
7060 }
7061 }
7062
7063 return false;
7064}