blob: f3a6765a6a22e6510d4a07e9a83fa2f0d4dc4bf1 [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) {
John McCallba135432009-11-21 08:51:07 +0000420 assert(!isa<OverloadedFunctionDecl>(D));
421
Anders Carlssone2bb2242009-06-26 19:16:07 +0000422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
423 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000424 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000425 << D->getDeclName();
426 return ExprError();
427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Anders Carlssone41590d2009-06-24 00:10:43 +0000429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
430 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
432 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000434 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000435 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000436 << D->getIdentifier();
437 return ExprError();
438 }
439 }
440 }
441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregore0762c92009-06-19 23:52:42 +0000443 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregora2813ce2009-10-23 18:54:35 +0000445 return Owned(DeclRefExpr::Create(Context,
446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
447 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000448 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000449}
450
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000451/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
452/// variable corresponding to the anonymous union or struct whose type
453/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000454static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
455 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000457 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Mike Stump390b4cc2009-05-16 07:39:55 +0000459 // FIXME: Once Decls are directly linked together, this will be an O(1)
460 // operation rather than a slow walk through DeclContext's vector (which
461 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000462 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000463 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000464 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000465 D != DEnd; ++D) {
466 if (*D == Record) {
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
469 ++D;
470 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000472 return *D;
473 }
474 }
475
476 assert(false && "Missing object for anonymous record");
477 return 0;
478}
479
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000480/// \brief Given a field that represents a member of an anonymous
481/// struct/union, build the path from that field's context to the
482/// actual member.
483///
484/// Construct the sequence of field member references we'll have to
485/// perform to get to the field in the anonymous union/struct. The
486/// list of members is built from the field outward, so traverse it
487/// backwards to go from an object in the current context to the field
488/// we found.
489///
490/// \returns The variable from which the field access should begin,
491/// for an anonymous struct/union that is not a member of another
492/// class. Otherwise, returns NULL.
493VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
494 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000495 assert(Field->getDeclContext()->isRecord() &&
496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
497 && "Field must be stored inside an anonymous struct or union");
498
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000499 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000500 VarDecl *BaseObject = 0;
501 DeclContext *Ctx = Field->getDeclContext();
502 do {
503 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000506 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000507 else {
508 BaseObject = cast<VarDecl>(AnonObject);
509 break;
510 }
511 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000512 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000514
515 return BaseObject;
516}
517
518Sema::OwningExprResult
519Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
520 FieldDecl *Field,
521 Expr *BaseObjectExpr,
522 SourceLocation OpLoc) {
523 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000525 AnonFields);
526
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 // Build the expression that refers to the base object, from
528 // which we will build a sequence of member references to each
529 // of the anonymous union objects and, eventually, the field we
530 // found via name lookup.
531 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000532 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 if (BaseObject) {
534 // BaseObject is an anonymous struct/union variable (and is,
535 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000537 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000539 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000540 BaseQuals
541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
John McCall0953e762009-09-24 19:53:00 +0000551 BaseQuals
552 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000553 } else {
554 // We've found a member of an anonymous struct/union that is
555 // inside a non-anonymous struct/union, so in a well-formed
556 // program our base object expression is "this".
557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
558 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000559 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000560 = Context.getTagDeclType(
561 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
562 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000563 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000564 == Context.getCanonicalType(ThisType)) ||
565 IsDerivedFrom(ThisType, AnonFieldType)) {
566 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000567 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000568 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 BaseObjectIsPointer = true;
570 }
571 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000572 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
573 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 }
John McCall0953e762009-09-24 19:53:00 +0000575 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000576 }
577
Mike Stump1eb44332009-09-09 15:08:12 +0000578 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000579 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
580 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000581 }
582
583 // Build the implicit member references to the field of the
584 // anonymous struct/union.
585 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000586 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
588 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
589 FI != FIEnd; ++FI) {
590 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000591 Qualifiers MemberTypeQuals =
592 Context.getCanonicalType(MemberType).getQualifiers();
593
594 // CVR attributes from the base are picked up by members,
595 // except that 'mutable' members don't pick up 'const'.
596 if ((*FI)->isMutable())
597 ResultQuals.removeConst();
598
599 // GC attributes are never picked up by members.
600 ResultQuals.removeObjCGCAttr();
601
602 // TR 18037 does not allow fields to be declared with address spaces.
603 assert(!MemberTypeQuals.hasAddressSpace());
604
605 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
606 if (NewQuals != MemberTypeQuals)
607 MemberType = Context.getQualifiedType(MemberType, NewQuals);
608
Douglas Gregore0762c92009-06-19 23:52:42 +0000609 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000610 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000611 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
612 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000613 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000614 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000615 }
616
Sebastian Redlcd965b92009-01-18 18:53:16 +0000617 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000618}
619
John McCallf7a1a742009-11-24 19:00:30 +0000620static void DecomposeTemplateName(LookupResult &R, TemplateName TName) {
621 if (TemplateDecl *TD = TName.getAsTemplateDecl())
622 R.addDecl(TD);
623 else if (OverloadedFunctionDecl *OD
624 = TName.getAsOverloadedFunctionDecl())
625 for (OverloadIterator I(OD), E; I != E; ++I)
626 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000627
John McCallf7a1a742009-11-24 19:00:30 +0000628 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000629}
630
John McCallf7a1a742009-11-24 19:00:30 +0000631Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
632 const CXXScopeSpec &SS,
633 UnqualifiedId &Id,
634 bool HasTrailingLParen,
635 bool isAddressOfOperand) {
636 assert(!(isAddressOfOperand && HasTrailingLParen) &&
637 "cannot be direct & operand and have a trailing lparen");
638
639 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000640 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000641
John McCallf7a1a742009-11-24 19:00:30 +0000642 TemplateArgumentListInfo ExplicitTemplateArgs;
643
644 // Decompose the UnqualifiedId into the following data.
645 DeclarationName Name;
646 SourceLocation NameLoc;
647 const TemplateArgumentListInfo *TemplateArgs;
648 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
649 ExplicitTemplateArgs.setLAngleLoc(Id.TemplateId->LAngleLoc);
650 ExplicitTemplateArgs.setRAngleLoc(Id.TemplateId->RAngleLoc);
651
652 ASTTemplateArgsPtr TemplateArgsPtr(*this,
653 Id.TemplateId->getTemplateArgs(),
654 Id.TemplateId->NumArgs);
655 translateTemplateArguments(TemplateArgsPtr, ExplicitTemplateArgs);
656 TemplateArgsPtr.release();
657
658 TemplateName TName =
659 TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
660
661 Name = Context.getNameForTemplate(TName);
662 NameLoc = Id.TemplateId->TemplateNameLoc;
663 TemplateArgs = &ExplicitTemplateArgs;
664 } else {
665 Name = GetNameFromUnqualifiedId(Id);
666 NameLoc = Id.StartLocation;
667 TemplateArgs = 0;
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000668 }
669
Douglas Gregor10c42622008-11-18 15:03:34 +0000670 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000671
John McCallf7a1a742009-11-24 19:00:30 +0000672 // C++ [temp.dep.expr]p3:
673 // An id-expression is type-dependent if it contains:
674 // -- a nested-name-specifier that contains a class-name that
675 // names a dependent type.
676 // Determine whether this is a member of an unknown specialization;
677 // we need to handle these differently.
678 if (SS.isSet() && !computeDeclContext(SS, false)) {
679 bool CheckForImplicitMember = !isAddressOfOperand;
John McCallba135432009-11-21 08:51:07 +0000680
John McCallf7a1a742009-11-24 19:00:30 +0000681 return ActOnDependentIdExpression(SS, Name, NameLoc,
682 CheckForImplicitMember,
683 TemplateArgs);
684 }
John McCallba135432009-11-21 08:51:07 +0000685
John McCallf7a1a742009-11-24 19:00:30 +0000686 // Perform the required lookup.
687 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
688 if (TemplateArgs) {
689 TemplateName TName =
690 TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
John McCallba135432009-11-21 08:51:07 +0000691
John McCallf7a1a742009-11-24 19:00:30 +0000692 // Just re-use the lookup done by isTemplateName.
693 DecomposeTemplateName(R, TName);
694 } else {
695 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
John McCallf7a1a742009-11-24 19:00:30 +0000697 // If this reference is in an Objective-C method, then we need to do
698 // some special Objective-C lookup, too.
699 if (!SS.isSet() && II && getCurMethodDecl()) {
700 OwningExprResult E(LookupInObjCMethod(R, S, II));
701 if (E.isInvalid())
702 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000703
John McCallf7a1a742009-11-24 19:00:30 +0000704 Expr *Ex = E.takeAs<Expr>();
705 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000706 }
Chris Lattner8a934232008-03-31 00:36:02 +0000707 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000708
John McCallf7a1a742009-11-24 19:00:30 +0000709 if (R.isAmbiguous())
710 return ExprError();
711
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000712 // Determine whether this name might be a candidate for
713 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000714 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000715
John McCallf7a1a742009-11-24 19:00:30 +0000716 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000718 // in C90, extension in C99, forbidden in C++).
719 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
720 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
721 if (D) R.addDecl(D);
722 }
723
724 // If this name wasn't predeclared and if this is not a function
725 // call, diagnose the problem.
726 if (R.empty()) {
727 if (!SS.isEmpty())
728 return ExprError(Diag(NameLoc, diag::err_no_member)
729 << Name << computeDeclContext(SS, false)
730 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000731 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000732 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000733 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
734 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000735 else
John McCallf7a1a742009-11-24 19:00:30 +0000736 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 }
738 }
Mike Stump1eb44332009-09-09 15:08:12 +0000739
John McCallf7a1a742009-11-24 19:00:30 +0000740 // This is guaranteed from this point on.
741 assert(!R.empty() || ADL);
742
743 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000744 // Warn about constructs like:
745 // if (void *X = foo()) { ... } else { X }.
746 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Douglas Gregor751f9a42009-06-30 15:47:41 +0000748 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
749 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000750 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000751 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000752 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +0000753 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000754 << Var->getDeclName()
755 << (Var->getType()->isPointerType()? 2 :
756 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000757 break;
758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000760 // Move to the parent of this scope.
761 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000762 }
763 }
John McCallf7a1a742009-11-24 19:00:30 +0000764 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000765 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
766 // C99 DR 316 says that, if a function type comes from a
767 // function definition (without a prototype), that type is only
768 // used for checking compatibility. Therefore, when referencing
769 // the function, we pretend that we don't have the full function
770 // type.
John McCallf7a1a742009-11-24 19:00:30 +0000771 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +0000772 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000773
Douglas Gregor751f9a42009-06-30 15:47:41 +0000774 QualType T = Func->getType();
775 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000776 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000777 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +0000778 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +0000779 }
780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
John McCall5b3f9132009-11-22 01:44:31 +0000782 // &SomeClass::foo is an abstract member reference, regardless of
783 // the nature of foo, but &SomeClass::foo(...) is not. If this is
784 // *not* an abstract member reference, and any of the results is a
785 // class member (which necessarily means they're all class members),
786 // then we make an implicit member reference instead.
787 //
788 // This check considers all the same information as the "needs ADL"
789 // check, but there's no simple logical relationship other than the
790 // fact that they can never be simultaneously true. We could
791 // calculate them both in one pass if that proves important for
792 // performance.
793 if (!ADL) {
John McCallf7a1a742009-11-24 19:00:30 +0000794 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +0000795
John McCallf7a1a742009-11-24 19:00:30 +0000796 if (!isAbstractMemberPointer && !R.empty() &&
797 isa<CXXRecordDecl>((*R.begin())->getDeclContext())) {
798 return BuildImplicitMemberReferenceExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +0000799 }
800 }
801
John McCallf7a1a742009-11-24 19:00:30 +0000802 if (TemplateArgs)
803 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +0000804
John McCallf7a1a742009-11-24 19:00:30 +0000805 return BuildDeclarationNameExpr(SS, R, ADL);
806}
807
808/// ActOnDeclarationNameExpr - Build a C++ qualified declaration name,
809/// generally during template instantiation. There's a large number
810/// of things which don't need to be done along this path.
811Sema::OwningExprResult
812Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
813 DeclarationName Name,
814 SourceLocation NameLoc) {
815 DeclContext *DC;
816 if (!(DC = computeDeclContext(SS, false)) ||
817 DC->isDependentContext() ||
818 RequireCompleteDeclContext(SS))
819 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
820
821 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
822 LookupQualifiedName(R, DC);
823
824 if (R.isAmbiguous())
825 return ExprError();
826
827 if (R.empty()) {
828 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
829 return ExprError();
830 }
831
832 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
833}
834
835/// LookupInObjCMethod - The parser has read a name in, and Sema has
836/// detected that we're currently inside an ObjC method. Perform some
837/// additional lookup.
838///
839/// Ideally, most of this would be done by lookup, but there's
840/// actually quite a lot of extra work involved.
841///
842/// Returns a null sentinel to indicate trivial success.
843Sema::OwningExprResult
844Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
845 IdentifierInfo *II) {
846 SourceLocation Loc = Lookup.getNameLoc();
847
848 // There are two cases to handle here. 1) scoped lookup could have failed,
849 // in which case we should look for an ivar. 2) scoped lookup could have
850 // found a decl, but that decl is outside the current instance method (i.e.
851 // a global variable). In these two cases, we do a lookup for an ivar with
852 // this name, if the lookup sucedes, we replace it our current decl.
853
854 // If we're in a class method, we don't normally want to look for
855 // ivars. But if we don't find anything else, and there's an
856 // ivar, that's an error.
857 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
858
859 bool LookForIvars;
860 if (Lookup.empty())
861 LookForIvars = true;
862 else if (IsClassMethod)
863 LookForIvars = false;
864 else
865 LookForIvars = (Lookup.isSingleResult() &&
866 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
867
868 if (LookForIvars) {
869 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
870 ObjCInterfaceDecl *ClassDeclared;
871 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
872 // Diagnose using an ivar in a class method.
873 if (IsClassMethod)
874 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
875 << IV->getDeclName());
876
877 // If we're referencing an invalid decl, just return this as a silent
878 // error node. The error diagnostic was already emitted on the decl.
879 if (IV->isInvalidDecl())
880 return ExprError();
881
882 // Check if referencing a field with __attribute__((deprecated)).
883 if (DiagnoseUseOfDecl(IV, Loc))
884 return ExprError();
885
886 // Diagnose the use of an ivar outside of the declaring class.
887 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
888 ClassDeclared != IFace)
889 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
890
891 // FIXME: This should use a new expr for a direct reference, don't
892 // turn this into Self->ivar, just return a BareIVarExpr or something.
893 IdentifierInfo &II = Context.Idents.get("self");
894 UnqualifiedId SelfName;
895 SelfName.setIdentifier(&II, SourceLocation());
896 CXXScopeSpec SelfScopeSpec;
897 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
898 SelfName, false, false);
899 MarkDeclarationReferenced(Loc, IV);
900 return Owned(new (Context)
901 ObjCIvarRefExpr(IV, IV->getType(), Loc,
902 SelfExpr.takeAs<Expr>(), true, true));
903 }
904 } else if (getCurMethodDecl()->isInstanceMethod()) {
905 // We should warn if a local variable hides an ivar.
906 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
907 ObjCInterfaceDecl *ClassDeclared;
908 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
909 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
910 IFace == ClassDeclared)
911 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
912 }
913 }
914
915 // Needed to implement property "super.method" notation.
916 if (Lookup.empty() && II->isStr("super")) {
917 QualType T;
918
919 if (getCurMethodDecl()->isInstanceMethod())
920 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
921 getCurMethodDecl()->getClassInterface()));
922 else
923 T = Context.getObjCClassType();
924 return Owned(new (Context) ObjCSuperExpr(Loc, T));
925 }
926
927 // Sentinel value saying that we didn't do anything special.
928 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +0000929}
John McCallba135432009-11-21 08:51:07 +0000930
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000931/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000932bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000933Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
934 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000935 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000936 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000937 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000938 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000939 if (DestType->isDependentType() || From->getType()->isDependentType())
940 return false;
941 QualType FromRecordType = From->getType();
942 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000943 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000944 DestType = Context.getPointerType(DestType);
945 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000946 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000947 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
948 CheckDerivedToBaseConversion(FromRecordType,
949 DestRecordType,
950 From->getSourceRange().getBegin(),
951 From->getSourceRange()))
952 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000953 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
954 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000955 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000956 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000957}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000958
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000959/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000960static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
961 const CXXScopeSpec *SS, NamedDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +0000962 SourceLocation Loc, QualType Ty,
963 const TemplateArgumentListInfo *TemplateArgs = 0) {
964 NestedNameSpecifier *Qualifier = 0;
965 SourceRange QualifierRange;
966 if (SS && SS->isSet()) {
967 Qualifier = (NestedNameSpecifier *) SS->getScopeRep();
968 QualifierRange = SS->getRange();
969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970
John McCallf7a1a742009-11-24 19:00:30 +0000971 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
972 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000973}
974
John McCallba135432009-11-21 08:51:07 +0000975/// Builds an implicit member access expression from the given
976/// unqualified lookup set, which is known to contain only class
977/// members.
John McCall5b3f9132009-11-22 01:44:31 +0000978Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000979Sema::BuildImplicitMemberReferenceExpr(const CXXScopeSpec &SS,
980 LookupResult &R,
981 const TemplateArgumentListInfo *TemplateArgs) {
982 assert(!R.empty() && !R.isAmbiguous());
983
John McCall5b3f9132009-11-22 01:44:31 +0000984 NamedDecl *D = R.getAsSingleDecl(Context);
John McCallba135432009-11-21 08:51:07 +0000985 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +0000986
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000987 // We may have found a field within an anonymous union or struct
988 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000989 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +0000990 // FIXME: template-ids inside anonymous structs?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000991 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
992 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +0000993 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000994
John McCallba135432009-11-21 08:51:07 +0000995 QualType ThisType;
996 QualType MemberType;
John McCall5b3f9132009-11-22 01:44:31 +0000997 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
998 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
999 MarkDeclarationReferenced(Loc, D);
1000 if (PerformObjectMemberConversion(This, D))
1001 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00001002
Douglas Gregore961afb2009-10-22 07:08:30 +00001003 bool ShouldCheckUse = true;
1004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1005 // Don't diagnose the use of a virtual member function unless it's
1006 // explicitly qualified.
John McCallf7a1a742009-11-24 19:00:30 +00001007 if (MD->isVirtual() && !SS.isSet())
Douglas Gregore961afb2009-10-22 07:08:30 +00001008 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001009 }
Douglas Gregore961afb2009-10-22 07:08:30 +00001010
John McCall5b3f9132009-11-22 01:44:31 +00001011 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
1012 return ExprError();
John McCallf7a1a742009-11-24 19:00:30 +00001013 return Owned(BuildMemberExpr(Context, This, true, &SS, D, Loc, MemberType,
1014 TemplateArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +00001015 }
1016
John McCallba135432009-11-21 08:51:07 +00001017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +00001018 if (!Method->isStatic())
1019 return ExprError(Diag(Loc, diag::err_member_call_without_object));
John McCallba135432009-11-21 08:51:07 +00001020 }
1021
1022 if (isa<FieldDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +00001023 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
John McCallba135432009-11-21 08:51:07 +00001024 if (MD->isStatic()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001025 // "invalid use of member 'x' in static member function"
John McCall5b3f9132009-11-22 01:44:31 +00001026 Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallba135432009-11-21 08:51:07 +00001027 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +00001028 return ExprError();
John McCallba135432009-11-21 08:51:07 +00001029 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001030 }
1031
Douglas Gregor88a35142008-12-22 05:46:06 +00001032 // Any other ways we could have found the field in a well-formed
1033 // program would have been turned into implicit member expressions
1034 // above.
John McCall5b3f9132009-11-22 01:44:31 +00001035 Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallba135432009-11-21 08:51:07 +00001036 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +00001037 return ExprError();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001038 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001039
John McCall5b3f9132009-11-22 01:44:31 +00001040 // We're not in an implicit member-reference context, but the lookup
1041 // results might not require an instance. Try to build a non-member
1042 // decl reference.
John McCallf7a1a742009-11-24 19:00:30 +00001043 if (TemplateArgs)
1044 return BuildTemplateIdExpr(SS, R, /* ADL */ false, *TemplateArgs);
1045
John McCall5b3f9132009-11-22 01:44:31 +00001046 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
John McCallba135432009-11-21 08:51:07 +00001047}
1048
John McCallf7a1a742009-11-24 19:00:30 +00001049bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001050 const LookupResult &R,
1051 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001052 // Only when used directly as the postfix-expression of a call.
1053 if (!HasTrailingLParen)
1054 return false;
1055
1056 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001057 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001058 return false;
1059
1060 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001061 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001062 return false;
1063
1064 // Turn off ADL when we find certain kinds of declarations during
1065 // normal lookup:
1066 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1067 NamedDecl *D = *I;
1068
1069 // C++0x [basic.lookup.argdep]p3:
1070 // -- a declaration of a class member
1071 // Since using decls preserve this property, we check this on the
1072 // original decl.
1073 if (D->getDeclContext()->isRecord())
1074 return false;
1075
1076 // C++0x [basic.lookup.argdep]p3:
1077 // -- a block-scope function declaration that is not a
1078 // using-declaration
1079 // NOTE: we also trigger this for function templates (in fact, we
1080 // don't check the decl type at all, since all other decl types
1081 // turn off ADL anyway).
1082 if (isa<UsingShadowDecl>(D))
1083 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1084 else if (D->getDeclContext()->isFunctionOrMethod())
1085 return false;
1086
1087 // C++0x [basic.lookup.argdep]p3:
1088 // -- a declaration that is neither a function or a function
1089 // template
1090 // And also for builtin functions.
1091 if (isa<FunctionDecl>(D)) {
1092 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1093
1094 // But also builtin functions.
1095 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1096 return false;
1097 } else if (!isa<FunctionTemplateDecl>(D))
1098 return false;
1099 }
1100
1101 return true;
1102}
1103
1104
John McCallba135432009-11-21 08:51:07 +00001105/// Diagnoses obvious problems with the use of the given declaration
1106/// as an expression. This is only actually called for lookups that
1107/// were not overloaded, and it doesn't promise that the declaration
1108/// will in fact be used.
1109static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1110 if (isa<TypedefDecl>(D)) {
1111 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1112 return true;
1113 }
1114
1115 if (isa<ObjCInterfaceDecl>(D)) {
1116 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1117 return true;
1118 }
1119
1120 if (isa<NamespaceDecl>(D)) {
1121 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1122 return true;
1123 }
1124
1125 return false;
1126}
1127
1128Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001129Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001130 LookupResult &R,
1131 bool NeedsADL) {
1132 assert(R.getResultKind() != LookupResult::FoundUnresolvedValue);
1133
John McCallf7a1a742009-11-24 19:00:30 +00001134 // If this isn't an overloaded result and we don't need ADL, just
1135 // build an ordinary singleton decl ref.
John McCall5b3f9132009-11-22 01:44:31 +00001136 if (!NeedsADL && !R.isOverloadedResult())
1137 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001138
1139 // We only need to check the declaration if there's exactly one
1140 // result, because in the overloaded case the results can only be
1141 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001142 if (R.isSingleResult() &&
1143 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001144 return ExprError();
1145
John McCallf7a1a742009-11-24 19:00:30 +00001146 bool Dependent
1147 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001148 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001149 = UnresolvedLookupExpr::Create(Context, Dependent,
1150 (NestedNameSpecifier*) SS.getScopeRep(),
1151 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001152 R.getLookupName(), R.getNameLoc(),
1153 NeedsADL, R.isOverloadedResult());
1154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1155 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001156
1157 return Owned(ULE);
1158}
1159
1160
1161/// \brief Complete semantic analysis for a reference to the given declaration.
1162Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001163Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001164 SourceLocation Loc, NamedDecl *D) {
1165 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001166 assert(!isa<FunctionTemplateDecl>(D) &&
1167 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001168 DeclarationName Name = D->getDeclName();
1169
1170 if (CheckDeclInExpr(*this, Loc, D))
1171 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001172
Steve Naroffdd972f22008-09-05 22:11:13 +00001173 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001174
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001175 // Check whether this declaration can be used. Note that we suppress
1176 // this check when we're going to perform argument-dependent lookup
1177 // on this function name, because this might not be the function
1178 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001179 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001180 return ExprError();
1181
Steve Naroffdd972f22008-09-05 22:11:13 +00001182 // Only create DeclRefExpr's for valid Decl's.
1183 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001184 return ExprError();
1185
Chris Lattner639e2d32008-10-20 05:16:36 +00001186 // If the identifier reference is inside a block, and it refers to a value
1187 // that is outside the block, create a BlockDeclRefExpr instead of a
1188 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1189 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001190 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001191 // We do not do this for things like enum constants, global variables, etc,
1192 // as they do not get snapshotted.
1193 //
1194 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001195 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001196 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001197 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001198 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001199 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001200 // This is to record that a 'const' was actually synthesize and added.
1201 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001202 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Eli Friedman5fdeae12009-03-22 23:00:19 +00001204 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001205 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001206 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001207 }
1208 // If this reference is not in a block or if the referenced variable is
1209 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001210
John McCallf7a1a742009-11-24 19:00:30 +00001211 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001212}
1213
Sebastian Redlcd965b92009-01-18 18:53:16 +00001214Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1215 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001216 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001219 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001220 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1221 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1222 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001224
Chris Lattnerfa28b302008-01-12 08:14:25 +00001225 // Pre-defined identifiers are of type char[x], where x is the length of the
1226 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Anders Carlsson3a082d82009-09-08 18:24:21 +00001228 Decl *currentDecl = getCurFunctionOrMethodDecl();
1229 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001230 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001231 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001232 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001233
Anders Carlsson773f3972009-09-11 01:22:35 +00001234 QualType ResTy;
1235 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1236 ResTy = Context.DependentTy;
1237 } else {
1238 unsigned Length =
1239 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001240
Anders Carlsson773f3972009-09-11 01:22:35 +00001241 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001242 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001243 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1244 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001245 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001246}
1247
Sebastian Redlcd965b92009-01-18 18:53:16 +00001248Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 llvm::SmallString<16> CharBuffer;
1250 CharBuffer.resize(Tok.getLength());
1251 const char *ThisTokBegin = &CharBuffer[0];
1252 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1255 Tok.getLocation(), PP);
1256 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001257 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001258
1259 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1260
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001261 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1262 Literal.isWide(),
1263 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001264}
1265
Sebastian Redlcd965b92009-01-18 18:53:16 +00001266Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1267 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1269 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001270 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001271 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001272 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001273 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 }
Ted Kremenek28396602009-01-13 23:19:12 +00001275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001277 // Add padding so that NumericLiteralParser can overread by one character.
1278 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001280
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 // Get the spelling of the token, which eliminates trigraphs, etc.
1282 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001283
Mike Stump1eb44332009-09-09 15:08:12 +00001284 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 Tok.getLocation(), PP);
1286 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001287 return ExprError();
1288
Chris Lattner5d661452007-08-26 03:42:43 +00001289 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001290
Chris Lattner5d661452007-08-26 03:42:43 +00001291 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001292 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001293 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001294 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001295 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001296 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001297 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001298 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001299
1300 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1301
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001302 // isExact will be set by GetFloatValue().
1303 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001304 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1305 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001306
Chris Lattner5d661452007-08-26 03:42:43 +00001307 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001308 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001309 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001310 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001311
Neil Boothb9449512007-08-29 22:00:19 +00001312 // long long is a C99 feature.
1313 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001314 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001315 Diag(Tok.getLocation(), diag::ext_longlong);
1316
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001318 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001319
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 if (Literal.GetIntegerValue(ResultVal)) {
1321 // If this value didn't fit into uintmax_t, warn and force to ull.
1322 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001323 Ty = Context.UnsignedLongLongTy;
1324 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001325 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 } else {
1327 // If this value fits into a ULL, try to figure out what else it fits into
1328 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001329
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1331 // be an unsigned int.
1332 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1333
1334 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001335 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001336 if (!Literal.isLong && !Literal.isLongLong) {
1337 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001338 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // Does it fit in a unsigned int?
1341 if (ResultVal.isIntN(IntSize)) {
1342 // Does it fit in a signed int?
1343 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001344 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001346 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001347 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001350
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001352 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001353 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001354
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 // Does it fit in a unsigned long?
1356 if (ResultVal.isIntN(LongSize)) {
1357 // Does it fit in a signed long?
1358 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001359 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001361 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001362 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001364 }
1365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001367 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001368 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 // Does it fit in a unsigned long long?
1371 if (ResultVal.isIntN(LongLongSize)) {
1372 // Does it fit in a signed long long?
1373 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001374 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001376 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001377 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 }
1379 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 // If we still couldn't decide a type, we probably have something that
1382 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001383 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001385 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001386 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001388
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001389 if (ResultVal.getBitWidth() != Width)
1390 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001392 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001394
Chris Lattner5d661452007-08-26 03:42:43 +00001395 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1396 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001397 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001398 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001399
1400 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001401}
1402
Sebastian Redlcd965b92009-01-18 18:53:16 +00001403Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1404 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001405 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001406 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001407 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001408}
1409
1410/// The UsualUnaryConversions() function is *not* called by this routine.
1411/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001412bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001413 SourceLocation OpLoc,
1414 const SourceRange &ExprRange,
1415 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001416 if (exprType->isDependentType())
1417 return false;
1418
Sebastian Redl5d484e82009-11-23 17:18:46 +00001419 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1420 // the result is the size of the referenced type."
1421 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1422 // result shall be the alignment of the referenced type."
1423 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1424 exprType = Ref->getPointeeType();
1425
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001427 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001428 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001429 if (isSizeof)
1430 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1431 return false;
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Chris Lattner1efaa952009-04-24 00:30:45 +00001434 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001435 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001436 Diag(OpLoc, diag::ext_sizeof_void_type)
1437 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001438 return false;
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Chris Lattner1efaa952009-04-24 00:30:45 +00001441 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001442 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001443 PDiag(diag::err_alignof_incomplete_type)
1444 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001445 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Chris Lattner1efaa952009-04-24 00:30:45 +00001447 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001448 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001449 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001450 << exprType << isSizeof << ExprRange;
1451 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chris Lattner1efaa952009-04-24 00:30:45 +00001454 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001455}
1456
Chris Lattner31e21e02009-01-24 20:17:12 +00001457bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1458 const SourceRange &ExprRange) {
1459 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001460
Mike Stump1eb44332009-09-09 15:08:12 +00001461 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001462 if (isa<DeclRefExpr>(E))
1463 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001464
1465 // Cannot know anything else if the expression is dependent.
1466 if (E->isTypeDependent())
1467 return false;
1468
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001469 if (E->getBitField()) {
1470 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1471 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001472 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001473
1474 // Alignment of a field access is always okay, so long as it isn't a
1475 // bit-field.
1476 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001477 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001478 return false;
1479
Chris Lattner31e21e02009-01-24 20:17:12 +00001480 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1481}
1482
Douglas Gregorba498172009-03-13 21:01:28 +00001483/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001484Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001485Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1486 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001487 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001488 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001489 return ExprError();
1490
John McCall5ab75172009-11-04 07:28:41 +00001491 QualType T = DInfo->getType();
1492
Douglas Gregorba498172009-03-13 21:01:28 +00001493 if (!T->isDependentType() &&
1494 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1495 return ExprError();
1496
1497 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001498 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001499 Context.getSizeType(), OpLoc,
1500 R.getEnd()));
1501}
1502
1503/// \brief Build a sizeof or alignof expression given an expression
1504/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001505Action::OwningExprResult
1506Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001507 bool isSizeOf, SourceRange R) {
1508 // Verify that the operand is valid.
1509 bool isInvalid = false;
1510 if (E->isTypeDependent()) {
1511 // Delay type-checking for type-dependent expressions.
1512 } else if (!isSizeOf) {
1513 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001514 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001515 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1516 isInvalid = true;
1517 } else {
1518 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1519 }
1520
1521 if (isInvalid)
1522 return ExprError();
1523
1524 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1525 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1526 Context.getSizeType(), OpLoc,
1527 R.getEnd()));
1528}
1529
Sebastian Redl05189992008-11-11 17:56:53 +00001530/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1531/// the same for @c alignof and @c __alignof
1532/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001533Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001534Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1535 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001537 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001538
Sebastian Redl05189992008-11-11 17:56:53 +00001539 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001540 DeclaratorInfo *DInfo;
1541 (void) GetTypeFromParser(TyOrEx, &DInfo);
1542 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001543 }
Sebastian Redl05189992008-11-11 17:56:53 +00001544
Douglas Gregorba498172009-03-13 21:01:28 +00001545 Expr *ArgEx = (Expr *)TyOrEx;
1546 Action::OwningExprResult Result
1547 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1548
1549 if (Result.isInvalid())
1550 DeleteExpr(ArgEx);
1551
1552 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001553}
1554
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001555QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001556 if (V->isTypeDependent())
1557 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Chris Lattnercc26ed72007-08-26 05:39:26 +00001559 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001560 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001561 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Chris Lattnercc26ed72007-08-26 05:39:26 +00001563 // Otherwise they pass through real integer and floating point types here.
1564 if (V->getType()->isArithmeticType())
1565 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Chris Lattnercc26ed72007-08-26 05:39:26 +00001567 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001568 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1569 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001570 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001571}
1572
1573
Reid Spencer5f016e22007-07-11 17:01:13 +00001574
Sebastian Redl0eb23302009-01-19 00:08:26 +00001575Action::OwningExprResult
1576Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1577 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 UnaryOperator::Opcode Opc;
1579 switch (Kind) {
1580 default: assert(0 && "Unknown unary op!");
1581 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1582 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1583 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001584
Eli Friedmane4216e92009-11-18 03:38:04 +00001585 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001586}
1587
Sebastian Redl0eb23302009-01-19 00:08:26 +00001588Action::OwningExprResult
1589Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1590 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001591 // Since this might be a postfix expression, get rid of ParenListExprs.
1592 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1593
Sebastian Redl0eb23302009-01-19 00:08:26 +00001594 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1595 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Douglas Gregor337c6b92008-11-19 17:17:41 +00001597 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001598 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1599 Base.release();
1600 Idx.release();
1601 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1602 Context.DependentTy, RLoc));
1603 }
1604
Mike Stump1eb44332009-09-09 15:08:12 +00001605 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001606 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001607 LHSExp->getType()->isEnumeralType() ||
1608 RHSExp->getType()->isRecordType() ||
1609 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001610 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001611 }
1612
Sebastian Redlf322ed62009-10-29 20:17:01 +00001613 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1614}
1615
1616
1617Action::OwningExprResult
1618Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1619 ExprArg Idx, SourceLocation RLoc) {
1620 Expr *LHSExp = static_cast<Expr*>(Base.get());
1621 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1622
Chris Lattner12d9ff62007-07-16 00:14:47 +00001623 // Perform default conversions.
1624 DefaultFunctionArrayConversion(LHSExp);
1625 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001626
Chris Lattner12d9ff62007-07-16 00:14:47 +00001627 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001628
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001630 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001631 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001633 Expr *BaseExpr, *IndexExpr;
1634 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001635 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1636 BaseExpr = LHSExp;
1637 IndexExpr = RHSExp;
1638 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001639 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001640 BaseExpr = LHSExp;
1641 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001642 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001643 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001644 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001645 BaseExpr = RHSExp;
1646 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001647 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001648 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001649 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001650 BaseExpr = LHSExp;
1651 IndexExpr = RHSExp;
1652 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001653 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001654 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001655 // Handle the uncommon case of "123[Ptr]".
1656 BaseExpr = RHSExp;
1657 IndexExpr = LHSExp;
1658 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001659 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001660 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001661 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001662
Chris Lattner12d9ff62007-07-16 00:14:47 +00001663 // FIXME: need to deal with const...
1664 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001665 } else if (LHSTy->isArrayType()) {
1666 // If we see an array that wasn't promoted by
1667 // DefaultFunctionArrayConversion, it must be an array that
1668 // wasn't promoted because of the C90 rule that doesn't
1669 // allow promoting non-lvalue arrays. Warn, then
1670 // force the promotion here.
1671 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1672 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001673 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1674 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001675 LHSTy = LHSExp->getType();
1676
1677 BaseExpr = LHSExp;
1678 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001679 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001680 } else if (RHSTy->isArrayType()) {
1681 // Same as previous, except for 123[f().a] case
1682 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1683 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001684 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1685 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001686 RHSTy = RHSExp->getType();
1687
1688 BaseExpr = RHSExp;
1689 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001690 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001692 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1693 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001694 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001696 if (!(IndexExpr->getType()->isIntegerType() &&
1697 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001698 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1699 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001700
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001701 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001702 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1703 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001704 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1705
Douglas Gregore7450f52009-03-24 19:52:54 +00001706 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001707 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1708 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001709 // incomplete types are not object types.
1710 if (ResultType->isFunctionType()) {
1711 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1712 << ResultType << BaseExpr->getSourceRange();
1713 return ExprError();
1714 }
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Douglas Gregore7450f52009-03-24 19:52:54 +00001716 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001717 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001718 PDiag(diag::err_subscript_incomplete_type)
1719 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001720 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattner1efaa952009-04-24 00:30:45 +00001722 // Diagnose bad cases where we step over interface counts.
1723 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1724 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1725 << ResultType << BaseExpr->getSourceRange();
1726 return ExprError();
1727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Sebastian Redl0eb23302009-01-19 00:08:26 +00001729 Base.release();
1730 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001731 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001732 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001733}
1734
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001735QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001736CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001737 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001738 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001739 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1740 // see FIXME there.
1741 //
1742 // FIXME: This logic can be greatly simplified by splitting it along
1743 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001744 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001745
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001746 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001747 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001748
Mike Stumpeed9cac2009-02-19 03:04:26 +00001749 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001750 // special names that indicate a subset of exactly half the elements are
1751 // to be selected.
1752 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001753
Nate Begeman353417a2009-01-18 01:47:54 +00001754 // This flag determines whether or not CompName has an 's' char prefix,
1755 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001756 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001757
1758 // Check that we've found one of the special components, or that the component
1759 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001760 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001761 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1762 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001763 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001764 do
1765 compStr++;
1766 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001767 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001768 do
1769 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001770 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001771 }
Nate Begeman353417a2009-01-18 01:47:54 +00001772
Mike Stumpeed9cac2009-02-19 03:04:26 +00001773 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001774 // We didn't get to the end of the string. This means the component names
1775 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001776 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1777 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001778 return QualType();
1779 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001780
Nate Begeman353417a2009-01-18 01:47:54 +00001781 // Ensure no component accessor exceeds the width of the vector type it
1782 // operates on.
1783 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001784 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001785
1786 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001787 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001788
1789 while (*compStr) {
1790 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1791 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1792 << baseType << SourceRange(CompLoc);
1793 return QualType();
1794 }
1795 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001796 }
Nate Begeman8a997642008-05-09 06:41:27 +00001797
Nate Begeman353417a2009-01-18 01:47:54 +00001798 // If this is a halving swizzle, verify that the base type has an even
1799 // number of elements.
1800 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001801 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001802 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001803 return QualType();
1804 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001805
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001806 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001807 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001808 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001809 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001810 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001811 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001812 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001813 if (HexSwizzle)
1814 CompSize--;
1815
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001816 if (CompSize == 1)
1817 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001818
Nate Begeman213541a2008-04-18 23:10:10 +00001819 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001820 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001821 // diagostics look bad. We want extended vector types to appear built-in.
1822 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1823 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1824 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001825 }
1826 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001827}
1828
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001829static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001830 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001831 const Selector &Sel,
1832 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Anders Carlsson8f28f992009-08-26 18:25:21 +00001834 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001835 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001836 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001837 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001839 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1840 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001841 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001842 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001843 return D;
1844 }
1845 return 0;
1846}
1847
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001848static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001849 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001850 const Selector &Sel,
1851 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001852 // Check protocols on qualified interfaces.
1853 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001854 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001855 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001856 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001857 GDecl = PD;
1858 break;
1859 }
1860 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001861 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001862 GDecl = OMD;
1863 break;
1864 }
1865 }
1866 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001867 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001868 E = QIdTy->qual_end(); I != E; ++I) {
1869 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001870 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001871 if (GDecl)
1872 return GDecl;
1873 }
1874 }
1875 return GDecl;
1876}
Chris Lattner76a642f2009-02-15 22:43:40 +00001877
Mike Stump1eb44332009-09-09 15:08:12 +00001878Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001879Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001880 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001881 DeclarationName MemberName,
John McCalld5532b62009-11-23 01:53:49 +00001882 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001883 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1884 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001885 if (SS && SS->isInvalid())
1886 return ExprError();
1887
Nate Begeman2ef13e52009-08-10 23:49:36 +00001888 // Since this might be a postfix expression, get rid of ParenListExprs.
1889 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1890
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001891 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001892 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Steve Naroff3cc4af82007-12-16 21:42:28 +00001894 // Perform default conversions.
1895 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001896
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001897 QualType BaseType = BaseExpr->getType();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00001898
1899 // If the user is trying to apply -> or . to a function pointer
1900 // type, it's probably because the forgot parentheses to call that
1901 // function. Suggest the addition of those parentheses, build the
1902 // call, and continue on.
1903 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1904 if (const FunctionProtoType *Fun
1905 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1906 QualType ResultTy = Fun->getResultType();
1907 if (Fun->getNumArgs() == 0 &&
1908 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1909 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1910 ResultTy->getAs<PointerType>()->getPointeeType()
1911 ->isRecordType()))) {
1912 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1913 Diag(Loc, diag::err_member_reference_needs_call)
1914 << QualType(Fun, 0)
1915 << CodeModificationHint::CreateInsertion(Loc, "()");
1916
1917 OwningExprResult NewBase
1918 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1919 MultiExprArg(*this, 0, 0), 0, Loc);
1920 if (NewBase.isInvalid())
1921 return move(NewBase);
1922
1923 BaseExpr = NewBase.takeAs<Expr>();
1924 DefaultFunctionArrayConversion(BaseExpr);
1925 BaseType = BaseExpr->getType();
1926 }
1927 }
1928 }
1929
David Chisnall0f436562009-08-17 16:35:33 +00001930 // If this is an Objective-C pseudo-builtin and a definition is provided then
1931 // use that.
1932 if (BaseType->isObjCIdType()) {
1933 // We have an 'id' type. Rather than fall through, we check if this
1934 // is a reference to 'isa'.
1935 if (BaseType != Context.ObjCIdRedefinitionType) {
1936 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001937 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001938 }
David Chisnall0f436562009-08-17 16:35:33 +00001939 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00001940 // If this is an Objective-C pseudo-builtin and a definition is provided then
1941 // use that.
1942 if (Context.isObjCSelType(BaseType)) {
1943 // We have an 'SEL' type. Rather than fall through, we check if this
1944 // is a reference to 'sel_id'.
1945 if (BaseType != Context.ObjCSelRedefinitionType) {
1946 BaseType = Context.ObjCSelRedefinitionType;
1947 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
1948 }
1949 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001950 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001951
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001952 // Handle properties on ObjC 'Class' types.
1953 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1954 // Also must look for a getter name which uses property syntax.
1955 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1956 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1957 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1958 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1959 ObjCMethodDecl *Getter;
1960 // FIXME: need to also look locally in the implementation.
1961 if ((Getter = IFace->lookupClassMethod(Sel))) {
1962 // Check the use of this method.
1963 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1964 return ExprError();
1965 }
1966 // If we found a getter then this may be a valid dot-reference, we
1967 // will look for the matching setter, in case it is needed.
1968 Selector SetterSel =
1969 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1970 PP.getSelectorTable(), Member);
1971 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1972 if (!Setter) {
1973 // If this reference is in an @implementation, also check for 'private'
1974 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001975 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001976 }
1977 // Look through local category implementations associated with the class.
1978 if (!Setter)
1979 Setter = IFace->getCategoryClassMethod(SetterSel);
1980
1981 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1982 return ExprError();
1983
1984 if (Getter || Setter) {
1985 QualType PType;
1986
1987 if (Getter)
1988 PType = Getter->getResultType();
1989 else
1990 // Get the expression type from Setter's incoming parameter.
1991 PType = (*(Setter->param_end() -1))->getType();
1992 // FIXME: we must check that the setter has property type.
1993 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1994 PType,
1995 Setter, MemberLoc, BaseExpr));
1996 }
1997 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1998 << MemberName << BaseType);
1999 }
2000 }
2001
2002 if (BaseType->isObjCClassType() &&
2003 BaseType != Context.ObjCClassRedefinitionType) {
2004 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002005 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002006 }
2007
Chris Lattner68a057b2008-07-21 04:36:39 +00002008 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2009 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00002011 if (BaseType->isDependentType()) {
2012 NestedNameSpecifier *Qualifier = 0;
2013 if (SS) {
2014 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2015 if (!FirstQualifierInScope)
2016 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
John McCall865d4472009-11-19 22:55:06 +00002019 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002020 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002021 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002022 FirstQualifierInScope,
2023 MemberName,
2024 MemberLoc,
John McCalld5532b62009-11-23 01:53:49 +00002025 ExplicitTemplateArgs));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002026 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002027 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002028 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002029 else if (BaseType->isObjCObjectPointerType())
2030 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002031 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002032 return ExprError(Diag(MemberLoc,
2033 diag::err_typecheck_member_reference_arrow)
2034 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002035 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002036 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002037 // (so we'll report an error for)
2038 // T* t;
2039 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002040 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002041 // In Obj-C++, however, the above expression is valid, since it could be
2042 // accessing the 'f' property if T is an Obj-C interface. The extra check
2043 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002044 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002045
Mike Stump1eb44332009-09-09 15:08:12 +00002046 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002047 !PT->getPointeeType()->isRecordType())) {
2048 NestedNameSpecifier *Qualifier = 0;
2049 if (SS) {
2050 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2051 if (!FirstQualifierInScope)
2052 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
John McCall865d4472009-11-19 22:55:06 +00002055 return Owned(CXXDependentScopeMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002056 BaseExpr, false,
2057 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002058 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002059 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002060 FirstQualifierInScope,
2061 MemberName,
2062 MemberLoc,
John McCalld5532b62009-11-23 01:53:49 +00002063 ExplicitTemplateArgs));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002064 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002065 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002066
Chris Lattner68a057b2008-07-21 04:36:39 +00002067 // Handle field access to simple records. This also handles access to fields
2068 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002069 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002070 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002071 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002072 PDiag(diag::err_typecheck_incomplete_tag)
2073 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002074 return ExprError();
2075
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002076 DeclContext *DC = RDecl;
2077 if (SS && SS->isSet()) {
2078 // If the member name was a qualified-id, look into the
2079 // nested-name-specifier.
2080 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00002081
2082 if (!isa<TypeDecl>(DC)) {
2083 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2084 << DC << SS->getRange();
2085 return ExprError();
2086 }
Mike Stump1eb44332009-09-09 15:08:12 +00002087
2088 // FIXME: If DC is not computable, we should build a
John McCall865d4472009-11-19 22:55:06 +00002089 // CXXDependentScopeMemberExpr.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002090 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2091 }
2092
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002093 // The record definition is complete, now make sure the member is valid.
John McCalla24dc2e2009-11-17 02:14:36 +00002094 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
2095 LookupQualifiedName(Result, DC);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002096
John McCallf36e02d2009-10-09 21:13:30 +00002097 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00002098 return ExprError(Diag(MemberLoc, diag::err_no_member)
2099 << MemberName << DC << BaseExpr->getSourceRange());
John McCalla24dc2e2009-11-17 02:14:36 +00002100 if (Result.isAmbiguous())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002101 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002102
John McCallf36e02d2009-10-09 21:13:30 +00002103 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2104
Douglas Gregora38c6872009-09-03 16:14:30 +00002105 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00002106 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002107 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002108 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002109 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00002110 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Douglas Gregora38c6872009-09-03 16:14:30 +00002112 if (BaseTypeCanon != MemberTypeCanon &&
2113 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2114 return ExprError(Diag(SS->getBeginLoc(),
2115 diag::err_not_direct_base_or_virtual)
2116 << MemberTypeCanon << BaseTypeCanon);
2117 }
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Chris Lattner56cd21b2009-02-13 22:08:30 +00002119 // If the decl being referenced had an error, return an error for this
2120 // sub-expr without emitting another error, in order to avoid cascading
2121 // error cases.
2122 if (MemberDecl->isInvalidDecl())
2123 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002124
Anders Carlsson0f728562009-09-10 20:48:14 +00002125 bool ShouldCheckUse = true;
2126 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2127 // Don't diagnose the use of a virtual member function unless it's
2128 // explicitly qualified.
2129 if (MD->isVirtual() && (!SS || !SS->isSet()))
2130 ShouldCheckUse = false;
2131 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002132
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002133 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00002134 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002135 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002136
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002137 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002138 // We may have found a field within an anonymous union or struct
2139 // (C++ [class.union]).
2140 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002141 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002142 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002143
Douglas Gregor86f19402008-12-20 23:49:58 +00002144 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002145 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002146 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002147 MemberType = Ref->getPointeeType();
2148 else {
John McCall0953e762009-09-24 19:53:00 +00002149 Qualifiers BaseQuals = BaseType.getQualifiers();
2150 BaseQuals.removeObjCGCAttr();
2151 if (FD->isMutable()) BaseQuals.removeConst();
2152
2153 Qualifiers MemberQuals
2154 = Context.getCanonicalType(MemberType).getQualifiers();
2155
2156 Qualifiers Combined = BaseQuals + MemberQuals;
2157 if (Combined != MemberQuals)
2158 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002159 }
Eli Friedman51019072008-02-06 22:48:16 +00002160
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002161 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002162 if (PerformObjectMemberConversion(BaseExpr, FD))
2163 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002164 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002165 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002166 }
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002168 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2169 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002170 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2171 Var, MemberLoc,
2172 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002173 }
2174 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2175 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002176 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2177 MemberFn, MemberLoc,
2178 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002179 }
Mike Stump1eb44332009-09-09 15:08:12 +00002180 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002181 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2182 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002183
John McCalld5532b62009-11-23 01:53:49 +00002184 if (ExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002185 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2186 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002187 SS? SS->getRange() : SourceRange(),
John McCalld5532b62009-11-23 01:53:49 +00002188 FunTmpl, MemberLoc,
2189 ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002190 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002192 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2193 FunTmpl, MemberLoc,
2194 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002195 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002196 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002197 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
John McCalld5532b62009-11-23 01:53:49 +00002198 if (ExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002199 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2200 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002201 SS? SS->getRange() : SourceRange(),
John McCalld5532b62009-11-23 01:53:49 +00002202 Ovl, MemberLoc, ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002203 Context.OverloadTy));
2204
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002205 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2206 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002207 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002208 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2209 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002210 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2211 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002212 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002213 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002214 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002215 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002216
Douglas Gregor86f19402008-12-20 23:49:58 +00002217 // We found a declaration kind that we didn't expect. This is a
2218 // generic error message that tells the user that she can't refer
2219 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002220 return ExprError(Diag(MemberLoc,
2221 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002222 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002223 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002224
Douglas Gregora71d8192009-09-04 17:36:40 +00002225 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2226 // into a record type was handled above, any destructor we see here is a
2227 // pseudo-destructor.
2228 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2229 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002230 // The left hand side of the dot operator shall be of scalar type. The
2231 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002232 // type.
2233 if (!BaseType->isScalarType())
2234 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2235 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Douglas Gregora71d8192009-09-04 17:36:40 +00002237 // [...] The type designated by the pseudo-destructor-name shall be the
2238 // same as the object type.
2239 if (!MemberName.getCXXNameType()->isDependentType() &&
2240 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2241 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2242 << BaseType << MemberName.getCXXNameType()
2243 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002244
2245 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002246 // the form
2247 //
Mike Stump1eb44332009-09-09 15:08:12 +00002248 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2249 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002250 // shall designate the same scalar type.
2251 //
2252 // FIXME: DPG can't see any way to trigger this particular clause, so it
2253 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregora71d8192009-09-04 17:36:40 +00002255 // FIXME: We've lost the precise spelling of the type by going through
2256 // DeclarationName. Can we do better?
2257 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002258 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002259 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002260 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002261 SS? SS->getRange() : SourceRange(),
2262 MemberName.getCXXNameType(),
2263 MemberLoc));
2264 }
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Chris Lattnera38e6b12008-07-21 04:59:05 +00002266 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2267 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002268 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2269 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002270 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002271 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002272 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002273 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002274 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2275
Steve Naroffc70e8d92009-07-16 00:25:06 +00002276 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2277 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002278 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Steve Naroffc70e8d92009-07-16 00:25:06 +00002280 if (IV) {
2281 // If the decl being referenced had an error, return an error for this
2282 // sub-expr without emitting another error, in order to avoid cascading
2283 // error cases.
2284 if (IV->isInvalidDecl())
2285 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002286
Steve Naroffc70e8d92009-07-16 00:25:06 +00002287 // Check whether we can reference this field.
2288 if (DiagnoseUseOfDecl(IV, MemberLoc))
2289 return ExprError();
2290 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2291 IV->getAccessControl() != ObjCIvarDecl::Package) {
2292 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2293 if (ObjCMethodDecl *MD = getCurMethodDecl())
2294 ClassOfMethodDecl = MD->getClassInterface();
2295 else if (ObjCImpDecl && getCurFunctionDecl()) {
2296 // Case of a c-function declared inside an objc implementation.
2297 // FIXME: For a c-style function nested inside an objc implementation
2298 // class, there is no implementation context available, so we pass
2299 // down the context as argument to this routine. Ideally, this context
2300 // need be passed down in the AST node and somehow calculated from the
2301 // AST for a function decl.
2302 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002303 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002304 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2305 ClassOfMethodDecl = IMPD->getClassInterface();
2306 else if (ObjCCategoryImplDecl* CatImplClass =
2307 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2308 ClassOfMethodDecl = CatImplClass->getClassInterface();
2309 }
Mike Stump1eb44332009-09-09 15:08:12 +00002310
2311 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2312 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002313 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002314 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002315 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002316 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2317 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002318 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002319 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002320 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002321
2322 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2323 MemberLoc, BaseExpr,
2324 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002325 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002326 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002327 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002328 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002329 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002330 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002331 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002332 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002333 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002334 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002335 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Steve Naroff14108da2009-07-10 23:34:53 +00002337 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002338 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002339 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2340 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2341 // Check the use of this declaration
2342 if (DiagnoseUseOfDecl(PD, MemberLoc))
2343 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Steve Naroff14108da2009-07-10 23:34:53 +00002345 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2346 MemberLoc, BaseExpr));
2347 }
2348 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2349 // Check the use of this method.
2350 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2351 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Steve Naroff14108da2009-07-10 23:34:53 +00002353 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002354 OMD->getResultType(),
2355 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002356 NULL, 0));
2357 }
2358 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002359
Steve Naroff14108da2009-07-10 23:34:53 +00002360 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002361 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002362 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002363 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2364 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002365 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002366 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002367 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2368 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2369 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002370 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Daniel Dunbar2307d312008-09-03 01:05:41 +00002372 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002373 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002374 // Check whether we can reference this property.
2375 if (DiagnoseUseOfDecl(PD, MemberLoc))
2376 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002377 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002378 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002379 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002380 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2381 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002382 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002383 MemberLoc, BaseExpr));
2384 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002385 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002386 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2387 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002388 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002389 // Check whether we can reference this property.
2390 if (DiagnoseUseOfDecl(PD, MemberLoc))
2391 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002392
Steve Naroff6ece14c2009-01-21 00:14:39 +00002393 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002394 MemberLoc, BaseExpr));
2395 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002396 // If that failed, look for an "implicit" property by seeing if the nullary
2397 // selector is implemented.
2398
2399 // FIXME: The logic for looking up nullary and unary selectors should be
2400 // shared with the code in ActOnInstanceMessage.
2401
Anders Carlsson8f28f992009-08-26 18:25:21 +00002402 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002403 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002404
Daniel Dunbar2307d312008-09-03 01:05:41 +00002405 // If this reference is in an @implementation, check for 'private' methods.
2406 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002407 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002408
Steve Naroff7692ed62008-10-22 19:16:27 +00002409 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002410 if (!Getter)
2411 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002412 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002413 // Check if we can reference this property.
2414 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2415 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002416 }
2417 // If we found a getter then this may be a valid dot-reference, we
2418 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002419 Selector SetterSel =
2420 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002421 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002422 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002423 if (!Setter) {
2424 // If this reference is in an @implementation, also check for 'private'
2425 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002426 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002427 }
2428 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002429 if (!Setter)
2430 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002431
Steve Naroff1ca66942009-03-11 13:48:17 +00002432 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2433 return ExprError();
2434
2435 if (Getter || Setter) {
2436 QualType PType;
2437
2438 if (Getter)
2439 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002440 else
2441 // Get the expression type from Setter's incoming parameter.
2442 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002443 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002444 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002445 Setter, MemberLoc, BaseExpr));
2446 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002447 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002448 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002449 }
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Steve Narofff242b1b2009-07-24 17:54:45 +00002451 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002452 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002453 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002454 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002455 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2456 Context.getObjCIdType()));
2457
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002458 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002459 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002460 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002461 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2462 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002463 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002464 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002465 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002466 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002467
Douglas Gregor214f31a2009-03-27 06:00:30 +00002468 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2469 << BaseType << BaseExpr->getSourceRange();
2470
Douglas Gregor214f31a2009-03-27 06:00:30 +00002471 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002472}
2473
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002474Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2475 SourceLocation OpLoc,
2476 tok::TokenKind OpKind,
2477 const CXXScopeSpec &SS,
2478 UnqualifiedId &Member,
2479 DeclPtrTy ObjCImpDecl,
2480 bool HasTrailingLParen) {
2481 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2482 TemplateName Template
2483 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2484
2485 // FIXME: We're going to end up looking up the template based on its name,
2486 // twice!
2487 DeclarationName Name;
2488 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2489 Name = ActualTemplate->getDeclName();
2490 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2491 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002492 else {
2493 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2494 if (DTN->isIdentifier())
2495 Name = DTN->getIdentifier();
2496 else
2497 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2498 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002499
2500 // Translate the parser's template argument list in our AST format.
2501 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2502 Member.TemplateId->getTemplateArgs(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002503 Member.TemplateId->NumArgs);
2504
John McCalld5532b62009-11-23 01:53:49 +00002505 TemplateArgumentListInfo TemplateArgs;
2506 TemplateArgs.setLAngleLoc(Member.TemplateId->LAngleLoc);
2507 TemplateArgs.setRAngleLoc(Member.TemplateId->RAngleLoc);
2508 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002509 TemplateArgsPtr.release();
2510
2511 // Do we have the save the actual template name? We might need it...
2512 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2513 Member.TemplateId->TemplateNameLoc,
John McCalld5532b62009-11-23 01:53:49 +00002514 Name, &TemplateArgs, DeclPtrTy(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002515 &SS);
2516 }
2517
2518 // FIXME: We lose a lot of source information by mapping directly to the
2519 // DeclarationName.
2520 OwningExprResult Result
2521 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2522 Member.getSourceRange().getBegin(),
2523 GetNameFromUnqualifiedId(Member),
2524 ObjCImpDecl, &SS);
2525
2526 if (Result.isInvalid() || HasTrailingLParen ||
2527 Member.getKind() != UnqualifiedId::IK_DestructorName)
2528 return move(Result);
2529
2530 // The only way a reference to a destructor can be used is to
2531 // immediately call them. Since the next token is not a '(', produce a
2532 // diagnostic and build the call now.
2533 Expr *E = (Expr *)Result.get();
2534 SourceLocation ExpectedLParenLoc
2535 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2536 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2537 << isa<CXXPseudoDestructorExpr>(E)
2538 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2539
2540 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2541 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002542}
2543
Anders Carlsson56c5e332009-08-25 03:49:14 +00002544Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2545 FunctionDecl *FD,
2546 ParmVarDecl *Param) {
2547 if (Param->hasUnparsedDefaultArg()) {
2548 Diag (CallLoc,
2549 diag::err_use_of_default_argument_to_function_declared_later) <<
2550 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002551 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002552 diag::note_default_argument_declared_here);
2553 } else {
2554 if (Param->hasUninstantiatedDefaultArg()) {
2555 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2556
2557 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002558 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002559
Mike Stump1eb44332009-09-09 15:08:12 +00002560 InstantiatingTemplate Inst(*this, CallLoc, Param,
2561 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002562 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002563
John McCallce3ff2b2009-08-25 22:02:44 +00002564 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002565 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002566 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002567
2568 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002569 /*FIXME:EqualLoc*/
2570 UninstExpr->getSourceRange().getBegin()))
2571 return ExprError();
2572 }
Mike Stump1eb44332009-09-09 15:08:12 +00002573
Anders Carlsson56c5e332009-08-25 03:49:14 +00002574 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Anders Carlsson56c5e332009-08-25 03:49:14 +00002576 // If the default expression creates temporaries, we need to
2577 // push them to the current stack of expression temporaries so they'll
2578 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002579 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002580 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002581 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002582 "Can't destroy temporaries in a default argument expr!");
2583 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2584 ExprTemporaries.push_back(E->getTemporary(I));
2585 }
2586 }
2587
2588 // We already type-checked the argument, so we know it works.
2589 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2590}
2591
Douglas Gregor88a35142008-12-22 05:46:06 +00002592/// ConvertArgumentsForCall - Converts the arguments specified in
2593/// Args/NumArgs to the parameter types of the function FDecl with
2594/// function prototype Proto. Call is the call expression itself, and
2595/// Fn is the function expression. For a C++ member function, this
2596/// routine does not attempt to convert the object argument. Returns
2597/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002598bool
2599Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002600 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002601 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002602 Expr **Args, unsigned NumArgs,
2603 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002604 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002605 // assignment, to the types of the corresponding parameter, ...
2606 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002607 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002608
Douglas Gregor88a35142008-12-22 05:46:06 +00002609 // If too few arguments are available (and we don't have default
2610 // arguments for the remaining parameters), don't make the call.
2611 if (NumArgs < NumArgsInProto) {
2612 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2613 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2614 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002615 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002616 }
2617
2618 // If too many are passed and not variadic, error on the extras and drop
2619 // them.
2620 if (NumArgs > NumArgsInProto) {
2621 if (!Proto->isVariadic()) {
2622 Diag(Args[NumArgsInProto]->getLocStart(),
2623 diag::err_typecheck_call_too_many_args)
2624 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2625 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2626 Args[NumArgs-1]->getLocEnd());
2627 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002628 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002629 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002630 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002631 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002632 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00002633 VariadicCallType CallType =
2634 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
2635 if (Fn->getType()->isBlockPointerType())
2636 CallType = VariadicBlock; // Block
2637 else if (isa<MemberExpr>(Fn))
2638 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002639 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00002640 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002641 if (Invalid)
2642 return true;
2643 unsigned TotalNumArgs = AllArgs.size();
2644 for (unsigned i = 0; i < TotalNumArgs; ++i)
2645 Call->setArg(i, AllArgs[i]);
2646
2647 return false;
2648}
Mike Stumpeed9cac2009-02-19 03:04:26 +00002649
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002650bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
2651 FunctionDecl *FDecl,
2652 const FunctionProtoType *Proto,
2653 unsigned FirstProtoArg,
2654 Expr **Args, unsigned NumArgs,
2655 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00002656 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002657 unsigned NumArgsInProto = Proto->getNumArgs();
2658 unsigned NumArgsToCheck = NumArgs;
2659 bool Invalid = false;
2660 if (NumArgs != NumArgsInProto)
2661 // Use default arguments for missing arguments
2662 NumArgsToCheck = NumArgsInProto;
2663 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00002664 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002665 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002666 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002667
Douglas Gregor88a35142008-12-22 05:46:06 +00002668 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002669 if (ArgIx < NumArgs) {
2670 Arg = Args[ArgIx++];
2671
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002672 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2673 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002674 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002675 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002676 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002677
Douglas Gregor61366e92008-12-24 00:01:03 +00002678 // Pass the argument.
2679 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2680 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00002681
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00002682 if (!ProtoArgType->isReferenceType())
2683 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002684 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002685 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002686
Mike Stump1eb44332009-09-09 15:08:12 +00002687 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002688 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00002689 if (ArgExpr.isInvalid())
2690 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002691
Anders Carlsson56c5e332009-08-25 03:49:14 +00002692 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002693 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002694 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00002695 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002696
Douglas Gregor88a35142008-12-22 05:46:06 +00002697 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00002698 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002699 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002700 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002701 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002702 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002703 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00002704 }
2705 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002706 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002707}
2708
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002709/// \brief "Deconstruct" the function argument of a call expression to find
2710/// the underlying declaration (if any), the name of the called function,
2711/// whether argument-dependent lookup is available, whether it has explicit
2712/// template arguments, etc.
2713void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00002714 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002715 DeclarationName &Name,
2716 NestedNameSpecifier *&Qualifier,
2717 SourceRange &QualifierRange,
2718 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00002719 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002720 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00002721 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002722 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002723 Name = DeclarationName();
2724 Qualifier = 0;
2725 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00002726 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00002727 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002728 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00002729
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002730 // If we're directly calling a function, get the appropriate declaration.
2731 // Also, in C++, keep track of whether we should perform argument-dependent
2732 // lookup and whether there were any explicitly-specified template arguments.
2733 while (true) {
2734 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2735 FnExpr = IcExpr->getSubExpr();
2736 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002737 FnExpr = PExpr->getSubExpr();
2738 } else if (isa<UnaryOperator>(FnExpr) &&
2739 cast<UnaryOperator>(FnExpr)->getOpcode()
2740 == UnaryOperator::AddrOf) {
2741 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002742 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00002743 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
2744 ArgumentDependentLookup = false;
2745 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00002746 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002747 break;
John McCallba135432009-11-21 08:51:07 +00002748 } else if (UnresolvedLookupExpr *UnresLookup
2749 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
2750 Name = UnresLookup->getName();
2751 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
2752 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00002753 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00002754 if ((Qualifier = UnresLookup->getQualifier()))
2755 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00002756 if (UnresLookup->hasExplicitTemplateArgs()) {
2757 HasExplicitTemplateArguments = true;
2758 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002759 }
2760 break;
2761 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002762 break;
2763 }
2764 }
2765}
2766
Steve Narofff69936d2007-09-16 03:34:24 +00002767/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002768/// This provides the location of the left/right parens and a list of comma
2769/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002770Action::OwningExprResult
2771Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2772 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002773 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002774 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002775
2776 // Since this might be a postfix expression, get rid of ParenListExprs.
2777 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002779 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002780 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002781 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Douglas Gregor88a35142008-12-22 05:46:06 +00002783 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002784 // If this is a pseudo-destructor expression, build the call immediately.
2785 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2786 if (NumArgs > 0) {
2787 // Pseudo-destructor calls should not have any arguments.
2788 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2789 << CodeModificationHint::CreateRemoval(
2790 SourceRange(Args[0]->getLocStart(),
2791 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Douglas Gregora71d8192009-09-04 17:36:40 +00002793 for (unsigned I = 0; I != NumArgs; ++I)
2794 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Douglas Gregora71d8192009-09-04 17:36:40 +00002796 NumArgs = 0;
2797 }
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Douglas Gregora71d8192009-09-04 17:36:40 +00002799 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2800 RParenLoc));
2801 }
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Douglas Gregor17330012009-02-04 15:01:18 +00002803 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002804 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002805 // FIXME: Will need to cache the results of name lookup (including ADL) in
2806 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002807 bool Dependent = false;
2808 if (Fn->isTypeDependent())
2809 Dependent = true;
2810 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2811 Dependent = true;
2812
2813 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002814 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002815 Context.DependentTy, RParenLoc));
2816
2817 // Determine whether this is a call to an object (C++ [over.call.object]).
2818 if (Fn->getType()->isRecordType())
2819 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2820 CommaLocs, RParenLoc));
2821
Douglas Gregorfa047642009-02-04 00:32:51 +00002822 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002823 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2824 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2825 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2826 isa<CXXMethodDecl>(MemDecl) ||
2827 (isa<FunctionTemplateDecl>(MemDecl) &&
2828 isa<CXXMethodDecl>(
2829 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002830 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2831 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002832 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002833
2834 // Determine whether this is a call to a pointer-to-member function.
2835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2836 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2837 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002838 if (const FunctionProtoType *FPT =
2839 dyn_cast<FunctionProtoType>(BO->getType())) {
2840 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002841
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002842 ExprOwningPtr<CXXMemberCallExpr>
2843 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2844 NumArgs, ResultTy,
2845 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002846
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002847 if (CheckCallReturnType(FPT->getResultType(),
2848 BO->getRHS()->getSourceRange().getBegin(),
2849 TheCall.get(), 0))
2850 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002851
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002852 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2853 RParenLoc))
2854 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002855
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002856 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2857 }
2858 return ExprError(Diag(Fn->getLocStart(),
2859 diag::err_typecheck_call_not_function)
2860 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002861 }
2862 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002863 }
2864
Douglas Gregorfa047642009-02-04 00:32:51 +00002865 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002866 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002867 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00002868 llvm::SmallVector<NamedDecl*,8> Fns;
2869 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00002870 bool Overloaded;
2871 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002872 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00002873 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002874 NestedNameSpecifier *Qualifier = 0;
2875 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00002876 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00002877 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00002878 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002879
John McCall7453ed42009-11-22 00:44:51 +00002880 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
2881 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00002882
John McCall7453ed42009-11-22 00:44:51 +00002883 if (Overloaded || ADL) {
2884#ifndef NDEBUG
2885 if (ADL) {
2886 // To do ADL, we must have found an unqualified name.
2887 assert(UnqualifiedName && "found no unqualified name for ADL");
2888
2889 // We don't perform ADL for implicit declarations of builtins.
2890 // Verify that this was correctly set up.
2891 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
2892 FDecl->getBuiltinID() && FDecl->isImplicit())
2893 assert(0 && "performing ADL for builtin");
2894
2895 // We don't perform ADL in C.
2896 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
2897 }
2898
2899 if (Overloaded) {
2900 // To be overloaded, we must either have multiple functions or
2901 // at least one function template (which is effectively an
2902 // infinite set of functions).
2903 assert((Fns.size() > 1 ||
2904 (Fns.size() == 1 &&
2905 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
2906 && "unrecognized overload situation");
2907 }
2908#endif
2909
2910 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00002911 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00002912 LParenLoc, Args, NumArgs, CommaLocs,
2913 RParenLoc, ADL);
2914 if (!FDecl)
2915 return ExprError();
2916
2917 Fn = FixOverloadedFunctionReference(Fn, FDecl);
2918
2919 NDecl = FDecl;
2920 } else {
2921 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
2922 if (Fns.empty())
2923 NDecl = FDecl = 0;
2924 else {
2925 NDecl = Fns[0];
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002926 FDecl = dyn_cast<FunctionDecl>(NDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002927 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002928 }
Chris Lattner04421082008-04-08 04:40:51 +00002929
2930 // Promote the function operand.
2931 UsualUnaryConversions(Fn);
2932
Chris Lattner925e60d2007-12-28 05:29:59 +00002933 // Make the call expr early, before semantic checks. This guarantees cleanup
2934 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002935 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2936 Args, NumArgs,
2937 Context.BoolTy,
2938 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002939
Steve Naroffdd972f22008-09-05 22:11:13 +00002940 const FunctionType *FuncT;
2941 if (!Fn->getType()->isBlockPointerType()) {
2942 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2943 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002944 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002945 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002946 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2947 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002948 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002949 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002950 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002951 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002952 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002953 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002954 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2955 << Fn->getType() << Fn->getSourceRange());
2956
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002957 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002958 if (CheckCallReturnType(FuncT->getResultType(),
2959 Fn->getSourceRange().getBegin(), TheCall.get(),
2960 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002961 return ExprError();
2962
Chris Lattner925e60d2007-12-28 05:29:59 +00002963 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002964 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002965
Douglas Gregor72564e72009-02-26 23:50:07 +00002966 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002967 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002968 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002969 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002970 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002971 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002972
Douglas Gregor74734d52009-04-02 15:37:10 +00002973 if (FDecl) {
2974 // Check if we have too few/too many template arguments, based
2975 // on our knowledge of the function definition.
2976 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002977 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002978 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002979 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002980 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2981 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2982 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2983 }
2984 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002985 }
2986
Steve Naroffb291ab62007-08-28 23:30:39 +00002987 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002988 for (unsigned i = 0; i != NumArgs; i++) {
2989 Expr *Arg = Args[i];
2990 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002991 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2992 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002993 PDiag(diag::err_call_incomplete_argument)
2994 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002995 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002996 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002997 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002999
Douglas Gregor88a35142008-12-22 05:46:06 +00003000 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3001 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003002 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3003 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003004
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003005 // Check for sentinels
3006 if (NDecl)
3007 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Chris Lattner59907c42007-08-10 20:18:51 +00003009 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003010 if (FDecl) {
3011 if (CheckFunctionCall(FDecl, TheCall.get()))
3012 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003014 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003015 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3016 } else if (NDecl) {
3017 if (CheckBlockCall(NDecl, TheCall.get()))
3018 return ExprError();
3019 }
Chris Lattner59907c42007-08-10 20:18:51 +00003020
Anders Carlssonec74c592009-08-16 03:06:32 +00003021 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003022}
3023
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003024Action::OwningExprResult
3025Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3026 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003027 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003028 //FIXME: Preserve type source info.
3029 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003030 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003031 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003032 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003033
Eli Friedman6223c222008-05-20 05:22:08 +00003034 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003035 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003036 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3037 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003038 } else if (!literalType->isDependentType() &&
3039 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003040 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003041 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003042 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003043 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003044
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003045 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003046 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003047 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003048
Chris Lattner371f2582008-12-04 23:50:19 +00003049 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003050 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003051 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003052 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003053 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003054 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003055 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003056 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003057}
3058
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003059Action::OwningExprResult
3060Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003061 SourceLocation RBraceLoc) {
3062 unsigned NumInit = initlist.size();
3063 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003064
Steve Naroff08d92e42007-09-15 18:49:24 +00003065 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003066 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003067
Mike Stumpeed9cac2009-02-19 03:04:26 +00003068 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003069 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003070 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003071 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003072}
3073
Anders Carlsson82debc72009-10-18 18:12:03 +00003074static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3075 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003076 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003077 return CastExpr::CK_NoOp;
3078
3079 if (SrcTy->hasPointerRepresentation()) {
3080 if (DestTy->hasPointerRepresentation())
3081 return CastExpr::CK_BitCast;
3082 if (DestTy->isIntegerType())
3083 return CastExpr::CK_PointerToIntegral;
3084 }
3085
3086 if (SrcTy->isIntegerType()) {
3087 if (DestTy->isIntegerType())
3088 return CastExpr::CK_IntegralCast;
3089 if (DestTy->hasPointerRepresentation())
3090 return CastExpr::CK_IntegralToPointer;
3091 if (DestTy->isRealFloatingType())
3092 return CastExpr::CK_IntegralToFloating;
3093 }
3094
3095 if (SrcTy->isRealFloatingType()) {
3096 if (DestTy->isRealFloatingType())
3097 return CastExpr::CK_FloatingCast;
3098 if (DestTy->isIntegerType())
3099 return CastExpr::CK_FloatingToIntegral;
3100 }
3101
3102 // FIXME: Assert here.
3103 // assert(false && "Unhandled cast combination!");
3104 return CastExpr::CK_Unknown;
3105}
3106
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003107/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003108bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003109 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003110 CXXMethodDecl *& ConversionDecl,
3111 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003112 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003113 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3114 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003115
Eli Friedman199ea952009-08-15 19:02:19 +00003116 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003117
3118 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3119 // type needs to be scalar.
3120 if (castType->isVoidType()) {
3121 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003122 Kind = CastExpr::CK_ToVoid;
3123 return false;
3124 }
3125
3126 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003127 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003128 (castType->isStructureType() || castType->isUnionType())) {
3129 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003130 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003131 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3132 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003133 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003134 return false;
3135 }
3136
3137 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003138 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003139 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003140 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003141 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003142 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003143 if (Context.hasSameUnqualifiedType(Field->getType(),
3144 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003145 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3146 << castExpr->getSourceRange();
3147 break;
3148 }
3149 }
3150 if (Field == FieldEnd)
3151 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3152 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003153 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003154 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003155 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003156
3157 // Reject any other conversions to non-scalar types.
3158 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3159 << castType << castExpr->getSourceRange();
3160 }
3161
3162 if (!castExpr->getType()->isScalarType() &&
3163 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003164 return Diag(castExpr->getLocStart(),
3165 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003166 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003167 }
3168
Anders Carlsson16a89042009-10-16 05:23:41 +00003169 if (castType->isExtVectorType())
3170 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3171
Anders Carlssonc3516322009-10-16 02:48:28 +00003172 if (castType->isVectorType())
3173 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3174 if (castExpr->getType()->isVectorType())
3175 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3176
3177 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003178 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003179
Anders Carlsson16a89042009-10-16 05:23:41 +00003180 if (isa<ObjCSelectorExpr>(castExpr))
3181 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3182
Anders Carlssonc3516322009-10-16 02:48:28 +00003183 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003184 QualType castExprType = castExpr->getType();
3185 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3186 return Diag(castExpr->getLocStart(),
3187 diag::err_cast_pointer_from_non_pointer_int)
3188 << castExprType << castExpr->getSourceRange();
3189 } else if (!castExpr->getType()->isArithmeticType()) {
3190 if (!castType->isIntegralType() && castType->isArithmeticType())
3191 return Diag(castExpr->getLocStart(),
3192 diag::err_cast_pointer_to_non_pointer_int)
3193 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003194 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003195
3196 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003197 return false;
3198}
3199
Anders Carlssonc3516322009-10-16 02:48:28 +00003200bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3201 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003202 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003203
Anders Carlssona64db8f2007-11-27 05:51:55 +00003204 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003205 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003206 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003207 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003208 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003209 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003210 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003211 } else
3212 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003213 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003214 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003215
Anders Carlssonc3516322009-10-16 02:48:28 +00003216 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003217 return false;
3218}
3219
Anders Carlsson16a89042009-10-16 05:23:41 +00003220bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3221 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003222 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003223
3224 QualType SrcTy = CastExpr->getType();
3225
Nate Begeman9b10da62009-06-27 22:05:55 +00003226 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3227 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003228 if (SrcTy->isVectorType()) {
3229 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3230 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3231 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003232 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003233 return false;
3234 }
3235
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003236 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003237 // conversion will take place first from scalar to elt type, and then
3238 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003239 if (SrcTy->isPointerType())
3240 return Diag(R.getBegin(),
3241 diag::err_invalid_conversion_between_vector_and_scalar)
3242 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003243
3244 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3245 ImpCastExprToType(CastExpr, DestElemTy,
3246 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003247
3248 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003249 return false;
3250}
3251
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003252Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003253Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003254 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003255 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003257 assert((Ty != 0) && (Op.get() != 0) &&
3258 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003259
Nate Begeman2ef13e52009-08-10 23:49:36 +00003260 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003261 //FIXME: Preserve type source info.
3262 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Nate Begeman2ef13e52009-08-10 23:49:36 +00003264 // If the Expr being casted is a ParenListExpr, handle it specially.
3265 if (isa<ParenListExpr>(castExpr))
3266 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003267 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003268 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003269 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003270 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003271
3272 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003273 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003274 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003275
Anders Carlsson0aebc812009-09-09 21:33:21 +00003276 if (CastArg.isInvalid())
3277 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003278
Anders Carlsson0aebc812009-09-09 21:33:21 +00003279 castExpr = CastArg.takeAs<Expr>();
3280 } else {
3281 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003282 }
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003284 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003285 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003286 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003287}
3288
Nate Begeman2ef13e52009-08-10 23:49:36 +00003289/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3290/// of comma binary operators.
3291Action::OwningExprResult
3292Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3293 Expr *expr = EA.takeAs<Expr>();
3294 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3295 if (!E)
3296 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003297
Nate Begeman2ef13e52009-08-10 23:49:36 +00003298 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Nate Begeman2ef13e52009-08-10 23:49:36 +00003300 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3301 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3302 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Nate Begeman2ef13e52009-08-10 23:49:36 +00003304 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3305}
3306
3307Action::OwningExprResult
3308Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3309 SourceLocation RParenLoc, ExprArg Op,
3310 QualType Ty) {
3311 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003312
3313 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003314 // then handle it as such.
3315 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3316 if (PE->getNumExprs() == 0) {
3317 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3318 return ExprError();
3319 }
3320
3321 llvm::SmallVector<Expr *, 8> initExprs;
3322 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3323 initExprs.push_back(PE->getExpr(i));
3324
3325 // FIXME: This means that pretty-printing the final AST will produce curly
3326 // braces instead of the original commas.
3327 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003328 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003329 initExprs.size(), RParenLoc);
3330 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003331 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003332 Owned(E));
3333 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003334 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003335 // sequence of BinOp comma operators.
3336 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3337 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3338 }
3339}
3340
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003341Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003342 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003343 MultiExprArg Val,
3344 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003345 unsigned nexprs = Val.size();
3346 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003347 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3348 Expr *expr;
3349 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3350 expr = new (Context) ParenExpr(L, R, exprs[0]);
3351 else
3352 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003353 return Owned(expr);
3354}
3355
Sebastian Redl28507842009-02-26 14:39:58 +00003356/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3357/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003358/// C99 6.5.15
3359QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3360 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003361 // C++ is sufficiently different to merit its own checker.
3362 if (getLangOptions().CPlusPlus)
3363 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3364
John McCallb13c87f2009-11-05 09:23:39 +00003365 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3366
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003367 UsualUnaryConversions(Cond);
3368 UsualUnaryConversions(LHS);
3369 UsualUnaryConversions(RHS);
3370 QualType CondTy = Cond->getType();
3371 QualType LHSTy = LHS->getType();
3372 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003373
Reid Spencer5f016e22007-07-11 17:01:13 +00003374 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003375 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3376 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3377 << CondTy;
3378 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003379 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003380
Chris Lattner70d67a92008-01-06 22:42:25 +00003381 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003382 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3383 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003384
Chris Lattner70d67a92008-01-06 22:42:25 +00003385 // If both operands have arithmetic type, do the usual arithmetic conversions
3386 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003387 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3388 UsualArithmeticConversions(LHS, RHS);
3389 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003390 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003391
Chris Lattner70d67a92008-01-06 22:42:25 +00003392 // If both operands are the same structure or union type, the result is that
3393 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003394 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3395 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003396 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003397 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003398 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003399 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003400 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003402
Chris Lattner70d67a92008-01-06 22:42:25 +00003403 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003404 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003405 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3406 if (!LHSTy->isVoidType())
3407 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3408 << RHS->getSourceRange();
3409 if (!RHSTy->isVoidType())
3410 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3411 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003412 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3413 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003414 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003415 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003416 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3417 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003418 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003419 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003420 // promote the null to a pointer.
3421 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003422 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003423 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003424 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003425 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003426 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003427 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003428 }
David Chisnall0f436562009-08-17 16:35:33 +00003429 // Handle things like Class and struct objc_class*. Here we case the result
3430 // to the pseudo-builtin, because that will be implicitly cast back to the
3431 // redefinition type if an attempt is made to access its fields.
3432 if (LHSTy->isObjCClassType() &&
3433 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003434 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003435 return LHSTy;
3436 }
3437 if (RHSTy->isObjCClassType() &&
3438 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003439 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003440 return RHSTy;
3441 }
3442 // And the same for struct objc_object* / id
3443 if (LHSTy->isObjCIdType() &&
3444 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003445 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003446 return LHSTy;
3447 }
3448 if (RHSTy->isObjCIdType() &&
3449 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003450 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003451 return RHSTy;
3452 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003453 // And the same for struct objc_selector* / SEL
3454 if (Context.isObjCSelType(LHSTy) &&
3455 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3456 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3457 return LHSTy;
3458 }
3459 if (Context.isObjCSelType(RHSTy) &&
3460 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3461 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3462 return RHSTy;
3463 }
Steve Naroff7154a772009-07-01 14:36:47 +00003464 // Handle block pointer types.
3465 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3466 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3467 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3468 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003469 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3470 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003471 return destType;
3472 }
3473 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3474 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3475 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003476 }
Steve Naroff7154a772009-07-01 14:36:47 +00003477 // We have 2 block pointer types.
3478 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3479 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003480 return LHSTy;
3481 }
Steve Naroff7154a772009-07-01 14:36:47 +00003482 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003483 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3484 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003485
Steve Naroff7154a772009-07-01 14:36:47 +00003486 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3487 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003488 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3489 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3490 // In this situation, we assume void* type. No especially good
3491 // reason, but this is what gcc does, and we do have to pick
3492 // to get a consistent AST.
3493 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003494 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3495 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003496 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003497 }
Steve Naroff7154a772009-07-01 14:36:47 +00003498 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003499 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3500 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003501 return LHSTy;
3502 }
Steve Naroff7154a772009-07-01 14:36:47 +00003503 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003504 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Steve Naroff7154a772009-07-01 14:36:47 +00003506 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3507 // Two identical object pointer types are always compatible.
3508 return LHSTy;
3509 }
John McCall183700f2009-09-21 23:43:11 +00003510 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3511 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003512 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Steve Naroff7154a772009-07-01 14:36:47 +00003514 // If both operands are interfaces and either operand can be
3515 // assigned to the other, use that type as the composite
3516 // type. This allows
3517 // xxx ? (A*) a : (B*) b
3518 // where B is a subclass of A.
3519 //
3520 // Additionally, as for assignment, if either type is 'id'
3521 // allow silent coercion. Finally, if the types are
3522 // incompatible then make sure to use 'id' as the composite
3523 // type so the result is acceptable for sending messages to.
3524
3525 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3526 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003527 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003528 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003529 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003530 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003531 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003532 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003533 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003534 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003535 // GCC allows qualified id and any Objective-C type to devolve to
3536 // id. Currently localizing to here until clear this should be
3537 // part of ObjCQualifiedIdTypesAreCompatible.
3538 compositeType = Context.getObjCIdType();
3539 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003540 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003541 } else if (!(compositeType =
3542 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3543 ;
3544 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003545 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3546 << LHSTy << RHSTy
3547 << LHS->getSourceRange() << RHS->getSourceRange();
3548 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003549 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3550 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003551 return incompatTy;
3552 }
3553 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003554 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3555 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003556 return compositeType;
3557 }
Steve Naroffc715e782009-07-29 15:09:39 +00003558 // Check Objective-C object pointer types and 'void *'
3559 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003560 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003561 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003562 QualType destPointee
3563 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003564 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003565 // Add qualifiers if necessary.
3566 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3567 // Promote to void*.
3568 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003569 return destType;
3570 }
3571 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003572 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003573 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003574 QualType destPointee
3575 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003576 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003577 // Add qualifiers if necessary.
3578 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3579 // Promote to void*.
3580 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003581 return destType;
3582 }
Steve Naroff7154a772009-07-01 14:36:47 +00003583 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3584 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3585 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003586 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3587 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003588
3589 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3590 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3591 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003592 QualType destPointee
3593 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003594 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003595 // Add qualifiers if necessary.
3596 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3597 // Promote to void*.
3598 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003599 return destType;
3600 }
3601 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003602 QualType destPointee
3603 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003604 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003605 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003606 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003607 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003608 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003609 return destType;
3610 }
3611
3612 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3613 // Two identical pointer types are always compatible.
3614 return LHSTy;
3615 }
3616 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3617 rhptee.getUnqualifiedType())) {
3618 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3619 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3620 // In this situation, we assume void* type. No especially good
3621 // reason, but this is what gcc does, and we do have to pick
3622 // to get a consistent AST.
3623 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003624 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3625 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003626 return incompatTy;
3627 }
3628 // The pointer types are compatible.
3629 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3630 // differently qualified versions of compatible types, the result type is
3631 // a pointer to an appropriately qualified version of the *composite*
3632 // type.
3633 // FIXME: Need to calculate the composite type.
3634 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003635 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3636 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003637 return LHSTy;
3638 }
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Steve Naroff7154a772009-07-01 14:36:47 +00003640 // GCC compatibility: soften pointer/integer mismatch.
3641 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3642 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3643 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003644 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003645 return RHSTy;
3646 }
3647 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3648 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3649 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003650 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003651 return LHSTy;
3652 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003653
Chris Lattner70d67a92008-01-06 22:42:25 +00003654 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003655 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3656 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003657 return QualType();
3658}
3659
Steve Narofff69936d2007-09-16 03:34:24 +00003660/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003661/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003662Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3663 SourceLocation ColonLoc,
3664 ExprArg Cond, ExprArg LHS,
3665 ExprArg RHS) {
3666 Expr *CondExpr = (Expr *) Cond.get();
3667 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003668
3669 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3670 // was the condition.
3671 bool isLHSNull = LHSExpr == 0;
3672 if (isLHSNull)
3673 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003674
3675 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003676 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003677 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003678 return ExprError();
3679
3680 Cond.release();
3681 LHS.release();
3682 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003683 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003684 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003685 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003686}
3687
Reid Spencer5f016e22007-07-11 17:01:13 +00003688// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003689// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003690// routine is it effectively iqnores the qualifiers on the top level pointee.
3691// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3692// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003693Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003694Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3695 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003696
David Chisnall0f436562009-08-17 16:35:33 +00003697 if ((lhsType->isObjCClassType() &&
3698 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3699 (rhsType->isObjCClassType() &&
3700 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3701 return Compatible;
3702 }
3703
Reid Spencer5f016e22007-07-11 17:01:13 +00003704 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003705 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3706 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003707
Reid Spencer5f016e22007-07-11 17:01:13 +00003708 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003709 lhptee = Context.getCanonicalType(lhptee);
3710 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003711
Chris Lattner5cf216b2008-01-04 18:04:52 +00003712 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003713
3714 // C99 6.5.16.1p1: This following citation is common to constraints
3715 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3716 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003717 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003718 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003719 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003720
Mike Stumpeed9cac2009-02-19 03:04:26 +00003721 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3722 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003723 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003724 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003725 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003726 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003727
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003728 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003729 assert(rhptee->isFunctionType());
3730 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003731 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003732
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003733 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003734 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003735 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003736
3737 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003738 assert(lhptee->isFunctionType());
3739 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003740 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003741 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003742 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003743 lhptee = lhptee.getUnqualifiedType();
3744 rhptee = rhptee.getUnqualifiedType();
3745 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3746 // Check if the pointee types are compatible ignoring the sign.
3747 // We explicitly check for char so that we catch "char" vs
3748 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003749 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003750 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003751 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003752 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003753
3754 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003755 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003756 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003757 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003758
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003759 if (lhptee == rhptee) {
3760 // Types are compatible ignoring the sign. Qualifier incompatibility
3761 // takes priority over sign incompatibility because the sign
3762 // warning can be disabled.
3763 if (ConvTy != Compatible)
3764 return ConvTy;
3765 return IncompatiblePointerSign;
3766 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003767
3768 // If we are a multi-level pointer, it's possible that our issue is simply
3769 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3770 // the eventual target type is the same and the pointers have the same
3771 // level of indirection, this must be the issue.
3772 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3773 do {
3774 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3775 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3776
3777 lhptee = Context.getCanonicalType(lhptee);
3778 rhptee = Context.getCanonicalType(rhptee);
3779 } while (lhptee->isPointerType() && rhptee->isPointerType());
3780
Douglas Gregora4923eb2009-11-16 21:35:15 +00003781 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00003782 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003783 }
3784
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003785 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003786 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003787 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003788 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003789}
3790
Steve Naroff1c7d0672008-09-04 15:10:53 +00003791/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3792/// block pointer types are compatible or whether a block and normal pointer
3793/// are compatible. It is more restrict than comparing two function pointer
3794// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003795Sema::AssignConvertType
3796Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003797 QualType rhsType) {
3798 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003799
Steve Naroff1c7d0672008-09-04 15:10:53 +00003800 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003801 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3802 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003803
Steve Naroff1c7d0672008-09-04 15:10:53 +00003804 // make sure we operate on the canonical type
3805 lhptee = Context.getCanonicalType(lhptee);
3806 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003807
Steve Naroff1c7d0672008-09-04 15:10:53 +00003808 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003809
Steve Naroff1c7d0672008-09-04 15:10:53 +00003810 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003811 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00003812 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003813
Eli Friedman26784c12009-06-08 05:08:54 +00003814 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003815 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003816 return ConvTy;
3817}
3818
Mike Stumpeed9cac2009-02-19 03:04:26 +00003819/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3820/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003821/// pointers. Here are some objectionable examples that GCC considers warnings:
3822///
3823/// int a, *pint;
3824/// short *pshort;
3825/// struct foo *pfoo;
3826///
3827/// pint = pshort; // warning: assignment from incompatible pointer type
3828/// a = pint; // warning: assignment makes integer from pointer without a cast
3829/// pint = a; // warning: assignment makes pointer from integer without a cast
3830/// pint = pfoo; // warning: assignment from incompatible pointer type
3831///
3832/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003833/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003834///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003835Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003836Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003837 // Get canonical types. We're not formatting these types, just comparing
3838 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003839 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3840 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003841
3842 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003843 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003844
David Chisnall0f436562009-08-17 16:35:33 +00003845 if ((lhsType->isObjCClassType() &&
3846 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3847 (rhsType->isObjCClassType() &&
3848 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3849 return Compatible;
3850 }
3851
Douglas Gregor9d293df2008-10-28 00:22:11 +00003852 // If the left-hand side is a reference type, then we are in a
3853 // (rare!) case where we've allowed the use of references in C,
3854 // e.g., as a parameter type in a built-in function. In this case,
3855 // just make sure that the type referenced is compatible with the
3856 // right-hand side type. The caller is responsible for adjusting
3857 // lhsType so that the resulting expression does not have reference
3858 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003859 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003860 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003861 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003862 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003863 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003864 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3865 // to the same ExtVector type.
3866 if (lhsType->isExtVectorType()) {
3867 if (rhsType->isExtVectorType())
3868 return lhsType == rhsType ? Compatible : Incompatible;
3869 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3870 return Compatible;
3871 }
Mike Stump1eb44332009-09-09 15:08:12 +00003872
Nate Begemanbe2341d2008-07-14 18:02:46 +00003873 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003874 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003875 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003876 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003877 if (getLangOptions().LaxVectorConversions &&
3878 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003879 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003880 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003881 }
3882 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003883 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003884
Chris Lattnere8b3e962008-01-04 23:32:24 +00003885 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003886 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003887
Chris Lattner78eca282008-04-07 06:49:41 +00003888 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003889 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003890 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003891
Chris Lattner78eca282008-04-07 06:49:41 +00003892 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003893 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003894
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003895 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003896 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003897 if (lhsType->isVoidPointerType()) // an exception to the rule.
3898 return Compatible;
3899 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003900 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003901 if (rhsType->getAs<BlockPointerType>()) {
3902 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003903 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003904
3905 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003906 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003907 return Compatible;
3908 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003909 return Incompatible;
3910 }
3911
3912 if (isa<BlockPointerType>(lhsType)) {
3913 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003914 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003915
Steve Naroffb4406862008-09-29 18:10:17 +00003916 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003917 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003918 return Compatible;
3919
Steve Naroff1c7d0672008-09-04 15:10:53 +00003920 if (rhsType->isBlockPointerType())
3921 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003922
Ted Kremenek6217b802009-07-29 21:53:49 +00003923 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003924 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003925 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003926 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003927 return Incompatible;
3928 }
3929
Steve Naroff14108da2009-07-10 23:34:53 +00003930 if (isa<ObjCObjectPointerType>(lhsType)) {
3931 if (rhsType->isIntegerType())
3932 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003934 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003935 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003936 if (rhsType->isVoidPointerType()) // an exception to the rule.
3937 return Compatible;
3938 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003939 }
3940 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003941 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3942 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003943 if (Context.typesAreCompatible(lhsType, rhsType))
3944 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003945 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3946 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003947 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003948 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003949 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003950 if (RHSPT->getPointeeType()->isVoidType())
3951 return Compatible;
3952 }
3953 // Treat block pointers as objects.
3954 if (rhsType->isBlockPointerType())
3955 return Compatible;
3956 return Incompatible;
3957 }
Chris Lattner78eca282008-04-07 06:49:41 +00003958 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003959 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003960 if (lhsType == Context.BoolTy)
3961 return Compatible;
3962
3963 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003964 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003965
Mike Stumpeed9cac2009-02-19 03:04:26 +00003966 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003967 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003968
3969 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003970 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003971 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003972 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003973 }
Steve Naroff14108da2009-07-10 23:34:53 +00003974 if (isa<ObjCObjectPointerType>(rhsType)) {
3975 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3976 if (lhsType == Context.BoolTy)
3977 return Compatible;
3978
3979 if (lhsType->isIntegerType())
3980 return PointerToInt;
3981
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003982 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003983 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003984 if (lhsType->isVoidPointerType()) // an exception to the rule.
3985 return Compatible;
3986 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003987 }
3988 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003989 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003990 return Compatible;
3991 return Incompatible;
3992 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003993
Chris Lattnerfc144e22008-01-04 23:18:45 +00003994 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003995 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003996 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003997 }
3998 return Incompatible;
3999}
4000
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004001/// \brief Constructs a transparent union from an expression that is
4002/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004003static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004004 QualType UnionType, FieldDecl *Field) {
4005 // Build an initializer list that designates the appropriate member
4006 // of the transparent union.
4007 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4008 &E, 1,
4009 SourceLocation());
4010 Initializer->setType(UnionType);
4011 Initializer->setInitializedFieldInUnion(Field);
4012
4013 // Build a compound literal constructing a value of the transparent
4014 // union type from this initializer list.
4015 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4016 false);
4017}
4018
4019Sema::AssignConvertType
4020Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4021 QualType FromType = rExpr->getType();
4022
Mike Stump1eb44332009-09-09 15:08:12 +00004023 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004024 // transparent_union GCC extension.
4025 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004026 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004027 return Incompatible;
4028
4029 // The field to initialize within the transparent union.
4030 RecordDecl *UD = UT->getDecl();
4031 FieldDecl *InitField = 0;
4032 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004033 for (RecordDecl::field_iterator it = UD->field_begin(),
4034 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004035 it != itend; ++it) {
4036 if (it->getType()->isPointerType()) {
4037 // If the transparent union contains a pointer type, we allow:
4038 // 1) void pointer
4039 // 2) null pointer constant
4040 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004041 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004042 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004043 InitField = *it;
4044 break;
4045 }
Mike Stump1eb44332009-09-09 15:08:12 +00004046
Douglas Gregorce940492009-09-25 04:25:58 +00004047 if (rExpr->isNullPointerConstant(Context,
4048 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004049 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004050 InitField = *it;
4051 break;
4052 }
4053 }
4054
4055 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4056 == Compatible) {
4057 InitField = *it;
4058 break;
4059 }
4060 }
4061
4062 if (!InitField)
4063 return Incompatible;
4064
4065 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4066 return Compatible;
4067}
4068
Chris Lattner5cf216b2008-01-04 18:04:52 +00004069Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004070Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004071 if (getLangOptions().CPlusPlus) {
4072 if (!lhsType->isRecordType()) {
4073 // C++ 5.17p3: If the left operand is not of class type, the
4074 // expression is implicitly converted (C++ 4) to the
4075 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004076 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4077 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004078 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004079 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004080 }
4081
4082 // FIXME: Currently, we fall through and treat C++ classes like C
4083 // structures.
4084 }
4085
Steve Naroff529a4ad2007-11-27 17:58:44 +00004086 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4087 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004088 if ((lhsType->isPointerType() ||
4089 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004090 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004091 && rExpr->isNullPointerConstant(Context,
4092 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004093 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004094 return Compatible;
4095 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004096
Chris Lattner943140e2007-10-16 02:55:40 +00004097 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004098 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004099 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004100 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004101 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004102 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004103 if (!lhsType->isReferenceType())
4104 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004105
Chris Lattner5cf216b2008-01-04 18:04:52 +00004106 Sema::AssignConvertType result =
4107 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004108
Steve Narofff1120de2007-08-24 22:33:52 +00004109 // C99 6.5.16.1p2: The value of the right operand is converted to the
4110 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004111 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4112 // so that we can use references in built-in functions even in C.
4113 // The getNonReferenceType() call makes sure that the resulting expression
4114 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004115 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004116 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4117 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004118 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004119}
4120
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004121QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004122 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004123 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004124 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004125 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004126}
4127
Mike Stumpeed9cac2009-02-19 03:04:26 +00004128inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004129 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004130 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004131 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004132 QualType lhsType =
4133 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4134 QualType rhsType =
4135 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004136
Nate Begemanbe2341d2008-07-14 18:02:46 +00004137 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004138 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004139 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004140
Nate Begemanbe2341d2008-07-14 18:02:46 +00004141 // Handle the case of a vector & extvector type of the same size and element
4142 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004143 if (getLangOptions().LaxVectorConversions) {
4144 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004145 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4146 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004147 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004148 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004149 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004150 }
4151 }
4152 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004153
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004154 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4155 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4156 bool swapped = false;
4157 if (rhsType->isExtVectorType()) {
4158 swapped = true;
4159 std::swap(rex, lex);
4160 std::swap(rhsType, lhsType);
4161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Nate Begemandde25982009-06-28 19:12:57 +00004163 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004164 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004165 QualType EltTy = LV->getElementType();
4166 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4167 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004168 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004169 if (swapped) std::swap(rex, lex);
4170 return lhsType;
4171 }
4172 }
4173 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4174 rhsType->isRealFloatingType()) {
4175 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004176 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004177 if (swapped) std::swap(rex, lex);
4178 return lhsType;
4179 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004180 }
4181 }
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Nate Begemandde25982009-06-28 19:12:57 +00004183 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004184 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004185 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004186 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004187 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004188}
4189
Reid Spencer5f016e22007-07-11 17:01:13 +00004190inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004191 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004192 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004193 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004194
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004195 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004196
Steve Naroffa4332e22007-07-17 00:58:39 +00004197 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004198 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004199 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004200}
4201
4202inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004203 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004204 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4205 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4206 return CheckVectorOperands(Loc, lex, rex);
4207 return InvalidOperands(Loc, lex, rex);
4208 }
Steve Naroff90045e82007-07-13 23:32:42 +00004209
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004210 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004211
Steve Naroffa4332e22007-07-17 00:58:39 +00004212 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004213 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004214 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004215}
4216
4217inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004218 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004219 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4220 QualType compType = CheckVectorOperands(Loc, lex, rex);
4221 if (CompLHSTy) *CompLHSTy = compType;
4222 return compType;
4223 }
Steve Naroff49b45262007-07-13 16:58:59 +00004224
Eli Friedmanab3a8522009-03-28 01:22:36 +00004225 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004226
Reid Spencer5f016e22007-07-11 17:01:13 +00004227 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004228 if (lex->getType()->isArithmeticType() &&
4229 rex->getType()->isArithmeticType()) {
4230 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004231 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004232 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004233
Eli Friedmand72d16e2008-05-18 18:08:51 +00004234 // Put any potential pointer into PExp
4235 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004236 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004237 std::swap(PExp, IExp);
4238
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004239 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Eli Friedmand72d16e2008-05-18 18:08:51 +00004241 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004242 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004243
Chris Lattnerb5f15622009-04-24 23:50:08 +00004244 // Check for arithmetic on pointers to incomplete types.
4245 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004246 if (getLangOptions().CPlusPlus) {
4247 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004248 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004249 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004250 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004251
4252 // GNU extension: arithmetic on pointer to void
4253 Diag(Loc, diag::ext_gnu_void_ptr)
4254 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004255 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004256 if (getLangOptions().CPlusPlus) {
4257 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4258 << lex->getType() << lex->getSourceRange();
4259 return QualType();
4260 }
4261
4262 // GNU extension: arithmetic on pointer to function
4263 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4264 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004265 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004266 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004267 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004268 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004269 PExp->getType()->isObjCObjectPointerType()) &&
4270 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004271 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4272 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004273 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004274 return QualType();
4275 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004276 // Diagnose bad cases where we step over interface counts.
4277 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4278 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4279 << PointeeTy << PExp->getSourceRange();
4280 return QualType();
4281 }
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Eli Friedmanab3a8522009-03-28 01:22:36 +00004283 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004284 QualType LHSTy = Context.isPromotableBitField(lex);
4285 if (LHSTy.isNull()) {
4286 LHSTy = lex->getType();
4287 if (LHSTy->isPromotableIntegerType())
4288 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004289 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004290 *CompLHSTy = LHSTy;
4291 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004292 return PExp->getType();
4293 }
4294 }
4295
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004296 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004297}
4298
Chris Lattnereca7be62008-04-07 05:30:13 +00004299// C99 6.5.6
4300QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004301 SourceLocation Loc, QualType* CompLHSTy) {
4302 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4303 QualType compType = CheckVectorOperands(Loc, lex, rex);
4304 if (CompLHSTy) *CompLHSTy = compType;
4305 return compType;
4306 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004307
Eli Friedmanab3a8522009-03-28 01:22:36 +00004308 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004309
Chris Lattner6e4ab612007-12-09 21:53:25 +00004310 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004311
Chris Lattner6e4ab612007-12-09 21:53:25 +00004312 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004313 if (lex->getType()->isArithmeticType()
4314 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004315 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004316 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004317 }
Mike Stump1eb44332009-09-09 15:08:12 +00004318
Chris Lattner6e4ab612007-12-09 21:53:25 +00004319 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004320 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004321 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004322
Douglas Gregore7450f52009-03-24 19:52:54 +00004323 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004324
Douglas Gregore7450f52009-03-24 19:52:54 +00004325 bool ComplainAboutVoid = false;
4326 Expr *ComplainAboutFunc = 0;
4327 if (lpointee->isVoidType()) {
4328 if (getLangOptions().CPlusPlus) {
4329 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4330 << lex->getSourceRange() << rex->getSourceRange();
4331 return QualType();
4332 }
4333
4334 // GNU C extension: arithmetic on pointer to void
4335 ComplainAboutVoid = true;
4336 } else if (lpointee->isFunctionType()) {
4337 if (getLangOptions().CPlusPlus) {
4338 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004339 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004340 return QualType();
4341 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004342
4343 // GNU C extension: arithmetic on pointer to function
4344 ComplainAboutFunc = lex;
4345 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004346 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004347 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004348 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004349 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004350 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004351
Chris Lattnerb5f15622009-04-24 23:50:08 +00004352 // Diagnose bad cases where we step over interface counts.
4353 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4354 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4355 << lpointee << lex->getSourceRange();
4356 return QualType();
4357 }
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Chris Lattner6e4ab612007-12-09 21:53:25 +00004359 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004360 if (rex->getType()->isIntegerType()) {
4361 if (ComplainAboutVoid)
4362 Diag(Loc, diag::ext_gnu_void_ptr)
4363 << lex->getSourceRange() << rex->getSourceRange();
4364 if (ComplainAboutFunc)
4365 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004366 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004367 << ComplainAboutFunc->getSourceRange();
4368
Eli Friedmanab3a8522009-03-28 01:22:36 +00004369 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004370 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004371 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004372
Chris Lattner6e4ab612007-12-09 21:53:25 +00004373 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004374 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004375 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004376
Douglas Gregore7450f52009-03-24 19:52:54 +00004377 // RHS must be a completely-type object type.
4378 // Handle the GNU void* extension.
4379 if (rpointee->isVoidType()) {
4380 if (getLangOptions().CPlusPlus) {
4381 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4382 << lex->getSourceRange() << rex->getSourceRange();
4383 return QualType();
4384 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004385
Douglas Gregore7450f52009-03-24 19:52:54 +00004386 ComplainAboutVoid = true;
4387 } else if (rpointee->isFunctionType()) {
4388 if (getLangOptions().CPlusPlus) {
4389 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004390 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004391 return QualType();
4392 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004393
4394 // GNU extension: arithmetic on pointer to function
4395 if (!ComplainAboutFunc)
4396 ComplainAboutFunc = rex;
4397 } else if (!rpointee->isDependentType() &&
4398 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004399 PDiag(diag::err_typecheck_sub_ptr_object)
4400 << rex->getSourceRange()
4401 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004402 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004403
Eli Friedman88d936b2009-05-16 13:54:38 +00004404 if (getLangOptions().CPlusPlus) {
4405 // Pointee types must be the same: C++ [expr.add]
4406 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4407 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4408 << lex->getType() << rex->getType()
4409 << lex->getSourceRange() << rex->getSourceRange();
4410 return QualType();
4411 }
4412 } else {
4413 // Pointee types must be compatible C99 6.5.6p3
4414 if (!Context.typesAreCompatible(
4415 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4416 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4417 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4418 << lex->getType() << rex->getType()
4419 << lex->getSourceRange() << rex->getSourceRange();
4420 return QualType();
4421 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004422 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004423
Douglas Gregore7450f52009-03-24 19:52:54 +00004424 if (ComplainAboutVoid)
4425 Diag(Loc, diag::ext_gnu_void_ptr)
4426 << lex->getSourceRange() << rex->getSourceRange();
4427 if (ComplainAboutFunc)
4428 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004429 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004430 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004431
4432 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004433 return Context.getPointerDiffType();
4434 }
4435 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004436
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004437 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004438}
4439
Chris Lattnereca7be62008-04-07 05:30:13 +00004440// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004441QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004442 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004443 // C99 6.5.7p2: Each of the operands shall have integer type.
4444 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004445 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004446
Nate Begeman2207d792009-10-25 02:26:48 +00004447 // Vector shifts promote their scalar inputs to vector type.
4448 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4449 return CheckVectorOperands(Loc, lex, rex);
4450
Chris Lattnerca5eede2007-12-12 05:47:28 +00004451 // Shifts don't perform usual arithmetic conversions, they just do integer
4452 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004453 QualType LHSTy = Context.isPromotableBitField(lex);
4454 if (LHSTy.isNull()) {
4455 LHSTy = lex->getType();
4456 if (LHSTy->isPromotableIntegerType())
4457 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004458 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004459 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004460 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004461
Chris Lattnerca5eede2007-12-12 05:47:28 +00004462 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004463
Ryan Flynnd0439682009-08-07 16:20:20 +00004464 // Sanity-check shift operands
4465 llvm::APSInt Right;
4466 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004467 if (!rex->isValueDependent() &&
4468 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004469 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004470 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4471 else {
4472 llvm::APInt LeftBits(Right.getBitWidth(),
4473 Context.getTypeSize(lex->getType()));
4474 if (Right.uge(LeftBits))
4475 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4476 }
4477 }
4478
Chris Lattnerca5eede2007-12-12 05:47:28 +00004479 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004480 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004481}
4482
John McCall5dbad3d2009-11-06 08:49:08 +00004483/// \brief Implements -Wsign-compare.
4484///
4485/// \param lex the left-hand expression
4486/// \param rex the right-hand expression
4487/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004488/// \param Equality whether this is an "equality-like" join, which
4489/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004490void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004491 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004492 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004493 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004494 return;
4495
John McCall45aa4552009-11-05 00:40:04 +00004496 QualType lt = lex->getType(), rt = rex->getType();
4497
4498 // Only warn if both operands are integral.
4499 if (!lt->isIntegerType() || !rt->isIntegerType())
4500 return;
4501
Sebastian Redl732429c2009-11-05 21:09:23 +00004502 // If either expression is value-dependent, don't warn. We'll get another
4503 // chance at instantiation time.
4504 if (lex->isValueDependent() || rex->isValueDependent())
4505 return;
4506
John McCall45aa4552009-11-05 00:40:04 +00004507 // The rule is that the signed operand becomes unsigned, so isolate the
4508 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004509 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004510 if (lt->isSignedIntegerType()) {
4511 if (rt->isSignedIntegerType()) return;
4512 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004513 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004514 } else {
4515 if (!rt->isSignedIntegerType()) return;
4516 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004517 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004518 }
4519
John McCall5dbad3d2009-11-06 08:49:08 +00004520 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004521 // then (1) the result type will be signed and (2) the unsigned
4522 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004523 // of the comparison will be exact.
4524 if (Context.getIntWidth(signedOperand->getType()) >
4525 Context.getIntWidth(unsignedOperand->getType()))
4526 return;
4527
John McCall45aa4552009-11-05 00:40:04 +00004528 // If the value is a non-negative integer constant, then the
4529 // signed->unsigned conversion won't change it.
4530 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004531 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004532 assert(value.isSigned() && "result of signed expression not signed");
4533
4534 if (value.isNonNegative())
4535 return;
4536 }
4537
John McCall5dbad3d2009-11-06 08:49:08 +00004538 if (Equality) {
4539 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004540 // constant which cannot collide with a overflowed signed operand,
4541 // then reinterpreting the signed operand as unsigned will not
4542 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004543 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4544 assert(!value.isSigned() && "result of unsigned expression is signed");
4545
4546 // 2's complement: test the top bit.
4547 if (value.isNonNegative())
4548 return;
4549 }
4550 }
4551
John McCallb13c87f2009-11-05 09:23:39 +00004552 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004553 << lex->getType() << rex->getType()
4554 << lex->getSourceRange() << rex->getSourceRange();
4555}
4556
Douglas Gregor0c6db942009-05-04 06:07:12 +00004557// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004558QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004559 unsigned OpaqueOpc, bool isRelational) {
4560 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4561
Nate Begemanbe2341d2008-07-14 18:02:46 +00004562 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004563 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004564
John McCall5dbad3d2009-11-06 08:49:08 +00004565 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4566 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00004567
Chris Lattnera5937dd2007-08-26 01:18:55 +00004568 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004569 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4570 UsualArithmeticConversions(lex, rex);
4571 else {
4572 UsualUnaryConversions(lex);
4573 UsualUnaryConversions(rex);
4574 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004575 QualType lType = lex->getType();
4576 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004577
Mike Stumpaf199f32009-05-07 18:43:07 +00004578 if (!lType->isFloatingType()
4579 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004580 // For non-floating point types, check for self-comparisons of the form
4581 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4582 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004583 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004584 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004585 Expr *LHSStripped = lex->IgnoreParens();
4586 Expr *RHSStripped = rex->IgnoreParens();
4587 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4588 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004589 if (DRL->getDecl() == DRR->getDecl() &&
4590 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004591 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Chris Lattner55660a72009-03-08 19:39:53 +00004593 if (isa<CastExpr>(LHSStripped))
4594 LHSStripped = LHSStripped->IgnoreParenCasts();
4595 if (isa<CastExpr>(RHSStripped))
4596 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004597
Chris Lattner55660a72009-03-08 19:39:53 +00004598 // Warn about comparisons against a string constant (unless the other
4599 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004600 Expr *literalString = 0;
4601 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004602 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004603 !RHSStripped->isNullPointerConstant(Context,
4604 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004605 literalString = lex;
4606 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004607 } else if ((isa<StringLiteral>(RHSStripped) ||
4608 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004609 !LHSStripped->isNullPointerConstant(Context,
4610 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004611 literalString = rex;
4612 literalStringStripped = RHSStripped;
4613 }
4614
4615 if (literalString) {
4616 std::string resultComparison;
4617 switch (Opc) {
4618 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4619 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4620 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4621 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4622 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4623 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4624 default: assert(false && "Invalid comparison operator");
4625 }
4626 Diag(Loc, diag::warn_stringcompare)
4627 << isa<ObjCEncodeExpr>(literalStringStripped)
4628 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004629 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4630 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4631 "strcmp(")
4632 << CodeModificationHint::CreateInsertion(
4633 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004634 resultComparison);
4635 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004636 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637
Douglas Gregor447b69e2008-11-19 03:25:36 +00004638 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004639 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004640
Chris Lattnera5937dd2007-08-26 01:18:55 +00004641 if (isRelational) {
4642 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004643 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004644 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004645 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004646 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004647 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004648 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004649 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004650
Chris Lattnera5937dd2007-08-26 01:18:55 +00004651 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004652 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004653 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004654
Douglas Gregorce940492009-09-25 04:25:58 +00004655 bool LHSIsNull = lex->isNullPointerConstant(Context,
4656 Expr::NPC_ValueDependentIsNull);
4657 bool RHSIsNull = rex->isNullPointerConstant(Context,
4658 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004659
Chris Lattnera5937dd2007-08-26 01:18:55 +00004660 // All of the following pointer related warnings are GCC extensions, except
4661 // when handling null pointer constants. One day, we can consider making them
4662 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004663 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004664 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004665 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004666 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004667 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004668
Douglas Gregor0c6db942009-05-04 06:07:12 +00004669 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004670 if (LCanPointeeTy == RCanPointeeTy)
4671 return ResultTy;
4672
Douglas Gregor0c6db942009-05-04 06:07:12 +00004673 // C++ [expr.rel]p2:
4674 // [...] Pointer conversions (4.10) and qualification
4675 // conversions (4.4) are performed on pointer operands (or on
4676 // a pointer operand and a null pointer constant) to bring
4677 // them to their composite pointer type. [...]
4678 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004679 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004680 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004681 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004682 if (T.isNull()) {
4683 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4684 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4685 return QualType();
4686 }
4687
Eli Friedman73c39ab2009-10-20 08:27:19 +00004688 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4689 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004690 return ResultTy;
4691 }
Eli Friedman3075e762009-08-23 00:27:47 +00004692 // C99 6.5.9p2 and C99 6.5.8p2
4693 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4694 RCanPointeeTy.getUnqualifiedType())) {
4695 // Valid unless a relational comparison of function pointers
4696 if (isRelational && LCanPointeeTy->isFunctionType()) {
4697 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4698 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4699 }
4700 } else if (!isRelational &&
4701 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4702 // Valid unless comparison between non-null pointer and function pointer
4703 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4704 && !LHSIsNull && !RHSIsNull) {
4705 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4706 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4707 }
4708 } else {
4709 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004710 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004711 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004712 }
Eli Friedman3075e762009-08-23 00:27:47 +00004713 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004714 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004715 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004716 }
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004718 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004719 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004720 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004721 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004722 (lType->isPointerType() ||
4723 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004724 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004725 return ResultTy;
4726 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004727 if (LHSIsNull &&
4728 (rType->isPointerType() ||
4729 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004730 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004731 return ResultTy;
4732 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004733
4734 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004735 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004736 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4737 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004738 // In addition, pointers to members can be compared, or a pointer to
4739 // member and a null pointer constant. Pointer to member conversions
4740 // (4.11) and qualification conversions (4.4) are performed to bring
4741 // them to a common type. If one operand is a null pointer constant,
4742 // the common type is the type of the other operand. Otherwise, the
4743 // common type is a pointer to member type similar (4.4) to the type
4744 // of one of the operands, with a cv-qualification signature (4.4)
4745 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004746 // types.
4747 QualType T = FindCompositePointerType(lex, rex);
4748 if (T.isNull()) {
4749 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4750 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4751 return QualType();
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Eli Friedman73c39ab2009-10-20 08:27:19 +00004754 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4755 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004756 return ResultTy;
4757 }
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Douglas Gregor20b3e992009-08-24 17:42:35 +00004759 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004760 if (lType->isNullPtrType() && rType->isNullPtrType())
4761 return ResultTy;
4762 }
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Steve Naroff1c7d0672008-09-04 15:10:53 +00004764 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004765 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004766 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4767 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004768
Steve Naroff1c7d0672008-09-04 15:10:53 +00004769 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004770 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004771 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004772 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004773 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004774 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004775 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004776 }
Steve Naroff59f53942008-09-28 01:11:11 +00004777 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004778 if (!isRelational
4779 && ((lType->isBlockPointerType() && rType->isPointerType())
4780 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004781 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004782 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004783 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004784 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004785 ->getPointeeType()->isVoidType())))
4786 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4787 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004788 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004789 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004790 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004791 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004792
Steve Naroff14108da2009-07-10 23:34:53 +00004793 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004794 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004795 const PointerType *LPT = lType->getAs<PointerType>();
4796 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004797 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004798 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004799 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004800 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004801
Steve Naroffa8069f12008-11-17 19:49:16 +00004802 if (!LPtrToVoid && !RPtrToVoid &&
4803 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004804 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004805 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004806 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004807 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004808 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004809 }
Steve Naroff14108da2009-07-10 23:34:53 +00004810 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004811 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004812 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4813 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004814 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004815 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004816 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004817 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004818 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004819 unsigned DiagID = 0;
4820 if (RHSIsNull) {
4821 if (isRelational)
4822 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4823 } else if (isRelational)
4824 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4825 else
4826 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004827
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004828 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004829 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004830 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004831 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004832 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004833 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004834 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004835 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004836 unsigned DiagID = 0;
4837 if (LHSIsNull) {
4838 if (isRelational)
4839 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4840 } else if (isRelational)
4841 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4842 else
4843 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004844
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004845 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004846 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004847 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004848 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004849 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004850 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004851 }
Steve Naroff39218df2008-09-04 16:56:14 +00004852 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004853 if (!isRelational && RHSIsNull
4854 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004855 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004856 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004857 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004858 if (!isRelational && LHSIsNull
4859 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004860 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004861 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004862 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004863 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004864}
4865
Nate Begemanbe2341d2008-07-14 18:02:46 +00004866/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004867/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004868/// like a scalar comparison, a vector comparison produces a vector of integer
4869/// types.
4870QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004871 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004872 bool isRelational) {
4873 // Check to make sure we're operating on vectors of the same type and width,
4874 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004875 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004876 if (vType.isNull())
4877 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004878
Nate Begemanbe2341d2008-07-14 18:02:46 +00004879 QualType lType = lex->getType();
4880 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004881
Nate Begemanbe2341d2008-07-14 18:02:46 +00004882 // For non-floating point types, check for self-comparisons of the form
4883 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4884 // often indicate logic errors in the program.
4885 if (!lType->isFloatingType()) {
4886 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4887 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4888 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004889 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004890 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004891
Nate Begemanbe2341d2008-07-14 18:02:46 +00004892 // Check for comparisons of floating point operands using != and ==.
4893 if (!isRelational && lType->isFloatingType()) {
4894 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004895 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004896 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004897
Nate Begemanbe2341d2008-07-14 18:02:46 +00004898 // Return the type for the comparison, which is the same as vector type for
4899 // integer vectors, or an integer type of identical size and number of
4900 // elements for floating point vectors.
4901 if (lType->isIntegerType())
4902 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004903
John McCall183700f2009-09-21 23:43:11 +00004904 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004905 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004906 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004907 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004908 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004909 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4910
Mike Stumpeed9cac2009-02-19 03:04:26 +00004911 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004912 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004913 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4914}
4915
Reid Spencer5f016e22007-07-11 17:01:13 +00004916inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004917 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004918 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004919 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004920
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004921 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004922
Steve Naroffa4332e22007-07-17 00:58:39 +00004923 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004924 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004925 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004926}
4927
4928inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004929 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004930 if (!Context.getLangOptions().CPlusPlus) {
4931 UsualUnaryConversions(lex);
4932 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004933
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004934 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4935 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00004936
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004937 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00004938 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004939
4940 // C++ [expr.log.and]p1
4941 // C++ [expr.log.or]p1
4942 // The operands are both implicitly converted to type bool (clause 4).
4943 StandardConversionSequence LHS;
4944 if (!IsStandardConversion(lex, Context.BoolTy,
4945 /*InOverloadResolution=*/false, LHS))
4946 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00004947
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004948 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
4949 "passing", /*IgnoreBaseAccess=*/false))
4950 return InvalidOperands(Loc, lex, rex);
4951
4952 StandardConversionSequence RHS;
4953 if (!IsStandardConversion(rex, Context.BoolTy,
4954 /*InOverloadResolution=*/false, RHS))
4955 return InvalidOperands(Loc, lex, rex);
4956
4957 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
4958 "passing", /*IgnoreBaseAccess=*/false))
4959 return InvalidOperands(Loc, lex, rex);
4960
4961 // C++ [expr.log.and]p2
4962 // C++ [expr.log.or]p2
4963 // The result is a bool.
4964 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004965}
4966
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004967/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4968/// is a read-only property; return true if so. A readonly property expression
4969/// depends on various declarations and thus must be treated specially.
4970///
Mike Stump1eb44332009-09-09 15:08:12 +00004971static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004972 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4973 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4974 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4975 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004976 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004977 BaseType->getAsObjCInterfacePointerType())
4978 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4979 if (S.isPropertyReadonly(PDecl, IFace))
4980 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004981 }
4982 }
4983 return false;
4984}
4985
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004986/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4987/// emit an error and return true. If so, return false.
4988static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004989 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004990 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004991 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004992 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4993 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004994 if (IsLV == Expr::MLV_Valid)
4995 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004996
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004997 unsigned Diag = 0;
4998 bool NeedType = false;
4999 switch (IsLV) { // C99 6.5.16p2
5000 default: assert(0 && "Unknown result from isModifiableLvalue!");
5001 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005002 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005003 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5004 NeedType = true;
5005 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005006 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005007 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5008 NeedType = true;
5009 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005010 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005011 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5012 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005013 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005014 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5015 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005016 case Expr::MLV_IncompleteType:
5017 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005018 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005019 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5020 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005021 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005022 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5023 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005024 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005025 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5026 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005027 case Expr::MLV_ReadonlyProperty:
5028 Diag = diag::error_readonly_property_assignment;
5029 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005030 case Expr::MLV_NoSetterProperty:
5031 Diag = diag::error_nosetter_property_assignment;
5032 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005033 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005034
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005035 SourceRange Assign;
5036 if (Loc != OrigLoc)
5037 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005038 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005039 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005040 else
Mike Stump1eb44332009-09-09 15:08:12 +00005041 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005042 return true;
5043}
5044
5045
5046
5047// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005048QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5049 SourceLocation Loc,
5050 QualType CompoundType) {
5051 // Verify that LHS is a modifiable lvalue, and emit error if not.
5052 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005053 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005054
5055 QualType LHSType = LHS->getType();
5056 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005057
Chris Lattner5cf216b2008-01-04 18:04:52 +00005058 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005059 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005060 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005061 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005062 // Special case of NSObject attributes on c-style pointer types.
5063 if (ConvTy == IncompatiblePointer &&
5064 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005065 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005066 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005067 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005068 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005069
Chris Lattner2c156472008-08-21 18:04:13 +00005070 // If the RHS is a unary plus or minus, check to see if they = and + are
5071 // right next to each other. If so, the user may have typo'd "x =+ 4"
5072 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005073 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005074 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5075 RHSCheck = ICE->getSubExpr();
5076 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5077 if ((UO->getOpcode() == UnaryOperator::Plus ||
5078 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005079 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005080 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005081 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5082 // And there is a space or other character before the subexpr of the
5083 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005084 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5085 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005086 Diag(Loc, diag::warn_not_compound_assign)
5087 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5088 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005089 }
Chris Lattner2c156472008-08-21 18:04:13 +00005090 }
5091 } else {
5092 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005093 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005094 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005095
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005096 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5097 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005098 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005099
Reid Spencer5f016e22007-07-11 17:01:13 +00005100 // C99 6.5.16p3: The type of an assignment expression is the type of the
5101 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005102 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005103 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5104 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005105 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005106 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005107 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005108}
5109
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005110// C99 6.5.17
5111QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005112 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005113 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005114
5115 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5116 // incomplete in C++).
5117
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005118 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005119}
5120
Steve Naroff49b45262007-07-13 16:58:59 +00005121/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5122/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005123QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5124 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005125 if (Op->isTypeDependent())
5126 return Context.DependentTy;
5127
Chris Lattner3528d352008-11-21 07:05:48 +00005128 QualType ResType = Op->getType();
5129 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005130
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005131 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5132 // Decrement of bool is not allowed.
5133 if (!isInc) {
5134 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5135 return QualType();
5136 }
5137 // Increment of bool sets it to true, but is deprecated.
5138 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5139 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005140 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005141 } else if (ResType->isAnyPointerType()) {
5142 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005143
Chris Lattner3528d352008-11-21 07:05:48 +00005144 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005145 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005146 if (getLangOptions().CPlusPlus) {
5147 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5148 << Op->getSourceRange();
5149 return QualType();
5150 }
5151
5152 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005153 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005154 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005155 if (getLangOptions().CPlusPlus) {
5156 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5157 << Op->getType() << Op->getSourceRange();
5158 return QualType();
5159 }
5160
5161 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005162 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005163 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005164 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005165 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005166 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005167 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005168 // Diagnose bad cases where we step over interface counts.
5169 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5170 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5171 << PointeeTy << Op->getSourceRange();
5172 return QualType();
5173 }
Chris Lattner3528d352008-11-21 07:05:48 +00005174 } else if (ResType->isComplexType()) {
5175 // C99 does not support ++/-- on complex types, we allow as an extension.
5176 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005177 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005178 } else {
5179 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005180 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005181 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005182 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005183 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005184 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005185 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005186 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005187 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005188}
5189
Anders Carlsson369dee42008-02-01 07:15:58 +00005190/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005191/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005192/// where the declaration is needed for type checking. We only need to
5193/// handle cases when the expression references a function designator
5194/// or is an lvalue. Here are some examples:
5195/// - &(x) => x
5196/// - &*****f => f for f a function designator.
5197/// - &s.xx => s
5198/// - &s.zz[1].yy -> s, if zz is an array
5199/// - *(x + 1) -> x, if x is an array
5200/// - &"123"[2] -> 0
5201/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005202static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005203 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005204 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005205 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005206 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005207 // If this is an arrow operator, the address is an offset from
5208 // the base's value, so the object the base refers to is
5209 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005210 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005211 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005212 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005213 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005214 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005215 // FIXME: This code shouldn't be necessary! We should catch the implicit
5216 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005217 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5218 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5219 if (ICE->getSubExpr()->getType()->isArrayType())
5220 return getPrimaryDecl(ICE->getSubExpr());
5221 }
5222 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005223 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005224 case Stmt::UnaryOperatorClass: {
5225 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005226
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005227 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005228 case UnaryOperator::Real:
5229 case UnaryOperator::Imag:
5230 case UnaryOperator::Extension:
5231 return getPrimaryDecl(UO->getSubExpr());
5232 default:
5233 return 0;
5234 }
5235 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005236 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005237 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005238 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005239 // If the result of an implicit cast is an l-value, we care about
5240 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005241 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005242 default:
5243 return 0;
5244 }
5245}
5246
5247/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005248/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005249/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005250/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005251/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005252/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005253/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005254QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005255 // Make sure to ignore parentheses in subsequent checks
5256 op = op->IgnoreParens();
5257
Douglas Gregor9103bb22008-12-17 22:52:20 +00005258 if (op->isTypeDependent())
5259 return Context.DependentTy;
5260
Steve Naroff08f19672008-01-13 17:10:08 +00005261 if (getLangOptions().C99) {
5262 // Implement C99-only parts of addressof rules.
5263 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5264 if (uOp->getOpcode() == UnaryOperator::Deref)
5265 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5266 // (assuming the deref expression is valid).
5267 return uOp->getSubExpr()->getType();
5268 }
5269 // Technically, there should be a check for array subscript
5270 // expressions here, but the result of one is always an lvalue anyway.
5271 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005272 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005273 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005274
Eli Friedman441cf102009-05-16 23:27:50 +00005275 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5276 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005277 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005278 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005279 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005280 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5281 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005282 return QualType();
5283 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005284 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005285 // The operand cannot be a bit-field
5286 Diag(OpLoc, diag::err_typecheck_address_of)
5287 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005288 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005289 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5290 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005291 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005292 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005293 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005294 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005295 } else if (isa<ObjCPropertyRefExpr>(op)) {
5296 // cannot take address of a property expression.
5297 Diag(OpLoc, diag::err_typecheck_address_of)
5298 << "property expression" << op->getSourceRange();
5299 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005300 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5301 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005302 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5303 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005304 } else if (isa<UnresolvedLookupExpr>(op)) {
5305 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005306 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005307 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005308 // with the register storage-class specifier.
5309 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5310 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005311 Diag(OpLoc, diag::err_typecheck_address_of)
5312 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005313 return QualType();
5314 }
John McCallba135432009-11-21 08:51:07 +00005315 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005316 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005317 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005318 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005319 // Could be a pointer to member, though, if there is an explicit
5320 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005321 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005322 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005323 if (Ctx && Ctx->isRecord()) {
5324 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005325 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005326 diag::err_cannot_form_pointer_to_member_of_reference_type)
5327 << FD->getDeclName() << FD->getType();
5328 return QualType();
5329 }
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Sebastian Redlebc07d52009-02-03 20:19:35 +00005331 return Context.getMemberPointerType(op->getType(),
5332 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005333 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005334 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005335 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005336 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005337 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005338 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5339 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005340 return Context.getMemberPointerType(op->getType(),
5341 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5342 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005343 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005344 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005345
Eli Friedman441cf102009-05-16 23:27:50 +00005346 if (lval == Expr::LV_IncompleteVoidType) {
5347 // Taking the address of a void variable is technically illegal, but we
5348 // allow it in cases which are otherwise valid.
5349 // Example: "extern void x; void* y = &x;".
5350 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5351 }
5352
Reid Spencer5f016e22007-07-11 17:01:13 +00005353 // If the operand has type "type", the result has type "pointer to type".
5354 return Context.getPointerType(op->getType());
5355}
5356
Chris Lattner22caddc2008-11-23 09:13:29 +00005357QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005358 if (Op->isTypeDependent())
5359 return Context.DependentTy;
5360
Chris Lattner22caddc2008-11-23 09:13:29 +00005361 UsualUnaryConversions(Op);
5362 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005363
Chris Lattner22caddc2008-11-23 09:13:29 +00005364 // Note that per both C89 and C99, this is always legal, even if ptype is an
5365 // incomplete type or void. It would be possible to warn about dereferencing
5366 // a void pointer, but it's completely well-defined, and such a warning is
5367 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005368 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005369 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005370
John McCall183700f2009-09-21 23:43:11 +00005371 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005372 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005373
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005374 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005375 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005376 return QualType();
5377}
5378
5379static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5380 tok::TokenKind Kind) {
5381 BinaryOperator::Opcode Opc;
5382 switch (Kind) {
5383 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005384 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5385 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005386 case tok::star: Opc = BinaryOperator::Mul; break;
5387 case tok::slash: Opc = BinaryOperator::Div; break;
5388 case tok::percent: Opc = BinaryOperator::Rem; break;
5389 case tok::plus: Opc = BinaryOperator::Add; break;
5390 case tok::minus: Opc = BinaryOperator::Sub; break;
5391 case tok::lessless: Opc = BinaryOperator::Shl; break;
5392 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5393 case tok::lessequal: Opc = BinaryOperator::LE; break;
5394 case tok::less: Opc = BinaryOperator::LT; break;
5395 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5396 case tok::greater: Opc = BinaryOperator::GT; break;
5397 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5398 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5399 case tok::amp: Opc = BinaryOperator::And; break;
5400 case tok::caret: Opc = BinaryOperator::Xor; break;
5401 case tok::pipe: Opc = BinaryOperator::Or; break;
5402 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5403 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5404 case tok::equal: Opc = BinaryOperator::Assign; break;
5405 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5406 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5407 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5408 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5409 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5410 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5411 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5412 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5413 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5414 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5415 case tok::comma: Opc = BinaryOperator::Comma; break;
5416 }
5417 return Opc;
5418}
5419
5420static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5421 tok::TokenKind Kind) {
5422 UnaryOperator::Opcode Opc;
5423 switch (Kind) {
5424 default: assert(0 && "Unknown unary op!");
5425 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5426 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5427 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5428 case tok::star: Opc = UnaryOperator::Deref; break;
5429 case tok::plus: Opc = UnaryOperator::Plus; break;
5430 case tok::minus: Opc = UnaryOperator::Minus; break;
5431 case tok::tilde: Opc = UnaryOperator::Not; break;
5432 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005433 case tok::kw___real: Opc = UnaryOperator::Real; break;
5434 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5435 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5436 }
5437 return Opc;
5438}
5439
Douglas Gregoreaebc752008-11-06 23:29:22 +00005440/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5441/// operator @p Opc at location @c TokLoc. This routine only supports
5442/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005443Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5444 unsigned Op,
5445 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005446 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005447 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005448 // The following two variables are used for compound assignment operators
5449 QualType CompLHSTy; // Type of LHS after promotions for computation
5450 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005451
5452 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005453 case BinaryOperator::Assign:
5454 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5455 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005456 case BinaryOperator::PtrMemD:
5457 case BinaryOperator::PtrMemI:
5458 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5459 Opc == BinaryOperator::PtrMemI);
5460 break;
5461 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005462 case BinaryOperator::Div:
5463 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5464 break;
5465 case BinaryOperator::Rem:
5466 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5467 break;
5468 case BinaryOperator::Add:
5469 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5470 break;
5471 case BinaryOperator::Sub:
5472 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5473 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005474 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005475 case BinaryOperator::Shr:
5476 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5477 break;
5478 case BinaryOperator::LE:
5479 case BinaryOperator::LT:
5480 case BinaryOperator::GE:
5481 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005482 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005483 break;
5484 case BinaryOperator::EQ:
5485 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005486 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005487 break;
5488 case BinaryOperator::And:
5489 case BinaryOperator::Xor:
5490 case BinaryOperator::Or:
5491 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5492 break;
5493 case BinaryOperator::LAnd:
5494 case BinaryOperator::LOr:
5495 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5496 break;
5497 case BinaryOperator::MulAssign:
5498 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005499 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5500 CompLHSTy = CompResultTy;
5501 if (!CompResultTy.isNull())
5502 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005503 break;
5504 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005505 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5506 CompLHSTy = CompResultTy;
5507 if (!CompResultTy.isNull())
5508 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005509 break;
5510 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005511 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5512 if (!CompResultTy.isNull())
5513 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005514 break;
5515 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005516 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5517 if (!CompResultTy.isNull())
5518 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005519 break;
5520 case BinaryOperator::ShlAssign:
5521 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005522 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5523 CompLHSTy = CompResultTy;
5524 if (!CompResultTy.isNull())
5525 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005526 break;
5527 case BinaryOperator::AndAssign:
5528 case BinaryOperator::XorAssign:
5529 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005530 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5531 CompLHSTy = CompResultTy;
5532 if (!CompResultTy.isNull())
5533 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005534 break;
5535 case BinaryOperator::Comma:
5536 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5537 break;
5538 }
5539 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005540 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005541 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005542 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5543 else
5544 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005545 CompLHSTy, CompResultTy,
5546 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005547}
5548
Sebastian Redlaee3c932009-10-27 12:10:02 +00005549/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5550/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005551static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5552 const PartialDiagnostic &PD,
5553 SourceRange ParenRange)
5554{
5555 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5556 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5557 // We can't display the parentheses, so just dig the
5558 // warning/error and return.
5559 Self.Diag(Loc, PD);
5560 return;
5561 }
5562
5563 Self.Diag(Loc, PD)
5564 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5565 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5566}
5567
Sebastian Redlaee3c932009-10-27 12:10:02 +00005568/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5569/// operators are mixed in a way that suggests that the programmer forgot that
5570/// comparison operators have higher precedence. The most typical example of
5571/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005572static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5573 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005574 typedef BinaryOperator BinOp;
5575 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5576 rhsopc = static_cast<BinOp::Opcode>(-1);
5577 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005578 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005579 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005580 rhsopc = BO->getOpcode();
5581
5582 // Subs are not binary operators.
5583 if (lhsopc == -1 && rhsopc == -1)
5584 return;
5585
5586 // Bitwise operations are sometimes used as eager logical ops.
5587 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005588 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5589 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005590 return;
5591
Sebastian Redlaee3c932009-10-27 12:10:02 +00005592 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005593 SuggestParentheses(Self, OpLoc,
5594 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005595 << SourceRange(lhs->getLocStart(), OpLoc)
5596 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5597 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5598 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005599 SuggestParentheses(Self, OpLoc,
5600 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005601 << SourceRange(OpLoc, rhs->getLocEnd())
5602 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5603 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005604}
5605
5606/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5607/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5608/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5609static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5610 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005611 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005612 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5613}
5614
Reid Spencer5f016e22007-07-11 17:01:13 +00005615// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005616Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5617 tok::TokenKind Kind,
5618 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005619 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005620 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005621
Steve Narofff69936d2007-09-16 03:34:24 +00005622 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5623 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005624
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005625 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5626 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5627
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005628 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5629}
5630
5631Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5632 BinaryOperator::Opcode Opc,
5633 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005634 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005635 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005636 rhs->getType()->isOverloadableType())) {
5637 // Find all of the overloaded operators visible from this
5638 // point. We perform both an operator-name lookup from the local
5639 // scope and an argument-dependent lookup based on the types of
5640 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005641 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005642 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5643 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005644 if (S)
5645 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5646 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00005647 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005648 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005649 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005650 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005651 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005652
Douglas Gregor063daf62009-03-13 18:40:31 +00005653 // Build the (potentially-overloaded, potentially-dependent)
5654 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005655 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005656 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005657
Douglas Gregoreaebc752008-11-06 23:29:22 +00005658 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005659 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005660}
5661
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005662Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005663 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005664 ExprArg InputArg) {
5665 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005666
Mike Stump390b4cc2009-05-16 07:39:55 +00005667 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005668 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005669 QualType resultType;
5670 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005671 case UnaryOperator::OffsetOf:
5672 assert(false && "Invalid unary operator");
5673 break;
5674
Reid Spencer5f016e22007-07-11 17:01:13 +00005675 case UnaryOperator::PreInc:
5676 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005677 case UnaryOperator::PostInc:
5678 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005679 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005680 Opc == UnaryOperator::PreInc ||
5681 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005682 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005683 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005684 resultType = CheckAddressOfOperand(Input, OpLoc);
5685 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005686 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005687 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005688 resultType = CheckIndirectionOperand(Input, OpLoc);
5689 break;
5690 case UnaryOperator::Plus:
5691 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005692 UsualUnaryConversions(Input);
5693 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005694 if (resultType->isDependentType())
5695 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005696 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5697 break;
5698 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5699 resultType->isEnumeralType())
5700 break;
5701 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5702 Opc == UnaryOperator::Plus &&
5703 resultType->isPointerType())
5704 break;
5705
Sebastian Redl0eb23302009-01-19 00:08:26 +00005706 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5707 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005708 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005709 UsualUnaryConversions(Input);
5710 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005711 if (resultType->isDependentType())
5712 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005713 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5714 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5715 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005716 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005717 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005718 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005719 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5720 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005721 break;
5722 case UnaryOperator::LNot: // logical negation
5723 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005724 DefaultFunctionArrayConversion(Input);
5725 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005726 if (resultType->isDependentType())
5727 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005728 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005729 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5730 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005731 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005732 // In C++, it's bool. C++ 5.3.1p8
5733 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005734 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005735 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005736 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005737 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005738 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005739 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005740 resultType = Input->getType();
5741 break;
5742 }
5743 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005744 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005745
5746 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005747 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005748}
5749
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005750Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5751 UnaryOperator::Opcode Opc,
5752 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005753 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00005754 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5755 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005756 // Find all of the overloaded operators visible from this
5757 // point. We perform both an operator-name lookup from the local
5758 // scope and an argument-dependent lookup based on the types of
5759 // the arguments.
5760 FunctionSet Functions;
5761 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5762 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005763 if (S)
5764 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5765 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005766 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005767 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005768 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005769 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005770
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005771 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5772 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005773
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005774 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5775}
5776
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005777// Unary Operators. 'Tok' is the token for the operator.
5778Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5779 tok::TokenKind Op, ExprArg input) {
5780 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5781}
5782
Steve Naroff1b273c42007-09-16 14:56:35 +00005783/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005784Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5785 SourceLocation LabLoc,
5786 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005787 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005788 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005789
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005790 // If we haven't seen this label yet, create a forward reference. It
5791 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005792 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005793 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005794
Reid Spencer5f016e22007-07-11 17:01:13 +00005795 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005796 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5797 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005798}
5799
Sebastian Redlf53597f2009-03-15 17:47:39 +00005800Sema::OwningExprResult
5801Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5802 SourceLocation RPLoc) { // "({..})"
5803 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005804 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5805 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5806
Eli Friedmandca2b732009-01-24 23:09:00 +00005807 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005808 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005809 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005810
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005811 // FIXME: there are a variety of strange constraints to enforce here, for
5812 // example, it is not possible to goto into a stmt expression apparently.
5813 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005814
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005815 // If there are sub stmts in the compound stmt, take the type of the last one
5816 // as the type of the stmtexpr.
5817 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005818
Chris Lattner611b2ec2008-07-26 19:51:01 +00005819 if (!Compound->body_empty()) {
5820 Stmt *LastStmt = Compound->body_back();
5821 // If LastStmt is a label, skip down through into the body.
5822 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5823 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005824
Chris Lattner611b2ec2008-07-26 19:51:01 +00005825 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005826 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005827 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005828
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005829 // FIXME: Check that expression type is complete/non-abstract; statement
5830 // expressions are not lvalues.
5831
Sebastian Redlf53597f2009-03-15 17:47:39 +00005832 substmt.release();
5833 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005834}
Steve Naroffd34e9152007-08-01 22:05:33 +00005835
Sebastian Redlf53597f2009-03-15 17:47:39 +00005836Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5837 SourceLocation BuiltinLoc,
5838 SourceLocation TypeLoc,
5839 TypeTy *argty,
5840 OffsetOfComponent *CompPtr,
5841 unsigned NumComponents,
5842 SourceLocation RPLoc) {
5843 // FIXME: This function leaks all expressions in the offset components on
5844 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005845 // FIXME: Preserve type source info.
5846 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005847 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005848
Sebastian Redl28507842009-02-26 14:39:58 +00005849 bool Dependent = ArgTy->isDependentType();
5850
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005851 // We must have at least one component that refers to the type, and the first
5852 // one is known to be a field designator. Verify that the ArgTy represents
5853 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005854 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005855 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005856
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005857 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5858 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005859
Eli Friedman35183ac2009-02-27 06:44:11 +00005860 // Otherwise, create a null pointer as the base, and iteratively process
5861 // the offsetof designators.
5862 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5863 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005864 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005865 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005866
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005867 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5868 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005869 // FIXME: This diagnostic isn't actually visible because the location is in
5870 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005871 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005872 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5873 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005874
Sebastian Redl28507842009-02-26 14:39:58 +00005875 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005876 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005877
John McCalld00f2002009-11-04 03:03:43 +00005878 if (RequireCompleteType(TypeLoc, Res->getType(),
5879 diag::err_offsetof_incomplete_type))
5880 return ExprError();
5881
Sebastian Redl28507842009-02-26 14:39:58 +00005882 // FIXME: Dependent case loses a lot of information here. And probably
5883 // leaks like a sieve.
5884 for (unsigned i = 0; i != NumComponents; ++i) {
5885 const OffsetOfComponent &OC = CompPtr[i];
5886 if (OC.isBrackets) {
5887 // Offset of an array sub-field. TODO: Should we allow vector elements?
5888 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5889 if (!AT) {
5890 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005891 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5892 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005893 }
5894
5895 // FIXME: C++: Verify that operator[] isn't overloaded.
5896
Eli Friedman35183ac2009-02-27 06:44:11 +00005897 // Promote the array so it looks more like a normal array subscript
5898 // expression.
5899 DefaultFunctionArrayConversion(Res);
5900
Sebastian Redl28507842009-02-26 14:39:58 +00005901 // C99 6.5.2.1p1
5902 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005903 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005904 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005905 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005906 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005907 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005908
5909 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5910 OC.LocEnd);
5911 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005912 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005913
Ted Kremenek6217b802009-07-29 21:53:49 +00005914 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005915 if (!RC) {
5916 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005917 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5918 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005919 }
Chris Lattner704fe352007-08-30 17:59:59 +00005920
Sebastian Redl28507842009-02-26 14:39:58 +00005921 // Get the decl corresponding to this.
5922 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005923 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005924 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005925 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5926 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5927 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005928 DidWarnAboutNonPOD = true;
5929 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005930 }
Mike Stump1eb44332009-09-09 15:08:12 +00005931
John McCalla24dc2e2009-11-17 02:14:36 +00005932 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5933 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00005934
Sebastian Redl28507842009-02-26 14:39:58 +00005935 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005936 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005937 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005938 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005939 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5940 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005941
Sebastian Redl28507842009-02-26 14:39:58 +00005942 // FIXME: C++: Verify that MemberDecl isn't a static field.
5943 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005944 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005945 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00005946 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005947 } else {
5948 // MemberDecl->getType() doesn't get the right qualifiers, but it
5949 // doesn't matter here.
5950 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5951 MemberDecl->getType().getNonReferenceType());
5952 }
Sebastian Redl28507842009-02-26 14:39:58 +00005953 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005954 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005955
Sebastian Redlf53597f2009-03-15 17:47:39 +00005956 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5957 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005958}
5959
5960
Sebastian Redlf53597f2009-03-15 17:47:39 +00005961Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5962 TypeTy *arg1,TypeTy *arg2,
5963 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005964 // FIXME: Preserve type source info.
5965 QualType argT1 = GetTypeFromParser(arg1);
5966 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005967
Steve Naroffd34e9152007-08-01 22:05:33 +00005968 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005969
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005970 if (getLangOptions().CPlusPlus) {
5971 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5972 << SourceRange(BuiltinLoc, RPLoc);
5973 return ExprError();
5974 }
5975
Sebastian Redlf53597f2009-03-15 17:47:39 +00005976 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5977 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005978}
5979
Sebastian Redlf53597f2009-03-15 17:47:39 +00005980Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5981 ExprArg cond,
5982 ExprArg expr1, ExprArg expr2,
5983 SourceLocation RPLoc) {
5984 Expr *CondExpr = static_cast<Expr*>(cond.get());
5985 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5986 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005987
Steve Naroffd04fdd52007-08-03 21:21:27 +00005988 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5989
Sebastian Redl28507842009-02-26 14:39:58 +00005990 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005991 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005992 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005993 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005994 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005995 } else {
5996 // The conditional expression is required to be a constant expression.
5997 llvm::APSInt condEval(32);
5998 SourceLocation ExpLoc;
5999 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006000 return ExprError(Diag(ExpLoc,
6001 diag::err_typecheck_choose_expr_requires_constant)
6002 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006003
Sebastian Redl28507842009-02-26 14:39:58 +00006004 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6005 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006006 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6007 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006008 }
6009
Sebastian Redlf53597f2009-03-15 17:47:39 +00006010 cond.release(); expr1.release(); expr2.release();
6011 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006012 resType, RPLoc,
6013 resType->isDependentType(),
6014 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006015}
6016
Steve Naroff4eb206b2008-09-03 18:15:37 +00006017//===----------------------------------------------------------------------===//
6018// Clang Extensions.
6019//===----------------------------------------------------------------------===//
6020
6021/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006022void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006023 // Analyze block parameters.
6024 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006025
Steve Naroff4eb206b2008-09-03 18:15:37 +00006026 // Add BSI to CurBlock.
6027 BSI->PrevBlockInfo = CurBlock;
6028 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006029
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006030 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006031 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006032 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006033 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006034 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6035 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006036
Steve Naroff090276f2008-10-10 01:28:17 +00006037 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006038 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006039}
6040
Mike Stump98eb8a72009-02-04 22:31:32 +00006041void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006042 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006043
6044 if (ParamInfo.getNumTypeObjects() == 0
6045 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006046 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006047 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6048
Mike Stump4eeab842009-04-28 01:10:27 +00006049 if (T->isArrayType()) {
6050 Diag(ParamInfo.getSourceRange().getBegin(),
6051 diag::err_block_returns_array);
6052 return;
6053 }
6054
Mike Stump98eb8a72009-02-04 22:31:32 +00006055 // The parameter list is optional, if there was none, assume ().
6056 if (!T->isFunctionType())
6057 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6058
6059 CurBlock->hasPrototype = true;
6060 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006061 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006062 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006063 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006064 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006065 // FIXME: remove the attribute.
6066 }
John McCall183700f2009-09-21 23:43:11 +00006067 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006068
Chris Lattner9097af12009-04-11 19:27:54 +00006069 // Do not allow returning a objc interface by-value.
6070 if (RetTy->isObjCInterfaceType()) {
6071 Diag(ParamInfo.getSourceRange().getBegin(),
6072 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6073 return;
6074 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006075 return;
6076 }
6077
Steve Naroff4eb206b2008-09-03 18:15:37 +00006078 // Analyze arguments to block.
6079 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6080 "Not a function declarator!");
6081 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006082
Steve Naroff090276f2008-10-10 01:28:17 +00006083 CurBlock->hasPrototype = FTI.hasPrototype;
6084 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006085
Steve Naroff4eb206b2008-09-03 18:15:37 +00006086 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6087 // no arguments, not a function that takes a single void argument.
6088 if (FTI.hasPrototype &&
6089 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006090 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6091 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006092 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006093 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006094 } else if (FTI.hasPrototype) {
6095 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006096 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006097 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006098 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006099 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006100 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006101 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006102 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006103 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6104 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6105 // If this has an identifier, add it to the scope stack.
6106 if ((*AI)->getIdentifier())
6107 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006108
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006109 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006110 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006111 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006112 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006113 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006114 // FIXME: remove the attribute.
6115 }
Mike Stump1eb44332009-09-09 15:08:12 +00006116
Chris Lattner9097af12009-04-11 19:27:54 +00006117 // Analyze the return type.
6118 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006119 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006120
Chris Lattner9097af12009-04-11 19:27:54 +00006121 // Do not allow returning a objc interface by-value.
6122 if (RetTy->isObjCInterfaceType()) {
6123 Diag(ParamInfo.getSourceRange().getBegin(),
6124 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6125 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006126 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006127}
6128
6129/// ActOnBlockError - If there is an error parsing a block, this callback
6130/// is invoked to pop the information about the block from the action impl.
6131void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6132 // Ensure that CurBlock is deleted.
6133 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006134
Chris Lattner17a78302009-04-19 05:28:12 +00006135 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6136
Steve Naroff4eb206b2008-09-03 18:15:37 +00006137 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006138 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006139 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006140 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006141}
6142
6143/// ActOnBlockStmtExpr - This is called when the body of a block statement
6144/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006145Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6146 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006147 // If blocks are disabled, emit an error.
6148 if (!LangOpts.Blocks)
6149 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006150
Steve Naroff4eb206b2008-09-03 18:15:37 +00006151 // Ensure that CurBlock is deleted.
6152 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006153
Steve Naroff090276f2008-10-10 01:28:17 +00006154 PopDeclContext();
6155
Steve Naroff4eb206b2008-09-03 18:15:37 +00006156 // Pop off CurBlock, handle nested blocks.
6157 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006158
Steve Naroff4eb206b2008-09-03 18:15:37 +00006159 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006160 if (!BSI->ReturnType.isNull())
6161 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006162
Steve Naroff4eb206b2008-09-03 18:15:37 +00006163 llvm::SmallVector<QualType, 8> ArgTypes;
6164 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6165 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006166
Mike Stump56925862009-07-28 22:04:01 +00006167 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006168 QualType BlockTy;
6169 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006170 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6171 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006172 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006173 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006174 BSI->isVariadic, 0, false, false, 0, 0,
6175 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006176
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006177 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006178 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006179 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006180
Chris Lattner17a78302009-04-19 05:28:12 +00006181 // If needed, diagnose invalid gotos and switches in the block.
6182 if (CurFunctionNeedsScopeChecking)
6183 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6184 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006185
Anders Carlssone9146f22009-05-01 19:49:17 +00006186 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006187 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006188 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6189 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006190}
6191
Sebastian Redlf53597f2009-03-15 17:47:39 +00006192Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6193 ExprArg expr, TypeTy *type,
6194 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006195 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006196 Expr *E = static_cast<Expr*>(expr.get());
6197 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006198
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006199 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006200
6201 // Get the va_list type
6202 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006203 if (VaListType->isArrayType()) {
6204 // Deal with implicit array decay; for example, on x86-64,
6205 // va_list is an array, but it's supposed to decay to
6206 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006207 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006208 // Make sure the input expression also decays appropriately.
6209 UsualUnaryConversions(E);
6210 } else {
6211 // Otherwise, the va_list argument must be an l-value because
6212 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006213 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006214 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006215 return ExprError();
6216 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006217
Douglas Gregordd027302009-05-19 23:10:31 +00006218 if (!E->isTypeDependent() &&
6219 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006220 return ExprError(Diag(E->getLocStart(),
6221 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006222 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006223 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006224
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006225 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006226 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006227
Sebastian Redlf53597f2009-03-15 17:47:39 +00006228 expr.release();
6229 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6230 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006231}
6232
Sebastian Redlf53597f2009-03-15 17:47:39 +00006233Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006234 // The type of __null will be int or long, depending on the size of
6235 // pointers on the target.
6236 QualType Ty;
6237 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6238 Ty = Context.IntTy;
6239 else
6240 Ty = Context.LongTy;
6241
Sebastian Redlf53597f2009-03-15 17:47:39 +00006242 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006243}
6244
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006245static void
6246MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6247 QualType DstType,
6248 Expr *SrcExpr,
6249 CodeModificationHint &Hint) {
6250 if (!SemaRef.getLangOptions().ObjC1)
6251 return;
6252
6253 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6254 if (!PT)
6255 return;
6256
6257 // Check if the destination is of type 'id'.
6258 if (!PT->isObjCIdType()) {
6259 // Check if the destination is the 'NSString' interface.
6260 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6261 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6262 return;
6263 }
6264
6265 // Strip off any parens and casts.
6266 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6267 if (!SL || SL->isWide())
6268 return;
6269
6270 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6271}
6272
Chris Lattner5cf216b2008-01-04 18:04:52 +00006273bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6274 SourceLocation Loc,
6275 QualType DstType, QualType SrcType,
6276 Expr *SrcExpr, const char *Flavor) {
6277 // Decode the result (notice that AST's are still created for extensions).
6278 bool isInvalid = false;
6279 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006280 CodeModificationHint Hint;
6281
Chris Lattner5cf216b2008-01-04 18:04:52 +00006282 switch (ConvTy) {
6283 default: assert(0 && "Unknown conversion type");
6284 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006285 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006286 DiagKind = diag::ext_typecheck_convert_pointer_int;
6287 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006288 case IntToPointer:
6289 DiagKind = diag::ext_typecheck_convert_int_pointer;
6290 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006291 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006292 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006293 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6294 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006295 case IncompatiblePointerSign:
6296 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6297 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006298 case FunctionVoidPointer:
6299 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6300 break;
6301 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006302 // If the qualifiers lost were because we were applying the
6303 // (deprecated) C++ conversion from a string literal to a char*
6304 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6305 // Ideally, this check would be performed in
6306 // CheckPointerTypesForAssignment. However, that would require a
6307 // bit of refactoring (so that the second argument is an
6308 // expression, rather than a type), which should be done as part
6309 // of a larger effort to fix CheckPointerTypesForAssignment for
6310 // C++ semantics.
6311 if (getLangOptions().CPlusPlus &&
6312 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6313 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006314 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6315 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006316 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006317 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006318 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006319 case IntToBlockPointer:
6320 DiagKind = diag::err_int_to_block_pointer;
6321 break;
6322 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006323 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006324 break;
Steve Naroff39579072008-10-14 22:18:38 +00006325 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006326 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006327 // it can give a more specific diagnostic.
6328 DiagKind = diag::warn_incompatible_qualified_id;
6329 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006330 case IncompatibleVectors:
6331 DiagKind = diag::warn_incompatible_vectors;
6332 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006333 case Incompatible:
6334 DiagKind = diag::err_typecheck_convert_incompatible;
6335 isInvalid = true;
6336 break;
6337 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006338
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006339 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006340 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006341 return isInvalid;
6342}
Anders Carlssone21555e2008-11-30 19:50:32 +00006343
Chris Lattner3bf68932009-04-25 21:59:05 +00006344bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006345 llvm::APSInt ICEResult;
6346 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6347 if (Result)
6348 *Result = ICEResult;
6349 return false;
6350 }
6351
Anders Carlssone21555e2008-11-30 19:50:32 +00006352 Expr::EvalResult EvalResult;
6353
Mike Stumpeed9cac2009-02-19 03:04:26 +00006354 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006355 EvalResult.HasSideEffects) {
6356 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6357
6358 if (EvalResult.Diag) {
6359 // We only show the note if it's not the usual "invalid subexpression"
6360 // or if it's actually in a subexpression.
6361 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6362 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6363 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6364 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006365
Anders Carlssone21555e2008-11-30 19:50:32 +00006366 return true;
6367 }
6368
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006369 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6370 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006371
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006372 if (EvalResult.Diag &&
6373 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6374 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006375
Anders Carlssone21555e2008-11-30 19:50:32 +00006376 if (Result)
6377 *Result = EvalResult.Val.getInt();
6378 return false;
6379}
Douglas Gregore0762c92009-06-19 23:52:42 +00006380
Douglas Gregor2afce722009-11-26 00:44:06 +00006381void
Mike Stump1eb44332009-09-09 15:08:12 +00006382Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006383 ExprEvalContexts.push_back(
6384 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006385}
6386
Mike Stump1eb44332009-09-09 15:08:12 +00006387void
Douglas Gregor2afce722009-11-26 00:44:06 +00006388Sema::PopExpressionEvaluationContext() {
6389 // Pop the current expression evaluation context off the stack.
6390 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6391 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006392
Douglas Gregor2afce722009-11-26 00:44:06 +00006393 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6394 Rec.PotentiallyReferenced) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006395 // Mark any remaining declarations in the current position of the stack
6396 // as "referenced". If they were not meant to be referenced, semantic
6397 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregor2afce722009-11-26 00:44:06 +00006398 for (PotentiallyReferencedDecls::iterator
6399 I = Rec.PotentiallyReferenced->begin(),
6400 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006401 I != IEnd; ++I)
6402 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregor2afce722009-11-26 00:44:06 +00006403 }
6404
6405 // When are coming out of an unevaluated context, clear out any
6406 // temporaries that we may have created as part of the evaluation of
6407 // the expression in that context: they aren't relevant because they
6408 // will never be constructed.
6409 if (Rec.Context == Unevaluated &&
6410 ExprTemporaries.size() > Rec.NumTemporaries)
6411 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6412 ExprTemporaries.end());
6413
6414 // Destroy the popped expression evaluation record.
6415 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006416}
Douglas Gregore0762c92009-06-19 23:52:42 +00006417
6418/// \brief Note that the given declaration was referenced in the source code.
6419///
6420/// This routine should be invoke whenever a given declaration is referenced
6421/// in the source code, and where that reference occurred. If this declaration
6422/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6423/// C99 6.9p3), then the declaration will be marked as used.
6424///
6425/// \param Loc the location where the declaration was referenced.
6426///
6427/// \param D the declaration that has been referenced by the source code.
6428void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6429 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006430
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006431 if (D->isUsed())
6432 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006433
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006434 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6435 // template or not. The reason for this is that unevaluated expressions
6436 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6437 // -Wunused-parameters)
6438 if (isa<ParmVarDecl>(D) ||
6439 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006440 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006441
Douglas Gregore0762c92009-06-19 23:52:42 +00006442 // Do not mark anything as "used" within a dependent context; wait for
6443 // an instantiation.
6444 if (CurContext->isDependentContext())
6445 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006446
Douglas Gregor2afce722009-11-26 00:44:06 +00006447 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006448 case Unevaluated:
6449 // We are in an expression that is not potentially evaluated; do nothing.
6450 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006451
Douglas Gregorac7610d2009-06-22 20:57:11 +00006452 case PotentiallyEvaluated:
6453 // We are in a potentially-evaluated expression, so this declaration is
6454 // "used"; handle this below.
6455 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006456
Douglas Gregorac7610d2009-06-22 20:57:11 +00006457 case PotentiallyPotentiallyEvaluated:
6458 // We are in an expression that may be potentially evaluated; queue this
6459 // declaration reference until we know whether the expression is
6460 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00006461 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00006462 return;
6463 }
Mike Stump1eb44332009-09-09 15:08:12 +00006464
Douglas Gregore0762c92009-06-19 23:52:42 +00006465 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006466 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006467 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006468 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6469 if (!Constructor->isUsed())
6470 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006471 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006472 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006473 if (!Constructor->isUsed())
6474 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6475 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006476 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6477 if (Destructor->isImplicit() && !Destructor->isUsed())
6478 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006479
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006480 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6481 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6482 MethodDecl->getOverloadedOperator() == OO_Equal) {
6483 if (!MethodDecl->isUsed())
6484 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6485 }
6486 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006487 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006488 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006489 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006490 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006491 bool AlreadyInstantiated = false;
6492 if (FunctionTemplateSpecializationInfo *SpecInfo
6493 = Function->getTemplateSpecializationInfo()) {
6494 if (SpecInfo->getPointOfInstantiation().isInvalid())
6495 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006496 else if (SpecInfo->getTemplateSpecializationKind()
6497 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006498 AlreadyInstantiated = true;
6499 } else if (MemberSpecializationInfo *MSInfo
6500 = Function->getMemberSpecializationInfo()) {
6501 if (MSInfo->getPointOfInstantiation().isInvalid())
6502 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006503 else if (MSInfo->getTemplateSpecializationKind()
6504 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006505 AlreadyInstantiated = true;
6506 }
6507
6508 if (!AlreadyInstantiated)
6509 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6510 }
6511
Douglas Gregore0762c92009-06-19 23:52:42 +00006512 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006513 Function->setUsed(true);
6514 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006515 }
Mike Stump1eb44332009-09-09 15:08:12 +00006516
Douglas Gregore0762c92009-06-19 23:52:42 +00006517 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006518 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006519 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006520 Var->getInstantiatedFromStaticDataMember()) {
6521 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6522 assert(MSInfo && "Missing member specialization information?");
6523 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6524 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6525 MSInfo->setPointOfInstantiation(Loc);
6526 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6527 }
6528 }
Mike Stump1eb44332009-09-09 15:08:12 +00006529
Douglas Gregore0762c92009-06-19 23:52:42 +00006530 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006531
Douglas Gregore0762c92009-06-19 23:52:42 +00006532 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006533 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006534 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006535}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006536
6537bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6538 CallExpr *CE, FunctionDecl *FD) {
6539 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6540 return false;
6541
6542 PartialDiagnostic Note =
6543 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6544 << FD->getDeclName() : PDiag();
6545 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6546
6547 if (RequireCompleteType(Loc, ReturnType,
6548 FD ?
6549 PDiag(diag::err_call_function_incomplete_return)
6550 << CE->getSourceRange() << FD->getDeclName() :
6551 PDiag(diag::err_call_incomplete_return)
6552 << CE->getSourceRange(),
6553 std::make_pair(NoteLoc, Note)))
6554 return true;
6555
6556 return false;
6557}
6558
John McCall5a881bb2009-10-12 21:59:07 +00006559// Diagnose the common s/=/==/ typo. Note that adding parentheses
6560// will prevent this condition from triggering, which is what we want.
6561void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6562 SourceLocation Loc;
6563
John McCalla52ef082009-11-11 02:41:58 +00006564 unsigned diagnostic = diag::warn_condition_is_assignment;
6565
John McCall5a881bb2009-10-12 21:59:07 +00006566 if (isa<BinaryOperator>(E)) {
6567 BinaryOperator *Op = cast<BinaryOperator>(E);
6568 if (Op->getOpcode() != BinaryOperator::Assign)
6569 return;
6570
John McCallc8d8ac52009-11-12 00:06:05 +00006571 // Greylist some idioms by putting them into a warning subcategory.
6572 if (ObjCMessageExpr *ME
6573 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6574 Selector Sel = ME->getSelector();
6575
John McCallc8d8ac52009-11-12 00:06:05 +00006576 // self = [<foo> init...]
6577 if (isSelfExpr(Op->getLHS())
6578 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6579 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6580
6581 // <foo> = [<bar> nextObject]
6582 else if (Sel.isUnarySelector() &&
6583 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6584 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6585 }
John McCalla52ef082009-11-11 02:41:58 +00006586
John McCall5a881bb2009-10-12 21:59:07 +00006587 Loc = Op->getOperatorLoc();
6588 } else if (isa<CXXOperatorCallExpr>(E)) {
6589 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6590 if (Op->getOperator() != OO_Equal)
6591 return;
6592
6593 Loc = Op->getOperatorLoc();
6594 } else {
6595 // Not an assignment.
6596 return;
6597 }
6598
John McCall5a881bb2009-10-12 21:59:07 +00006599 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006600 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006601
John McCalla52ef082009-11-11 02:41:58 +00006602 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00006603 << E->getSourceRange()
6604 << CodeModificationHint::CreateInsertion(Open, "(")
6605 << CodeModificationHint::CreateInsertion(Close, ")");
6606}
6607
6608bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6609 DiagnoseAssignmentAsCondition(E);
6610
6611 if (!E->isTypeDependent()) {
6612 DefaultFunctionArrayConversion(E);
6613
6614 QualType T = E->getType();
6615
6616 if (getLangOptions().CPlusPlus) {
6617 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6618 return true;
6619 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6620 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6621 << T << E->getSourceRange();
6622 return true;
6623 }
6624 }
6625
6626 return false;
6627}