blob: fd79935fbd9fb7d486db1b4c83ba9a72980ec1d0 [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];
155 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
Douglas Gregorce940492009-09-25 04:25:58 +0000156 !sentinelExpr->isNullPointerConstant(Context,
157 Expr::NPC_ValueDependentIsNull))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000158 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000159 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000160 }
161 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000162}
163
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000164SourceRange Sema::getExprRange(ExprTy *E) const {
165 Expr *Ex = (Expr *)E;
166 return Ex? Ex->getSourceRange() : SourceRange();
167}
168
Chris Lattnere7a2e912008-07-25 21:10:04 +0000169//===----------------------------------------------------------------------===//
170// Standard Promotions and Conversions
171//===----------------------------------------------------------------------===//
172
Chris Lattnere7a2e912008-07-25 21:10:04 +0000173/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
174void Sema::DefaultFunctionArrayConversion(Expr *&E) {
175 QualType Ty = E->getType();
176 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
177
Chris Lattnere7a2e912008-07-25 21:10:04 +0000178 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000179 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000180 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000181 else if (Ty->isArrayType()) {
182 // In C90 mode, arrays only promote to pointers if the array expression is
183 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
184 // type 'array of type' is converted to an expression that has type 'pointer
185 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
186 // that has type 'array of type' ...". The relevant change is "an lvalue"
187 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000188 //
189 // C++ 4.2p1:
190 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
191 // T" can be converted to an rvalue of type "pointer to T".
192 //
193 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
194 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000195 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
196 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000197 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000198}
199
200/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000201/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000202/// sometimes surpressed. For example, the array->pointer conversion doesn't
203/// apply if the array is an argument to the sizeof or address (&) operators.
204/// In these instances, this routine should *not* be called.
205Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
206 QualType Ty = Expr->getType();
207 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Douglas Gregorfc24e442009-05-01 20:41:21 +0000209 // C99 6.3.1.1p2:
210 //
211 // The following may be used in an expression wherever an int or
212 // unsigned int may be used:
213 // - an object or expression with an integer type whose integer
214 // conversion rank is less than or equal to the rank of int
215 // and unsigned int.
216 // - A bit-field of type _Bool, int, signed int, or unsigned int.
217 //
218 // If an int can represent all values of the original type, the
219 // value is converted to an int; otherwise, it is converted to an
220 // unsigned int. These are called the integer promotions. All
221 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000222 QualType PTy = Context.isPromotableBitField(Expr);
223 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000224 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000225 return Expr;
226 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000227 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000228 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000229 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000230 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000231 }
232
Douglas Gregorfc24e442009-05-01 20:41:21 +0000233 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234 return Expr;
235}
236
Chris Lattner05faf172008-07-25 22:25:12 +0000237/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000238/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000239/// double. All other argument types are converted by UsualUnaryConversions().
240void Sema::DefaultArgumentPromotion(Expr *&Expr) {
241 QualType Ty = Expr->getType();
242 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattner05faf172008-07-25 22:25:12 +0000244 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000245 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000246 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000247 return ImpCastExprToType(Expr, Context.DoubleTy,
248 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattner05faf172008-07-25 22:25:12 +0000250 UsualUnaryConversions(Expr);
251}
252
Chris Lattner312531a2009-04-12 08:11:20 +0000253/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
254/// will warn if the resulting type is not a POD type, and rejects ObjC
255/// interfaces passed by value. This returns true if the argument type is
256/// completely illegal.
257bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000258 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Chris Lattner312531a2009-04-12 08:11:20 +0000260 if (Expr->getType()->isObjCInterfaceType()) {
261 Diag(Expr->getLocStart(),
262 diag::err_cannot_pass_objc_interface_to_vararg)
263 << Expr->getType() << CT;
264 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000265 }
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattner312531a2009-04-12 08:11:20 +0000267 if (!Expr->getType()->isPODType())
268 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
269 << Expr->getType() << CT;
270
271 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000272}
273
274
Chris Lattnere7a2e912008-07-25 21:10:04 +0000275/// UsualArithmeticConversions - Performs various conversions that are common to
276/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000277/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000278/// responsible for emitting appropriate error diagnostics.
279/// FIXME: verify the conversion rules for "complex int" are consistent with
280/// GCC.
281QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
282 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000283 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000284 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000285
286 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000287
Mike Stump1eb44332009-09-09 15:08:12 +0000288 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000289 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000290 QualType lhs =
291 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000292 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000293 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000294
295 // If both types are identical, no conversion is needed.
296 if (lhs == rhs)
297 return lhs;
298
299 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
300 // The caller can deal with this (e.g. pointer + int).
301 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
302 return lhs;
303
Douglas Gregor2d833e32009-05-02 00:36:19 +0000304 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000305 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000306 if (!LHSBitfieldPromoteTy.isNull())
307 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000308 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000309 if (!RHSBitfieldPromoteTy.isNull())
310 rhs = RHSBitfieldPromoteTy;
311
Eli Friedmana95d7572009-08-19 07:44:53 +0000312 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000313 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000314 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
315 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000316 return destType;
317}
318
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319//===----------------------------------------------------------------------===//
320// Semantic Analysis for various Expression Types
321//===----------------------------------------------------------------------===//
322
323
Steve Narofff69936d2007-09-16 03:34:24 +0000324/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000325/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
326/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
327/// multiple tokens. However, the common case is that StringToks points to one
328/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000329///
330Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000331Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 assert(NumStringToks && "Must have at least one string!");
333
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000334 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000336 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000337
338 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
339 for (unsigned i = 0; i != NumStringToks; ++i)
340 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000341
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000342 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000343 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000344 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000345
346 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
347 if (getLangOptions().CPlusPlus)
348 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000349
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000350 // Get an array type for the string, according to C99 6.4.5. This includes
351 // the nul terminator character as well as the string length for pascal
352 // strings.
353 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000354 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000355 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000358 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000359 Literal.GetStringLength(),
360 Literal.AnyWide, StrTy,
361 &StringTokLocs[0],
362 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
Chris Lattner639e2d32008-10-20 05:16:36 +0000365/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
366/// CurBlock to VD should cause it to be snapshotted (as we do for auto
367/// variables defined outside the block) or false if this is not needed (e.g.
368/// for values inside the block or for globals).
369///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000370/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
371/// up-to-date.
372///
Chris Lattner639e2d32008-10-20 05:16:36 +0000373static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
374 ValueDecl *VD) {
375 // If the value is defined inside the block, we couldn't snapshot it even if
376 // we wanted to.
377 if (CurBlock->TheDecl == VD->getDeclContext())
378 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner639e2d32008-10-20 05:16:36 +0000380 // If this is an enum constant or function, it is constant, don't snapshot.
381 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
382 return false;
383
384 // If this is a reference to an extern, static, or global variable, no need to
385 // snapshot it.
386 // FIXME: What about 'const' variables in C++?
387 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000388 if (!Var->hasLocalStorage())
389 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000391 // Blocks that have these can't be constant.
392 CurBlock->hasBlockDeclRefExprs = true;
393
394 // If we have nested blocks, the decl may be declared in an outer block (in
395 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
396 // be defined outside all of the current blocks (in which case the blocks do
397 // all get the bit). Walk the nesting chain.
398 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
399 NextBlock = NextBlock->PrevBlockInfo) {
400 // If we found the defining block for the variable, don't mark the block as
401 // having a reference outside it.
402 if (NextBlock->TheDecl == VD->getDeclContext())
403 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000405 // Otherwise, the DeclRef from the inner block causes the outer one to need
406 // a snapshot as well.
407 NextBlock->hasBlockDeclRefExprs = true;
408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner639e2d32008-10-20 05:16:36 +0000410 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000411}
412
Chris Lattner639e2d32008-10-20 05:16:36 +0000413
414
Douglas Gregora2813ce2009-10-23 18:54:35 +0000415/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000416Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000417Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
418 bool TypeDependent, bool ValueDependent,
419 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(),
448 D, Loc,
449 Ty, TypeDependent, ValueDependent));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000450}
451
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000452/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
453/// variable corresponding to the anonymous union or struct whose type
454/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000455static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
456 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000457 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000458 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Mike Stump390b4cc2009-05-16 07:39:55 +0000460 // FIXME: Once Decls are directly linked together, this will be an O(1)
461 // operation rather than a slow walk through DeclContext's vector (which
462 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000463 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000464 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000465 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000466 D != DEnd; ++D) {
467 if (*D == Record) {
468 // The object for the anonymous struct/union directly
469 // follows its type in the list of declarations.
470 ++D;
471 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000472 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000473 return *D;
474 }
475 }
476
477 assert(false && "Missing object for anonymous record");
478 return 0;
479}
480
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000481/// \brief Given a field that represents a member of an anonymous
482/// struct/union, build the path from that field's context to the
483/// actual member.
484///
485/// Construct the sequence of field member references we'll have to
486/// perform to get to the field in the anonymous union/struct. The
487/// list of members is built from the field outward, so traverse it
488/// backwards to go from an object in the current context to the field
489/// we found.
490///
491/// \returns The variable from which the field access should begin,
492/// for an anonymous struct/union that is not a member of another
493/// class. Otherwise, returns NULL.
494VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
495 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000496 assert(Field->getDeclContext()->isRecord() &&
497 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
498 && "Field must be stored inside an anonymous struct or union");
499
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000500 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000501 VarDecl *BaseObject = 0;
502 DeclContext *Ctx = Field->getDeclContext();
503 do {
504 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000505 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000506 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000507 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000508 else {
509 BaseObject = cast<VarDecl>(AnonObject);
510 break;
511 }
512 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000513 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000514 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000515
516 return BaseObject;
517}
518
519Sema::OwningExprResult
520Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
521 FieldDecl *Field,
522 Expr *BaseObjectExpr,
523 SourceLocation OpLoc) {
524 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000525 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 AnonFields);
527
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000528 // Build the expression that refers to the base object, from
529 // which we will build a sequence of member references to each
530 // of the anonymous union objects and, eventually, the field we
531 // found via name lookup.
532 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000533 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000534 if (BaseObject) {
535 // BaseObject is an anonymous struct/union variable (and is,
536 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000538 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000539 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000540 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000541 BaseQuals
542 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000543 } else if (BaseObjectExpr) {
544 // The caller provided the base object expression. Determine
545 // whether its a pointer and whether it adds any qualifiers to the
546 // anonymous struct/union fields we're looking into.
547 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000548 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000549 BaseObjectIsPointer = true;
550 ObjectType = ObjectPtr->getPointeeType();
551 }
John McCall0953e762009-09-24 19:53:00 +0000552 BaseQuals
553 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 } else {
555 // We've found a member of an anonymous struct/union that is
556 // inside a non-anonymous struct/union, so in a well-formed
557 // program our base object expression is "this".
558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
559 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000560 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000561 = Context.getTagDeclType(
562 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
563 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000564 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000565 == Context.getCanonicalType(ThisType)) ||
566 IsDerivedFrom(ThisType, AnonFieldType)) {
567 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000568 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000569 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000570 BaseObjectIsPointer = true;
571 }
572 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000573 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
574 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 }
John McCall0953e762009-09-24 19:53:00 +0000576 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000577 }
578
Mike Stump1eb44332009-09-09 15:08:12 +0000579 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000580 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
581 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000582 }
583
584 // Build the implicit member references to the field of the
585 // anonymous struct/union.
586 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000587 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000588 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
589 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
590 FI != FIEnd; ++FI) {
591 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000592 Qualifiers MemberTypeQuals =
593 Context.getCanonicalType(MemberType).getQualifiers();
594
595 // CVR attributes from the base are picked up by members,
596 // except that 'mutable' members don't pick up 'const'.
597 if ((*FI)->isMutable())
598 ResultQuals.removeConst();
599
600 // GC attributes are never picked up by members.
601 ResultQuals.removeObjCGCAttr();
602
603 // TR 18037 does not allow fields to be declared with address spaces.
604 assert(!MemberTypeQuals.hasAddressSpace());
605
606 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
607 if (NewQuals != MemberTypeQuals)
608 MemberType = Context.getQualifiedType(MemberType, NewQuals);
609
Douglas Gregore0762c92009-06-19 23:52:42 +0000610 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000611 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000612 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
613 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000614 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000615 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616 }
617
Sebastian Redlcd965b92009-01-18 18:53:16 +0000618 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000619}
620
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000621Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
622 const CXXScopeSpec &SS,
623 UnqualifiedId &Name,
624 bool HasTrailingLParen,
625 bool IsAddressOfOperand) {
John McCallb681b612009-11-22 02:49:43 +0000626 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
627 "cannot be direct & operand and have a trailing lparen");
628
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000629 if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
630 ASTTemplateArgsPtr TemplateArgsPtr(*this,
631 Name.TemplateId->getTemplateArgs(),
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000632 Name.TemplateId->NumArgs);
633 return ActOnTemplateIdExpr(SS,
634 TemplateTy::make(Name.TemplateId->Template),
635 Name.TemplateId->TemplateNameLoc,
636 Name.TemplateId->LAngleLoc,
637 TemplateArgsPtr,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000638 Name.TemplateId->RAngleLoc);
639 }
640
641 // FIXME: We lose a bunch of source information by doing this. Later,
642 // we'll want to merge ActOnDeclarationNameExpr's logic into
643 // ActOnIdExpression.
644 return ActOnDeclarationNameExpr(S,
645 Name.StartLocation,
646 GetNameFromUnqualifiedId(Name),
647 HasTrailingLParen,
648 &SS,
649 IsAddressOfOperand);
650}
651
Douglas Gregor10c42622008-11-18 15:03:34 +0000652/// ActOnDeclarationNameExpr - The parser has read some kind of name
653/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
654/// performs lookup on that name and returns an expression that refers
655/// to that name. This routine isn't directly called from the parser,
656/// because the parser doesn't know about DeclarationName. Rather,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000657/// this routine is called by ActOnIdExpression, which contains a
658/// parsed UnqualifiedId.
Douglas Gregor10c42622008-11-18 15:03:34 +0000659///
660/// HasTrailingLParen indicates whether this identifier is used in a
661/// function call context. LookupCtx is only used for a C++
662/// qualified-id (foo::bar) to indicate the class or namespace that
663/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000664///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000665/// isAddressOfOperand means that this expression is the direct operand
666/// of an address-of operator. This matters because this is the only
667/// situation where a qualified name referencing a non-static member may
668/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000669Sema::OwningExprResult
670Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
671 DeclarationName Name, bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000672 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000673 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000674 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000675 if (SS && SS->isInvalid())
676 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000677
678 // C++ [temp.dep.expr]p3:
679 // An id-expression is type-dependent if it contains:
680 // -- a nested-name-specifier that contains a class-name that
681 // names a dependent type.
Douglas Gregor00c44862009-05-29 14:49:33 +0000682 // FIXME: Member of the current instantiation.
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000683 if (SS && isDependentScopeSpecifier(*SS)) {
John McCall865d4472009-11-19 22:55:06 +0000684 return Owned(new (Context) DependentScopeDeclRefExpr(Name, Context.DependentTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000685 Loc, SS->getRange(),
Anders Carlsson9b31df42009-07-09 00:05:08 +0000686 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
687 isAddressOfOperand));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000688 }
689
John McCalla24dc2e2009-11-17 02:14:36 +0000690 LookupResult Lookup(*this, Name, Loc, LookupOrdinaryName);
691 LookupParsedName(Lookup, S, SS, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000692
John McCalla24dc2e2009-11-17 02:14:36 +0000693 if (Lookup.isAmbiguous())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000694 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattner8a934232008-03-31 00:36:02 +0000696 // If this reference is in an Objective-C method, then ivar lookup happens as
697 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000698 IdentifierInfo *II = Name.getAsIdentifierInfo();
699 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000700 // There are two cases to handle here. 1) scoped lookup could have failed,
701 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump1eb44332009-09-09 15:08:12 +0000702 // found a decl, but that decl is outside the current instance method (i.e.
703 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000704 // this name, if the lookup sucedes, we replace it our current decl.
John McCallba135432009-11-21 08:51:07 +0000705
706 // FIXME: we should change lookup to do this.
707
708 // If we're in a class method, we don't normally want to look for
709 // ivars. But if we don't find anything else, and there's an
710 // ivar, that's an error.
711 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
712
713 bool LookForIvars;
714 if (Lookup.empty())
715 LookForIvars = true;
716 else if (IsClassMethod)
717 LookForIvars = false;
718 else
719 LookForIvars = (Lookup.isSingleResult() &&
720 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
721
722 if (LookForIvars) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000723 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000724 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000725 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
John McCallba135432009-11-21 08:51:07 +0000726 // Diagnose using an ivar in a class method.
727 if (IsClassMethod)
728 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
729 << IV->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Chris Lattner5cb10d32009-04-24 22:30:50 +0000731 // If we're referencing an invalid decl, just return this as a silent
732 // error node. The error diagnostic was already emitted on the decl.
733 if (IV->isInvalidDecl())
734 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000735
John McCallba135432009-11-21 08:51:07 +0000736 // Check if referencing a field with __attribute__((deprecated)).
737 if (DiagnoseUseOfDecl(IV, Loc))
738 return ExprError();
739
740 // Diagnose the use of an ivar outside of the declaring class.
741 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
742 ClassDeclared != IFace)
743 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
744
745 // FIXME: This should use a new expr for a direct reference, don't
746 // turn this into Self->ivar, just return a BareIVarExpr or something.
747 IdentifierInfo &II = Context.Idents.get("self");
748 UnqualifiedId SelfName;
749 SelfName.setIdentifier(&II, SourceLocation());
750 CXXScopeSpec SelfScopeSpec;
751 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
752 SelfName, false, false);
753 MarkDeclarationReferenced(Loc, IV);
754 return Owned(new (Context)
755 ObjCIvarRefExpr(IV, IV->getType(), Loc,
756 SelfExpr.takeAs<Expr>(), true, true));
Chris Lattner8a934232008-03-31 00:36:02 +0000757 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000758 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000759 // We should warn if a local variable hides an ivar.
760 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000761 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000762 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000763 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
764 IFace == ClassDeclared)
Chris Lattner5cb10d32009-04-24 22:30:50 +0000765 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000766 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000767 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000768 // Needed to implement property "super.method" notation.
John McCallba135432009-11-21 08:51:07 +0000769 if (Lookup.empty() && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000770 QualType T;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Steve Naroffdd53eb52009-03-05 20:12:00 +0000772 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff14108da2009-07-10 23:34:53 +0000773 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
774 getCurMethodDecl()->getClassInterface()));
Steve Naroffdd53eb52009-03-05 20:12:00 +0000775 else
776 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000777 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000778 }
Chris Lattner8a934232008-03-31 00:36:02 +0000779 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000780
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000781 // Determine whether this name might be a candidate for
782 // argument-dependent lookup.
John McCall5b3f9132009-11-22 01:44:31 +0000783 bool ADL = UseArgumentDependentLookup(SS, Lookup, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000784
John McCallba135432009-11-21 08:51:07 +0000785 if (Lookup.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 // Otherwise, this could be an implicitly declared function reference (legal
787 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000788 if (HasTrailingLParen && II &&
John McCallba135432009-11-21 08:51:07 +0000789 !getLangOptions().CPlusPlus) { // Not in C++.
790 NamedDecl *D = ImplicitlyDefineFunction(Loc, *II, S);
791 if (D) Lookup.addDecl(D);
792 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 // If this name wasn't predeclared and if this is not a function call,
794 // diagnose the problem.
Douglas Gregor3f093272009-10-13 21:16:44 +0000795 if (SS && !SS->isEmpty())
796 return ExprError(Diag(Loc, diag::err_no_member)
797 << Name << computeDeclContext(*SS, false)
798 << SS->getRange());
799 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000800 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000801 return ExprError(Diag(Loc, diag::err_undeclared_use)
802 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000803 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000804 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 }
806 }
Mike Stump1eb44332009-09-09 15:08:12 +0000807
John McCallba135432009-11-21 08:51:07 +0000808 if (VarDecl *Var = Lookup.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000809 // Warn about constructs like:
810 // if (void *X = foo()) { ... } else { X }.
811 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Douglas Gregor751f9a42009-06-30 15:47:41 +0000813 // FIXME: In a template instantiation, we don't have scope
814 // information to check this property.
815 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
816 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000817 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000818 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000819 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000820 ExprError(Diag(Loc, diag::warn_value_always_zero)
821 << Var->getDeclName()
822 << (Var->getType()->isPointerType()? 2 :
823 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000824 break;
825 }
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000827 // Move to the parent of this scope.
828 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000829 }
830 }
John McCallba135432009-11-21 08:51:07 +0000831 } else if (FunctionDecl *Func = Lookup.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000832 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
833 // C99 DR 316 says that, if a function type comes from a
834 // function definition (without a prototype), that type is only
835 // used for checking compatibility. Therefore, when referencing
836 // the function, we pretend that we don't have the full function
837 // type.
838 if (DiagnoseUseOfDecl(Func, Loc))
839 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000840
Douglas Gregor751f9a42009-06-30 15:47:41 +0000841 QualType T = Func->getType();
842 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000843 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000844 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
845 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
846 }
847 }
Mike Stump1eb44332009-09-09 15:08:12 +0000848
John McCall5b3f9132009-11-22 01:44:31 +0000849 // &SomeClass::foo is an abstract member reference, regardless of
850 // the nature of foo, but &SomeClass::foo(...) is not. If this is
851 // *not* an abstract member reference, and any of the results is a
852 // class member (which necessarily means they're all class members),
853 // then we make an implicit member reference instead.
854 //
855 // This check considers all the same information as the "needs ADL"
856 // check, but there's no simple logical relationship other than the
857 // fact that they can never be simultaneously true. We could
858 // calculate them both in one pass if that proves important for
859 // performance.
860 if (!ADL) {
861 bool isAbstractMemberPointer =
John McCallb681b612009-11-22 02:49:43 +0000862 (isAddressOfOperand && SS && !SS->isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +0000863
864 if (!isAbstractMemberPointer && !Lookup.empty() &&
865 isa<CXXRecordDecl>((*Lookup.begin())->getDeclContext())) {
866 return BuildImplicitMemberReferenceExpr(SS, Lookup);
867 }
868 }
869
870 assert(Lookup.getResultKind() != LookupResult::FoundUnresolvedValue &&
871 "found UnresolvedUsingValueDecl in non-class scope");
872
873 return BuildDeclarationNameExpr(SS, Lookup, ADL);
Douglas Gregor751f9a42009-06-30 15:47:41 +0000874}
John McCallba135432009-11-21 08:51:07 +0000875
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000876/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000877bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000878Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
879 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000880 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000881 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000882 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000883 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000884 if (DestType->isDependentType() || From->getType()->isDependentType())
885 return false;
886 QualType FromRecordType = From->getType();
887 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000888 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000889 DestType = Context.getPointerType(DestType);
890 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000891 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000892 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
893 CheckDerivedToBaseConversion(FromRecordType,
894 DestRecordType,
895 From->getSourceRange().getBegin(),
896 From->getSourceRange()))
897 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000898 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
899 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000900 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000901 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000902}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000903
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000904/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000905static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
906 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000907 SourceLocation Loc, QualType Ty) {
908 if (SS && SS->isSet())
Mike Stump1eb44332009-09-09 15:08:12 +0000909 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000910 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump1eb44332009-09-09 15:08:12 +0000911 SS->getRange(), Member, Loc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +0000912 // FIXME: Explicit template argument lists
913 false, SourceLocation(), 0, 0, SourceLocation(),
914 Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000916 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
917}
918
John McCallba135432009-11-21 08:51:07 +0000919/// Builds an implicit member access expression from the given
920/// unqualified lookup set, which is known to contain only class
921/// members.
John McCall5b3f9132009-11-22 01:44:31 +0000922Sema::OwningExprResult
923Sema::BuildImplicitMemberReferenceExpr(const CXXScopeSpec *SS,
924 LookupResult &R) {
925 NamedDecl *D = R.getAsSingleDecl(Context);
John McCallba135432009-11-21 08:51:07 +0000926 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +0000927
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000928 // We may have found a field within an anonymous union or struct
929 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000930 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000931 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
932 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +0000933 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000934
John McCallba135432009-11-21 08:51:07 +0000935 QualType ThisType;
936 QualType MemberType;
John McCall5b3f9132009-11-22 01:44:31 +0000937 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
938 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
939 MarkDeclarationReferenced(Loc, D);
940 if (PerformObjectMemberConversion(This, D))
941 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +0000942
Douglas Gregore961afb2009-10-22 07:08:30 +0000943 bool ShouldCheckUse = true;
944 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
945 // Don't diagnose the use of a virtual member function unless it's
946 // explicitly qualified.
947 if (MD->isVirtual() && (!SS || !SS->isSet()))
948 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +0000949 }
Douglas Gregore961afb2009-10-22 07:08:30 +0000950
John McCall5b3f9132009-11-22 01:44:31 +0000951 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
952 return ExprError();
953 return Owned(BuildMemberExpr(Context, This, true, SS, D, Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000954 }
955
John McCallba135432009-11-21 08:51:07 +0000956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +0000957 if (!Method->isStatic())
958 return ExprError(Diag(Loc, diag::err_member_call_without_object));
John McCallba135432009-11-21 08:51:07 +0000959 }
960
961 if (isa<FieldDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +0000962 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
John McCallba135432009-11-21 08:51:07 +0000963 if (MD->isStatic()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000964 // "invalid use of member 'x' in static member function"
John McCall5b3f9132009-11-22 01:44:31 +0000965 Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallba135432009-11-21 08:51:07 +0000966 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +0000967 return ExprError();
John McCallba135432009-11-21 08:51:07 +0000968 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000969 }
970
Douglas Gregor88a35142008-12-22 05:46:06 +0000971 // Any other ways we could have found the field in a well-formed
972 // program would have been turned into implicit member expressions
973 // above.
John McCall5b3f9132009-11-22 01:44:31 +0000974 Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallba135432009-11-21 08:51:07 +0000975 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +0000976 return ExprError();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000977 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000978
John McCall5b3f9132009-11-22 01:44:31 +0000979 // We're not in an implicit member-reference context, but the lookup
980 // results might not require an instance. Try to build a non-member
981 // decl reference.
982 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
John McCallba135432009-11-21 08:51:07 +0000983}
984
John McCall5b3f9132009-11-22 01:44:31 +0000985bool Sema::UseArgumentDependentLookup(const CXXScopeSpec *SS,
986 const LookupResult &R,
987 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +0000988 // Only when used directly as the postfix-expression of a call.
989 if (!HasTrailingLParen)
990 return false;
991
992 // Never if a scope specifier was provided.
993 if (SS && SS->isSet())
994 return false;
995
996 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +0000997 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +0000998 return false;
999
1000 // Turn off ADL when we find certain kinds of declarations during
1001 // normal lookup:
1002 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1003 NamedDecl *D = *I;
1004
1005 // C++0x [basic.lookup.argdep]p3:
1006 // -- a declaration of a class member
1007 // Since using decls preserve this property, we check this on the
1008 // original decl.
1009 if (D->getDeclContext()->isRecord())
1010 return false;
1011
1012 // C++0x [basic.lookup.argdep]p3:
1013 // -- a block-scope function declaration that is not a
1014 // using-declaration
1015 // NOTE: we also trigger this for function templates (in fact, we
1016 // don't check the decl type at all, since all other decl types
1017 // turn off ADL anyway).
1018 if (isa<UsingShadowDecl>(D))
1019 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1020 else if (D->getDeclContext()->isFunctionOrMethod())
1021 return false;
1022
1023 // C++0x [basic.lookup.argdep]p3:
1024 // -- a declaration that is neither a function or a function
1025 // template
1026 // And also for builtin functions.
1027 if (isa<FunctionDecl>(D)) {
1028 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1029
1030 // But also builtin functions.
1031 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1032 return false;
1033 } else if (!isa<FunctionTemplateDecl>(D))
1034 return false;
1035 }
1036
1037 return true;
1038}
1039
1040
John McCallba135432009-11-21 08:51:07 +00001041/// Diagnoses obvious problems with the use of the given declaration
1042/// as an expression. This is only actually called for lookups that
1043/// were not overloaded, and it doesn't promise that the declaration
1044/// will in fact be used.
1045static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1046 if (isa<TypedefDecl>(D)) {
1047 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1048 return true;
1049 }
1050
1051 if (isa<ObjCInterfaceDecl>(D)) {
1052 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1053 return true;
1054 }
1055
1056 if (isa<NamespaceDecl>(D)) {
1057 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1058 return true;
1059 }
1060
1061 return false;
1062}
1063
1064Sema::OwningExprResult
1065Sema::BuildDeclarationNameExpr(const CXXScopeSpec *SS,
John McCall5b3f9132009-11-22 01:44:31 +00001066 LookupResult &R,
1067 bool NeedsADL) {
1068 assert(R.getResultKind() != LookupResult::FoundUnresolvedValue);
1069
1070 if (!NeedsADL && !R.isOverloadedResult())
1071 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001072
1073 // We only need to check the declaration if there's exactly one
1074 // result, because in the overloaded case the results can only be
1075 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001076 if (R.isSingleResult() &&
1077 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001078 return ExprError();
1079
1080 UnresolvedLookupExpr *ULE
1081 = UnresolvedLookupExpr::Create(Context,
1082 SS ? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7453ed42009-11-22 00:44:51 +00001083 SS ? SS->getRange() : SourceRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001084 R.getLookupName(), R.getNameLoc(),
1085 NeedsADL, R.isOverloadedResult());
1086 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1087 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001088
1089 return Owned(ULE);
1090}
1091
1092
1093/// \brief Complete semantic analysis for a reference to the given declaration.
1094Sema::OwningExprResult
1095Sema::BuildDeclarationNameExpr(const CXXScopeSpec *SS,
1096 SourceLocation Loc, NamedDecl *D) {
1097 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001098 assert(!isa<FunctionTemplateDecl>(D) &&
1099 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001100 DeclarationName Name = D->getDeclName();
1101
1102 if (CheckDeclInExpr(*this, Loc, D))
1103 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001104
Steve Naroffdd972f22008-09-05 22:11:13 +00001105 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001106
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001107 // Check whether this declaration can be used. Note that we suppress
1108 // this check when we're going to perform argument-dependent lookup
1109 // on this function name, because this might not be the function
1110 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001111 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001112 return ExprError();
1113
Steve Naroffdd972f22008-09-05 22:11:13 +00001114 // Only create DeclRefExpr's for valid Decl's.
1115 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001116 return ExprError();
1117
Chris Lattner639e2d32008-10-20 05:16:36 +00001118 // If the identifier reference is inside a block, and it refers to a value
1119 // that is outside the block, create a BlockDeclRefExpr instead of a
1120 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1121 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001122 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001123 // We do not do this for things like enum constants, global variables, etc,
1124 // as they do not get snapshotted.
1125 //
1126 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001127 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001128 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001129 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001130 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001131 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001132 // This is to record that a 'const' was actually synthesize and added.
1133 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001134 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Eli Friedman5fdeae12009-03-22 23:00:19 +00001136 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001137 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001138 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001139 }
1140 // If this reference is not in a block or if the referenced variable is
1141 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001142
Douglas Gregor898574e2008-12-05 23:32:09 +00001143 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001144 bool ValueDependent = false;
1145 if (getLangOptions().CPlusPlus) {
1146 // C++ [temp.dep.expr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001147 // An id-expression is type-dependent if it contains:
Douglas Gregor83f96f62008-12-10 20:57:37 +00001148 // - an identifier that was declared with a dependent type,
1149 if (VD->getType()->isDependentType())
1150 TypeDependent = true;
1151 // - FIXME: a template-id that is dependent,
1152 // - a conversion-function-id that specifies a dependent type,
1153 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1154 Name.getCXXNameType()->isDependentType())
1155 TypeDependent = true;
1156 // - a nested-name-specifier that contains a class-name that
1157 // names a dependent type.
John McCallba135432009-11-21 08:51:07 +00001158 else {
1159 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001160 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001161 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001162 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1163 if (Context.getTypeDeclType(Record)->isDependentType()) {
1164 TypeDependent = true;
1165 break;
1166 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001167 }
1168 }
1169 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001170
Douglas Gregor83f96f62008-12-10 20:57:37 +00001171 // C++ [temp.dep.constexpr]p2:
1172 //
1173 // An identifier is value-dependent if it is:
1174 // - a name declared with a dependent type,
1175 if (TypeDependent)
1176 ValueDependent = true;
1177 // - the name of a non-type template parameter,
1178 else if (isa<NonTypeTemplateParmDecl>(VD))
1179 ValueDependent = true;
1180 // - a constant with integral or enumeration type and is
1181 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001182 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
Mike Stumpfbf68702009-11-03 22:20:01 +00001183 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1184 == Qualifiers::Const &&
Eli Friedmanc1494122009-06-11 01:11:20 +00001185 Dcl->getInit()) {
1186 ValueDependent = Dcl->getInit()->isValueDependent();
1187 }
1188 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001189 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001190
Anders Carlssone41590d2009-06-24 00:10:43 +00001191 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1192 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001193}
1194
Sebastian Redlcd965b92009-01-18 18:53:16 +00001195Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1196 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001197 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001200 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001201 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1202 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1203 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001205
Chris Lattnerfa28b302008-01-12 08:14:25 +00001206 // Pre-defined identifiers are of type char[x], where x is the length of the
1207 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Anders Carlsson3a082d82009-09-08 18:24:21 +00001209 Decl *currentDecl = getCurFunctionOrMethodDecl();
1210 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001211 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001212 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001213 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001214
Anders Carlsson773f3972009-09-11 01:22:35 +00001215 QualType ResTy;
1216 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1217 ResTy = Context.DependentTy;
1218 } else {
1219 unsigned Length =
1220 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001221
Anders Carlsson773f3972009-09-11 01:22:35 +00001222 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001223 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001224 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1225 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001226 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001227}
1228
Sebastian Redlcd965b92009-01-18 18:53:16 +00001229Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 llvm::SmallString<16> CharBuffer;
1231 CharBuffer.resize(Tok.getLength());
1232 const char *ThisTokBegin = &CharBuffer[0];
1233 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1236 Tok.getLocation(), PP);
1237 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001238 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001239
1240 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1241
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001242 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1243 Literal.isWide(),
1244 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001245}
1246
Sebastian Redlcd965b92009-01-18 18:53:16 +00001247Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1248 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1250 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001251 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001252 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001253 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001254 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 }
Ted Kremenek28396602009-01-13 23:19:12 +00001256
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001258 // Add padding so that NumericLiteralParser can overread by one character.
1259 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001261
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 // Get the spelling of the token, which eliminates trigraphs, etc.
1263 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001264
Mike Stump1eb44332009-09-09 15:08:12 +00001265 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 Tok.getLocation(), PP);
1267 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001268 return ExprError();
1269
Chris Lattner5d661452007-08-26 03:42:43 +00001270 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001271
Chris Lattner5d661452007-08-26 03:42:43 +00001272 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001273 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001274 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001275 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001276 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001277 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001278 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001279 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001280
1281 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1282
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001283 // isExact will be set by GetFloatValue().
1284 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001285 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1286 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001287
Chris Lattner5d661452007-08-26 03:42:43 +00001288 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001289 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001290 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001291 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001292
Neil Boothb9449512007-08-29 22:00:19 +00001293 // long long is a C99 feature.
1294 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001295 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001296 Diag(Tok.getLocation(), diag::ext_longlong);
1297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001299 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001300
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 if (Literal.GetIntegerValue(ResultVal)) {
1302 // If this value didn't fit into uintmax_t, warn and force to ull.
1303 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001304 Ty = Context.UnsignedLongLongTy;
1305 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001306 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 } else {
1308 // If this value fits into a ULL, try to figure out what else it fits into
1309 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001310
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1312 // be an unsigned int.
1313 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1314
1315 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001316 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001317 if (!Literal.isLong && !Literal.isLongLong) {
1318 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001319 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 // Does it fit in a unsigned int?
1322 if (ResultVal.isIntN(IntSize)) {
1323 // Does it fit in a signed int?
1324 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001325 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001327 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001328 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001331
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001333 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001334 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001335
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 // Does it fit in a unsigned long?
1337 if (ResultVal.isIntN(LongSize)) {
1338 // Does it fit in a signed long?
1339 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001340 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001342 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001343 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001345 }
1346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001348 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001349 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001350
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // Does it fit in a unsigned long long?
1352 if (ResultVal.isIntN(LongLongSize)) {
1353 // Does it fit in a signed long long?
1354 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001355 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001357 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001358 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 }
1360 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 // If we still couldn't decide a type, we probably have something that
1363 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001364 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001366 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001367 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001369
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001370 if (ResultVal.getBitWidth() != Width)
1371 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001373 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001375
Chris Lattner5d661452007-08-26 03:42:43 +00001376 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1377 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001378 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001379 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001380
1381 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001382}
1383
Sebastian Redlcd965b92009-01-18 18:53:16 +00001384Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1385 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001386 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001387 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001388 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}
1390
1391/// The UsualUnaryConversions() function is *not* called by this routine.
1392/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001393bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001394 SourceLocation OpLoc,
1395 const SourceRange &ExprRange,
1396 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001397 if (exprType->isDependentType())
1398 return false;
1399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001401 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001402 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001403 if (isSizeof)
1404 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1405 return false;
1406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattner1efaa952009-04-24 00:30:45 +00001408 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001409 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001410 Diag(OpLoc, diag::ext_sizeof_void_type)
1411 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001412 return false;
1413 }
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Chris Lattner1efaa952009-04-24 00:30:45 +00001415 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001416 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001417 PDiag(diag::err_alignof_incomplete_type)
1418 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001419 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Chris Lattner1efaa952009-04-24 00:30:45 +00001421 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001422 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001423 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001424 << exprType << isSizeof << ExprRange;
1425 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Chris Lattner1efaa952009-04-24 00:30:45 +00001428 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001429}
1430
Chris Lattner31e21e02009-01-24 20:17:12 +00001431bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1432 const SourceRange &ExprRange) {
1433 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001434
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001436 if (isa<DeclRefExpr>(E))
1437 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001438
1439 // Cannot know anything else if the expression is dependent.
1440 if (E->isTypeDependent())
1441 return false;
1442
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001443 if (E->getBitField()) {
1444 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1445 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001446 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001447
1448 // Alignment of a field access is always okay, so long as it isn't a
1449 // bit-field.
1450 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001451 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001452 return false;
1453
Chris Lattner31e21e02009-01-24 20:17:12 +00001454 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1455}
1456
Douglas Gregorba498172009-03-13 21:01:28 +00001457/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001458Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001459Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1460 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001461 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001462 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001463 return ExprError();
1464
John McCall5ab75172009-11-04 07:28:41 +00001465 QualType T = DInfo->getType();
1466
Douglas Gregorba498172009-03-13 21:01:28 +00001467 if (!T->isDependentType() &&
1468 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1469 return ExprError();
1470
1471 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001472 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001473 Context.getSizeType(), OpLoc,
1474 R.getEnd()));
1475}
1476
1477/// \brief Build a sizeof or alignof expression given an expression
1478/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001479Action::OwningExprResult
1480Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001481 bool isSizeOf, SourceRange R) {
1482 // Verify that the operand is valid.
1483 bool isInvalid = false;
1484 if (E->isTypeDependent()) {
1485 // Delay type-checking for type-dependent expressions.
1486 } else if (!isSizeOf) {
1487 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001488 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001489 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1490 isInvalid = true;
1491 } else {
1492 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1493 }
1494
1495 if (isInvalid)
1496 return ExprError();
1497
1498 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1499 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1500 Context.getSizeType(), OpLoc,
1501 R.getEnd()));
1502}
1503
Sebastian Redl05189992008-11-11 17:56:53 +00001504/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1505/// the same for @c alignof and @c __alignof
1506/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001507Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001508Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1509 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001511 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001512
Sebastian Redl05189992008-11-11 17:56:53 +00001513 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001514 DeclaratorInfo *DInfo;
1515 (void) GetTypeFromParser(TyOrEx, &DInfo);
1516 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001517 }
Sebastian Redl05189992008-11-11 17:56:53 +00001518
Douglas Gregorba498172009-03-13 21:01:28 +00001519 Expr *ArgEx = (Expr *)TyOrEx;
1520 Action::OwningExprResult Result
1521 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1522
1523 if (Result.isInvalid())
1524 DeleteExpr(ArgEx);
1525
1526 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001527}
1528
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001529QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001530 if (V->isTypeDependent())
1531 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Chris Lattnercc26ed72007-08-26 05:39:26 +00001533 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001534 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001535 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Chris Lattnercc26ed72007-08-26 05:39:26 +00001537 // Otherwise they pass through real integer and floating point types here.
1538 if (V->getType()->isArithmeticType())
1539 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Chris Lattnercc26ed72007-08-26 05:39:26 +00001541 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001542 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1543 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001544 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001545}
1546
1547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548
Sebastian Redl0eb23302009-01-19 00:08:26 +00001549Action::OwningExprResult
1550Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1551 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 UnaryOperator::Opcode Opc;
1553 switch (Kind) {
1554 default: assert(0 && "Unknown unary op!");
1555 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1556 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1557 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001558
Eli Friedmane4216e92009-11-18 03:38:04 +00001559 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001560}
1561
Sebastian Redl0eb23302009-01-19 00:08:26 +00001562Action::OwningExprResult
1563Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1564 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001565 // Since this might be a postfix expression, get rid of ParenListExprs.
1566 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1567
Sebastian Redl0eb23302009-01-19 00:08:26 +00001568 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1569 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Douglas Gregor337c6b92008-11-19 17:17:41 +00001571 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001572 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1573 Base.release();
1574 Idx.release();
1575 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1576 Context.DependentTy, RLoc));
1577 }
1578
Mike Stump1eb44332009-09-09 15:08:12 +00001579 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001580 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001581 LHSExp->getType()->isEnumeralType() ||
1582 RHSExp->getType()->isRecordType() ||
1583 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001584 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001585 }
1586
Sebastian Redlf322ed62009-10-29 20:17:01 +00001587 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1588}
1589
1590
1591Action::OwningExprResult
1592Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1593 ExprArg Idx, SourceLocation RLoc) {
1594 Expr *LHSExp = static_cast<Expr*>(Base.get());
1595 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1596
Chris Lattner12d9ff62007-07-16 00:14:47 +00001597 // Perform default conversions.
1598 DefaultFunctionArrayConversion(LHSExp);
1599 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001600
Chris Lattner12d9ff62007-07-16 00:14:47 +00001601 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001602
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001604 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001605 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001607 Expr *BaseExpr, *IndexExpr;
1608 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001609 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1610 BaseExpr = LHSExp;
1611 IndexExpr = RHSExp;
1612 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001613 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001614 BaseExpr = LHSExp;
1615 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001616 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001617 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001618 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001619 BaseExpr = RHSExp;
1620 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001621 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001622 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001623 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001624 BaseExpr = LHSExp;
1625 IndexExpr = RHSExp;
1626 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001627 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001628 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001629 // Handle the uncommon case of "123[Ptr]".
1630 BaseExpr = RHSExp;
1631 IndexExpr = LHSExp;
1632 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001633 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001634 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001635 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001636
Chris Lattner12d9ff62007-07-16 00:14:47 +00001637 // FIXME: need to deal with const...
1638 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001639 } else if (LHSTy->isArrayType()) {
1640 // If we see an array that wasn't promoted by
1641 // DefaultFunctionArrayConversion, it must be an array that
1642 // wasn't promoted because of the C90 rule that doesn't
1643 // allow promoting non-lvalue arrays. Warn, then
1644 // force the promotion here.
1645 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1646 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001647 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1648 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001649 LHSTy = LHSExp->getType();
1650
1651 BaseExpr = LHSExp;
1652 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001653 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001654 } else if (RHSTy->isArrayType()) {
1655 // Same as previous, except for 123[f().a] case
1656 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1657 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001658 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1659 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001660 RHSTy = RHSExp->getType();
1661
1662 BaseExpr = RHSExp;
1663 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001664 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001666 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1667 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001668 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001670 if (!(IndexExpr->getType()->isIntegerType() &&
1671 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001672 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1673 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001674
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001675 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001676 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1677 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001678 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1679
Douglas Gregore7450f52009-03-24 19:52:54 +00001680 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001681 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1682 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001683 // incomplete types are not object types.
1684 if (ResultType->isFunctionType()) {
1685 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1686 << ResultType << BaseExpr->getSourceRange();
1687 return ExprError();
1688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Douglas Gregore7450f52009-03-24 19:52:54 +00001690 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001691 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001692 PDiag(diag::err_subscript_incomplete_type)
1693 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001694 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Chris Lattner1efaa952009-04-24 00:30:45 +00001696 // Diagnose bad cases where we step over interface counts.
1697 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1698 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1699 << ResultType << BaseExpr->getSourceRange();
1700 return ExprError();
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Sebastian Redl0eb23302009-01-19 00:08:26 +00001703 Base.release();
1704 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001705 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001706 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001707}
1708
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001709QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001710CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001711 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001712 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001713 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1714 // see FIXME there.
1715 //
1716 // FIXME: This logic can be greatly simplified by splitting it along
1717 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001718 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001719
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001720 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001721 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001722
Mike Stumpeed9cac2009-02-19 03:04:26 +00001723 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001724 // special names that indicate a subset of exactly half the elements are
1725 // to be selected.
1726 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001727
Nate Begeman353417a2009-01-18 01:47:54 +00001728 // This flag determines whether or not CompName has an 's' char prefix,
1729 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001730 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001731
1732 // Check that we've found one of the special components, or that the component
1733 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001734 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001735 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1736 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001737 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001738 do
1739 compStr++;
1740 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001741 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001742 do
1743 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001744 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001745 }
Nate Begeman353417a2009-01-18 01:47:54 +00001746
Mike Stumpeed9cac2009-02-19 03:04:26 +00001747 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001748 // We didn't get to the end of the string. This means the component names
1749 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001750 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1751 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001752 return QualType();
1753 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001754
Nate Begeman353417a2009-01-18 01:47:54 +00001755 // Ensure no component accessor exceeds the width of the vector type it
1756 // operates on.
1757 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001758 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001759
1760 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001761 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001762
1763 while (*compStr) {
1764 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1765 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1766 << baseType << SourceRange(CompLoc);
1767 return QualType();
1768 }
1769 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001770 }
Nate Begeman8a997642008-05-09 06:41:27 +00001771
Nate Begeman353417a2009-01-18 01:47:54 +00001772 // If this is a halving swizzle, verify that the base type has an even
1773 // number of elements.
1774 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001775 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001776 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001777 return QualType();
1778 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001779
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001780 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001781 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001782 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001783 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001784 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001785 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001786 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001787 if (HexSwizzle)
1788 CompSize--;
1789
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001790 if (CompSize == 1)
1791 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001792
Nate Begeman213541a2008-04-18 23:10:10 +00001793 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001794 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001795 // diagostics look bad. We want extended vector types to appear built-in.
1796 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1797 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1798 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001799 }
1800 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001801}
1802
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001803static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001804 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001805 const Selector &Sel,
1806 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anders Carlsson8f28f992009-08-26 18:25:21 +00001808 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001809 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001810 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001811 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001813 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1814 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001815 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001816 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001817 return D;
1818 }
1819 return 0;
1820}
1821
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001822static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001823 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001824 const Selector &Sel,
1825 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001826 // Check protocols on qualified interfaces.
1827 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001828 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001829 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001830 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001831 GDecl = PD;
1832 break;
1833 }
1834 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001835 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001836 GDecl = OMD;
1837 break;
1838 }
1839 }
1840 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001841 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001842 E = QIdTy->qual_end(); I != E; ++I) {
1843 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001844 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001845 if (GDecl)
1846 return GDecl;
1847 }
1848 }
1849 return GDecl;
1850}
Chris Lattner76a642f2009-02-15 22:43:40 +00001851
Mike Stump1eb44332009-09-09 15:08:12 +00001852Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001853Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001854 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001855 DeclarationName MemberName,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001856 bool HasExplicitTemplateArgs,
1857 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001858 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001859 unsigned NumExplicitTemplateArgs,
1860 SourceLocation RAngleLoc,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001861 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1862 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001863 if (SS && SS->isInvalid())
1864 return ExprError();
1865
Nate Begeman2ef13e52009-08-10 23:49:36 +00001866 // Since this might be a postfix expression, get rid of ParenListExprs.
1867 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1868
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001869 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001870 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Steve Naroff3cc4af82007-12-16 21:42:28 +00001872 // Perform default conversions.
1873 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001874
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001875 QualType BaseType = BaseExpr->getType();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00001876
1877 // If the user is trying to apply -> or . to a function pointer
1878 // type, it's probably because the forgot parentheses to call that
1879 // function. Suggest the addition of those parentheses, build the
1880 // call, and continue on.
1881 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1882 if (const FunctionProtoType *Fun
1883 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1884 QualType ResultTy = Fun->getResultType();
1885 if (Fun->getNumArgs() == 0 &&
1886 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1887 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1888 ResultTy->getAs<PointerType>()->getPointeeType()
1889 ->isRecordType()))) {
1890 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1891 Diag(Loc, diag::err_member_reference_needs_call)
1892 << QualType(Fun, 0)
1893 << CodeModificationHint::CreateInsertion(Loc, "()");
1894
1895 OwningExprResult NewBase
1896 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1897 MultiExprArg(*this, 0, 0), 0, Loc);
1898 if (NewBase.isInvalid())
1899 return move(NewBase);
1900
1901 BaseExpr = NewBase.takeAs<Expr>();
1902 DefaultFunctionArrayConversion(BaseExpr);
1903 BaseType = BaseExpr->getType();
1904 }
1905 }
1906 }
1907
David Chisnall0f436562009-08-17 16:35:33 +00001908 // If this is an Objective-C pseudo-builtin and a definition is provided then
1909 // use that.
1910 if (BaseType->isObjCIdType()) {
1911 // We have an 'id' type. Rather than fall through, we check if this
1912 // is a reference to 'isa'.
1913 if (BaseType != Context.ObjCIdRedefinitionType) {
1914 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001915 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001916 }
David Chisnall0f436562009-08-17 16:35:33 +00001917 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001918 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001919
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001920 // Handle properties on ObjC 'Class' types.
1921 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1922 // Also must look for a getter name which uses property syntax.
1923 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1924 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1925 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1926 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1927 ObjCMethodDecl *Getter;
1928 // FIXME: need to also look locally in the implementation.
1929 if ((Getter = IFace->lookupClassMethod(Sel))) {
1930 // Check the use of this method.
1931 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1932 return ExprError();
1933 }
1934 // If we found a getter then this may be a valid dot-reference, we
1935 // will look for the matching setter, in case it is needed.
1936 Selector SetterSel =
1937 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1938 PP.getSelectorTable(), Member);
1939 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1940 if (!Setter) {
1941 // If this reference is in an @implementation, also check for 'private'
1942 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001943 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001944 }
1945 // Look through local category implementations associated with the class.
1946 if (!Setter)
1947 Setter = IFace->getCategoryClassMethod(SetterSel);
1948
1949 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1950 return ExprError();
1951
1952 if (Getter || Setter) {
1953 QualType PType;
1954
1955 if (Getter)
1956 PType = Getter->getResultType();
1957 else
1958 // Get the expression type from Setter's incoming parameter.
1959 PType = (*(Setter->param_end() -1))->getType();
1960 // FIXME: we must check that the setter has property type.
1961 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1962 PType,
1963 Setter, MemberLoc, BaseExpr));
1964 }
1965 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1966 << MemberName << BaseType);
1967 }
1968 }
1969
1970 if (BaseType->isObjCClassType() &&
1971 BaseType != Context.ObjCClassRedefinitionType) {
1972 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001973 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001974 }
1975
Chris Lattner68a057b2008-07-21 04:36:39 +00001976 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1977 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00001979 if (BaseType->isDependentType()) {
1980 NestedNameSpecifier *Qualifier = 0;
1981 if (SS) {
1982 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1983 if (!FirstQualifierInScope)
1984 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1985 }
Mike Stump1eb44332009-09-09 15:08:12 +00001986
John McCall865d4472009-11-19 22:55:06 +00001987 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001988 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00001989 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001990 FirstQualifierInScope,
1991 MemberName,
1992 MemberLoc,
1993 HasExplicitTemplateArgs,
1994 LAngleLoc,
1995 ExplicitTemplateArgs,
1996 NumExplicitTemplateArgs,
1997 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00001998 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001999 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002000 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002001 else if (BaseType->isObjCObjectPointerType())
2002 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002003 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002004 return ExprError(Diag(MemberLoc,
2005 diag::err_typecheck_member_reference_arrow)
2006 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002007 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002008 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002009 // (so we'll report an error for)
2010 // T* t;
2011 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002012 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002013 // In Obj-C++, however, the above expression is valid, since it could be
2014 // accessing the 'f' property if T is an Obj-C interface. The extra check
2015 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002016 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002017
Mike Stump1eb44332009-09-09 15:08:12 +00002018 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002019 !PT->getPointeeType()->isRecordType())) {
2020 NestedNameSpecifier *Qualifier = 0;
2021 if (SS) {
2022 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2023 if (!FirstQualifierInScope)
2024 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
John McCall865d4472009-11-19 22:55:06 +00002027 return Owned(CXXDependentScopeMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002028 BaseExpr, false,
2029 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002030 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002031 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002032 FirstQualifierInScope,
2033 MemberName,
2034 MemberLoc,
2035 HasExplicitTemplateArgs,
2036 LAngleLoc,
2037 ExplicitTemplateArgs,
2038 NumExplicitTemplateArgs,
2039 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002040 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002041 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002042
Chris Lattner68a057b2008-07-21 04:36:39 +00002043 // Handle field access to simple records. This also handles access to fields
2044 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002045 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002046 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002047 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002048 PDiag(diag::err_typecheck_incomplete_tag)
2049 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002050 return ExprError();
2051
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002052 DeclContext *DC = RDecl;
2053 if (SS && SS->isSet()) {
2054 // If the member name was a qualified-id, look into the
2055 // nested-name-specifier.
2056 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00002057
2058 if (!isa<TypeDecl>(DC)) {
2059 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2060 << DC << SS->getRange();
2061 return ExprError();
2062 }
Mike Stump1eb44332009-09-09 15:08:12 +00002063
2064 // FIXME: If DC is not computable, we should build a
John McCall865d4472009-11-19 22:55:06 +00002065 // CXXDependentScopeMemberExpr.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002066 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2067 }
2068
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002069 // The record definition is complete, now make sure the member is valid.
John McCalla24dc2e2009-11-17 02:14:36 +00002070 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
2071 LookupQualifiedName(Result, DC);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002072
John McCallf36e02d2009-10-09 21:13:30 +00002073 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00002074 return ExprError(Diag(MemberLoc, diag::err_no_member)
2075 << MemberName << DC << BaseExpr->getSourceRange());
John McCalla24dc2e2009-11-17 02:14:36 +00002076 if (Result.isAmbiguous())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002077 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002078
John McCallf36e02d2009-10-09 21:13:30 +00002079 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2080
Douglas Gregora38c6872009-09-03 16:14:30 +00002081 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00002082 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002083 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002084 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002085 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00002086 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregora38c6872009-09-03 16:14:30 +00002088 if (BaseTypeCanon != MemberTypeCanon &&
2089 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2090 return ExprError(Diag(SS->getBeginLoc(),
2091 diag::err_not_direct_base_or_virtual)
2092 << MemberTypeCanon << BaseTypeCanon);
2093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Chris Lattner56cd21b2009-02-13 22:08:30 +00002095 // If the decl being referenced had an error, return an error for this
2096 // sub-expr without emitting another error, in order to avoid cascading
2097 // error cases.
2098 if (MemberDecl->isInvalidDecl())
2099 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002100
Anders Carlsson0f728562009-09-10 20:48:14 +00002101 bool ShouldCheckUse = true;
2102 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2103 // Don't diagnose the use of a virtual member function unless it's
2104 // explicitly qualified.
2105 if (MD->isVirtual() && (!SS || !SS->isSet()))
2106 ShouldCheckUse = false;
2107 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002108
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002109 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00002110 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002111 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002112
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002113 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002114 // We may have found a field within an anonymous union or struct
2115 // (C++ [class.union]).
2116 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002117 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002118 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002119
Douglas Gregor86f19402008-12-20 23:49:58 +00002120 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002121 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002122 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002123 MemberType = Ref->getPointeeType();
2124 else {
John McCall0953e762009-09-24 19:53:00 +00002125 Qualifiers BaseQuals = BaseType.getQualifiers();
2126 BaseQuals.removeObjCGCAttr();
2127 if (FD->isMutable()) BaseQuals.removeConst();
2128
2129 Qualifiers MemberQuals
2130 = Context.getCanonicalType(MemberType).getQualifiers();
2131
2132 Qualifiers Combined = BaseQuals + MemberQuals;
2133 if (Combined != MemberQuals)
2134 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002135 }
Eli Friedman51019072008-02-06 22:48:16 +00002136
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002137 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002138 if (PerformObjectMemberConversion(BaseExpr, FD))
2139 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002140 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002141 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002142 }
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002144 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2145 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002146 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2147 Var, MemberLoc,
2148 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002149 }
2150 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2151 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002152 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2153 MemberFn, MemberLoc,
2154 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002155 }
Mike Stump1eb44332009-09-09 15:08:12 +00002156 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002157 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2158 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002160 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002161 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2162 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002163 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002164 FunTmpl, MemberLoc, true,
2165 LAngleLoc, ExplicitTemplateArgs,
2166 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002167 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002169 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2170 FunTmpl, MemberLoc,
2171 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002172 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002173 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002174 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2175 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002176 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2177 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002178 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002179 Ovl, MemberLoc, true,
2180 LAngleLoc, ExplicitTemplateArgs,
2181 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002182 Context.OverloadTy));
2183
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002184 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2185 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002186 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002187 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2188 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002189 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2190 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002191 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002192 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002193 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002194 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002195
Douglas Gregor86f19402008-12-20 23:49:58 +00002196 // We found a declaration kind that we didn't expect. This is a
2197 // generic error message that tells the user that she can't refer
2198 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002199 return ExprError(Diag(MemberLoc,
2200 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002201 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002202 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002203
Douglas Gregora71d8192009-09-04 17:36:40 +00002204 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2205 // into a record type was handled above, any destructor we see here is a
2206 // pseudo-destructor.
2207 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2208 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002209 // The left hand side of the dot operator shall be of scalar type. The
2210 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002211 // type.
2212 if (!BaseType->isScalarType())
2213 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2214 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Douglas Gregora71d8192009-09-04 17:36:40 +00002216 // [...] The type designated by the pseudo-destructor-name shall be the
2217 // same as the object type.
2218 if (!MemberName.getCXXNameType()->isDependentType() &&
2219 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2220 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2221 << BaseType << MemberName.getCXXNameType()
2222 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002223
2224 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002225 // the form
2226 //
Mike Stump1eb44332009-09-09 15:08:12 +00002227 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2228 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002229 // shall designate the same scalar type.
2230 //
2231 // FIXME: DPG can't see any way to trigger this particular clause, so it
2232 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Douglas Gregora71d8192009-09-04 17:36:40 +00002234 // FIXME: We've lost the precise spelling of the type by going through
2235 // DeclarationName. Can we do better?
2236 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002237 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002238 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002239 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002240 SS? SS->getRange() : SourceRange(),
2241 MemberName.getCXXNameType(),
2242 MemberLoc));
2243 }
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Chris Lattnera38e6b12008-07-21 04:59:05 +00002245 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2246 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002247 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2248 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002249 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002250 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002251 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002252 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002253 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2254
Steve Naroffc70e8d92009-07-16 00:25:06 +00002255 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2256 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002257 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Steve Naroffc70e8d92009-07-16 00:25:06 +00002259 if (IV) {
2260 // If the decl being referenced had an error, return an error for this
2261 // sub-expr without emitting another error, in order to avoid cascading
2262 // error cases.
2263 if (IV->isInvalidDecl())
2264 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002265
Steve Naroffc70e8d92009-07-16 00:25:06 +00002266 // Check whether we can reference this field.
2267 if (DiagnoseUseOfDecl(IV, MemberLoc))
2268 return ExprError();
2269 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2270 IV->getAccessControl() != ObjCIvarDecl::Package) {
2271 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2272 if (ObjCMethodDecl *MD = getCurMethodDecl())
2273 ClassOfMethodDecl = MD->getClassInterface();
2274 else if (ObjCImpDecl && getCurFunctionDecl()) {
2275 // Case of a c-function declared inside an objc implementation.
2276 // FIXME: For a c-style function nested inside an objc implementation
2277 // class, there is no implementation context available, so we pass
2278 // down the context as argument to this routine. Ideally, this context
2279 // need be passed down in the AST node and somehow calculated from the
2280 // AST for a function decl.
2281 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002282 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002283 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2284 ClassOfMethodDecl = IMPD->getClassInterface();
2285 else if (ObjCCategoryImplDecl* CatImplClass =
2286 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2287 ClassOfMethodDecl = CatImplClass->getClassInterface();
2288 }
Mike Stump1eb44332009-09-09 15:08:12 +00002289
2290 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2291 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002292 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002293 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002294 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002295 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2296 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002297 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002298 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002299 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002300
2301 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2302 MemberLoc, BaseExpr,
2303 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002304 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002305 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002306 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002307 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002308 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002309 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002310 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002311 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002312 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002313 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002314 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Steve Naroff14108da2009-07-10 23:34:53 +00002316 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002317 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002318 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2319 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2320 // Check the use of this declaration
2321 if (DiagnoseUseOfDecl(PD, MemberLoc))
2322 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Steve Naroff14108da2009-07-10 23:34:53 +00002324 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2325 MemberLoc, BaseExpr));
2326 }
2327 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2328 // Check the use of this method.
2329 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2330 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Steve Naroff14108da2009-07-10 23:34:53 +00002332 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002333 OMD->getResultType(),
2334 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002335 NULL, 0));
2336 }
2337 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002338
Steve Naroff14108da2009-07-10 23:34:53 +00002339 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002340 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002341 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002342 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2343 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002344 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002345 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002346 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2347 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2348 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002349 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Daniel Dunbar2307d312008-09-03 01:05:41 +00002351 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002352 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002353 // Check whether we can reference this property.
2354 if (DiagnoseUseOfDecl(PD, MemberLoc))
2355 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002356 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002357 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002358 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002359 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2360 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002361 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002362 MemberLoc, BaseExpr));
2363 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002364 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002365 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2366 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002367 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002368 // Check whether we can reference this property.
2369 if (DiagnoseUseOfDecl(PD, MemberLoc))
2370 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002371
Steve Naroff6ece14c2009-01-21 00:14:39 +00002372 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002373 MemberLoc, BaseExpr));
2374 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002375 // If that failed, look for an "implicit" property by seeing if the nullary
2376 // selector is implemented.
2377
2378 // FIXME: The logic for looking up nullary and unary selectors should be
2379 // shared with the code in ActOnInstanceMessage.
2380
Anders Carlsson8f28f992009-08-26 18:25:21 +00002381 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002382 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002383
Daniel Dunbar2307d312008-09-03 01:05:41 +00002384 // If this reference is in an @implementation, check for 'private' methods.
2385 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002386 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002387
Steve Naroff7692ed62008-10-22 19:16:27 +00002388 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002389 if (!Getter)
2390 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002391 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002392 // Check if we can reference this property.
2393 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2394 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002395 }
2396 // If we found a getter then this may be a valid dot-reference, we
2397 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002398 Selector SetterSel =
2399 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002400 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002401 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002402 if (!Setter) {
2403 // If this reference is in an @implementation, also check for 'private'
2404 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002405 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002406 }
2407 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002408 if (!Setter)
2409 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002410
Steve Naroff1ca66942009-03-11 13:48:17 +00002411 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2412 return ExprError();
2413
2414 if (Getter || Setter) {
2415 QualType PType;
2416
2417 if (Getter)
2418 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002419 else
2420 // Get the expression type from Setter's incoming parameter.
2421 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002422 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002423 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002424 Setter, MemberLoc, BaseExpr));
2425 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002426 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002427 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002428 }
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Steve Narofff242b1b2009-07-24 17:54:45 +00002430 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002431 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002432 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002433 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002434 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2435 Context.getObjCIdType()));
2436
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002437 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002438 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002439 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002440 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2441 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002442 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002443 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002444 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002445 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002446
Douglas Gregor214f31a2009-03-27 06:00:30 +00002447 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2448 << BaseType << BaseExpr->getSourceRange();
2449
Douglas Gregor214f31a2009-03-27 06:00:30 +00002450 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002451}
2452
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002453Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2454 SourceLocation OpLoc,
2455 tok::TokenKind OpKind,
2456 const CXXScopeSpec &SS,
2457 UnqualifiedId &Member,
2458 DeclPtrTy ObjCImpDecl,
2459 bool HasTrailingLParen) {
2460 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2461 TemplateName Template
2462 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2463
2464 // FIXME: We're going to end up looking up the template based on its name,
2465 // twice!
2466 DeclarationName Name;
2467 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2468 Name = ActualTemplate->getDeclName();
2469 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2470 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002471 else {
2472 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2473 if (DTN->isIdentifier())
2474 Name = DTN->getIdentifier();
2475 else
2476 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2477 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002478
2479 // Translate the parser's template argument list in our AST format.
2480 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2481 Member.TemplateId->getTemplateArgs(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002482 Member.TemplateId->NumArgs);
2483
2484 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2485 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002486 TemplateArgs);
2487 TemplateArgsPtr.release();
2488
2489 // Do we have the save the actual template name? We might need it...
2490 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2491 Member.TemplateId->TemplateNameLoc,
2492 Name, true, Member.TemplateId->LAngleLoc,
2493 TemplateArgs.data(), TemplateArgs.size(),
2494 Member.TemplateId->RAngleLoc, DeclPtrTy(),
2495 &SS);
2496 }
2497
2498 // FIXME: We lose a lot of source information by mapping directly to the
2499 // DeclarationName.
2500 OwningExprResult Result
2501 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2502 Member.getSourceRange().getBegin(),
2503 GetNameFromUnqualifiedId(Member),
2504 ObjCImpDecl, &SS);
2505
2506 if (Result.isInvalid() || HasTrailingLParen ||
2507 Member.getKind() != UnqualifiedId::IK_DestructorName)
2508 return move(Result);
2509
2510 // The only way a reference to a destructor can be used is to
2511 // immediately call them. Since the next token is not a '(', produce a
2512 // diagnostic and build the call now.
2513 Expr *E = (Expr *)Result.get();
2514 SourceLocation ExpectedLParenLoc
2515 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2516 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2517 << isa<CXXPseudoDestructorExpr>(E)
2518 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2519
2520 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2521 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002522}
2523
Anders Carlsson56c5e332009-08-25 03:49:14 +00002524Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2525 FunctionDecl *FD,
2526 ParmVarDecl *Param) {
2527 if (Param->hasUnparsedDefaultArg()) {
2528 Diag (CallLoc,
2529 diag::err_use_of_default_argument_to_function_declared_later) <<
2530 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002531 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002532 diag::note_default_argument_declared_here);
2533 } else {
2534 if (Param->hasUninstantiatedDefaultArg()) {
2535 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2536
2537 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002538 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002539
Mike Stump1eb44332009-09-09 15:08:12 +00002540 InstantiatingTemplate Inst(*this, CallLoc, Param,
2541 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002542 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002543
John McCallce3ff2b2009-08-25 22:02:44 +00002544 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002545 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002546 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002547
2548 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002549 /*FIXME:EqualLoc*/
2550 UninstExpr->getSourceRange().getBegin()))
2551 return ExprError();
2552 }
Mike Stump1eb44332009-09-09 15:08:12 +00002553
Anders Carlsson56c5e332009-08-25 03:49:14 +00002554 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Anders Carlsson56c5e332009-08-25 03:49:14 +00002556 // If the default expression creates temporaries, we need to
2557 // push them to the current stack of expression temporaries so they'll
2558 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002559 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002560 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002561 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002562 "Can't destroy temporaries in a default argument expr!");
2563 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2564 ExprTemporaries.push_back(E->getTemporary(I));
2565 }
2566 }
2567
2568 // We already type-checked the argument, so we know it works.
2569 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2570}
2571
Douglas Gregor88a35142008-12-22 05:46:06 +00002572/// ConvertArgumentsForCall - Converts the arguments specified in
2573/// Args/NumArgs to the parameter types of the function FDecl with
2574/// function prototype Proto. Call is the call expression itself, and
2575/// Fn is the function expression. For a C++ member function, this
2576/// routine does not attempt to convert the object argument. Returns
2577/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002578bool
2579Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002580 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002581 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002582 Expr **Args, unsigned NumArgs,
2583 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002584 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002585 // assignment, to the types of the corresponding parameter, ...
2586 unsigned NumArgsInProto = Proto->getNumArgs();
2587 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002588 bool Invalid = false;
2589
Douglas Gregor88a35142008-12-22 05:46:06 +00002590 // If too few arguments are available (and we don't have default
2591 // arguments for the remaining parameters), don't make the call.
2592 if (NumArgs < NumArgsInProto) {
2593 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2594 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2595 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2596 // Use default arguments for missing arguments
2597 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002598 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002599 }
2600
2601 // If too many are passed and not variadic, error on the extras and drop
2602 // them.
2603 if (NumArgs > NumArgsInProto) {
2604 if (!Proto->isVariadic()) {
2605 Diag(Args[NumArgsInProto]->getLocStart(),
2606 diag::err_typecheck_call_too_many_args)
2607 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2608 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2609 Args[NumArgs-1]->getLocEnd());
2610 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002611 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002612 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002613 }
2614 NumArgsToCheck = NumArgsInProto;
2615 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002616
Douglas Gregor88a35142008-12-22 05:46:06 +00002617 // Continue to check argument types (even if we have too few/many args).
2618 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2619 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002620
Douglas Gregor88a35142008-12-22 05:46:06 +00002621 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002622 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002623 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002624
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002625 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2626 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002627 PDiag(diag::err_call_incomplete_argument)
2628 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002629 return true;
2630
Douglas Gregor61366e92008-12-24 00:01:03 +00002631 // Pass the argument.
2632 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2633 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00002634
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00002635 if (!ProtoArgType->isReferenceType())
2636 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002637 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002638 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002639
2640 OwningExprResult ArgExpr =
Anders Carlsson56c5e332009-08-25 03:49:14 +00002641 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2642 FDecl, Param);
2643 if (ArgExpr.isInvalid())
2644 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Anders Carlsson56c5e332009-08-25 03:49:14 +00002646 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002647 }
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Douglas Gregor88a35142008-12-22 05:46:06 +00002649 Call->setArg(i, Arg);
2650 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002651
Douglas Gregor88a35142008-12-22 05:46:06 +00002652 // If this is a variadic call, handle args passed through "...".
2653 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002654 VariadicCallType CallType = VariadicFunction;
2655 if (Fn->getType()->isBlockPointerType())
2656 CallType = VariadicBlock; // Block
2657 else if (isa<MemberExpr>(Fn))
2658 CallType = VariadicMethod;
2659
Douglas Gregor88a35142008-12-22 05:46:06 +00002660 // Promote the arguments (C99 6.5.2.2p7).
Eli Friedman3e42ffd2009-11-14 04:43:10 +00002661 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002662 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002663 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002664 Call->setArg(i, Arg);
2665 }
2666 }
2667
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002668 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002669}
2670
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002671/// \brief "Deconstruct" the function argument of a call expression to find
2672/// the underlying declaration (if any), the name of the called function,
2673/// whether argument-dependent lookup is available, whether it has explicit
2674/// template arguments, etc.
2675void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00002676 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002677 DeclarationName &Name,
2678 NestedNameSpecifier *&Qualifier,
2679 SourceRange &QualifierRange,
2680 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00002681 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002682 bool &HasExplicitTemplateArguments,
John McCall833ca992009-10-29 08:12:44 +00002683 const TemplateArgumentLoc *&ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002684 unsigned &NumExplicitTemplateArgs) {
2685 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002686 Name = DeclarationName();
2687 Qualifier = 0;
2688 QualifierRange = SourceRange();
2689 ArgumentDependentLookup = getLangOptions().CPlusPlus;
John McCall7453ed42009-11-22 00:44:51 +00002690 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002691 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00002692
2693 // Most of the explicit tracking of ArgumentDependentLookup in this
2694 // function can disappear when we handle unresolved
2695 // TemplateIdRefExprs properly.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002696
2697 // If we're directly calling a function, get the appropriate declaration.
2698 // Also, in C++, keep track of whether we should perform argument-dependent
2699 // lookup and whether there were any explicitly-specified template arguments.
2700 while (true) {
2701 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2702 FnExpr = IcExpr->getSubExpr();
2703 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2704 // Parentheses around a function disable ADL
2705 // (C++0x [basic.lookup.argdep]p1).
2706 ArgumentDependentLookup = false;
2707 FnExpr = PExpr->getSubExpr();
2708 } else if (isa<UnaryOperator>(FnExpr) &&
2709 cast<UnaryOperator>(FnExpr)->getOpcode()
2710 == UnaryOperator::AddrOf) {
2711 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002712 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00002713 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
2714 ArgumentDependentLookup = false;
2715 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00002716 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002717 break;
John McCallba135432009-11-21 08:51:07 +00002718 } else if (UnresolvedLookupExpr *UnresLookup
2719 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
2720 Name = UnresLookup->getName();
2721 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
2722 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00002723 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00002724 if ((Qualifier = UnresLookup->getQualifier()))
2725 QualifierRange = UnresLookup->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002726 break;
2727 } else if (TemplateIdRefExpr *TemplateIdRef
2728 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00002729 if (NamedDecl *Function
John McCall7453ed42009-11-22 00:44:51 +00002730 = TemplateIdRef->getTemplateName().getAsTemplateDecl()) {
2731 Name = Function->getDeclName();
John McCallba135432009-11-21 08:51:07 +00002732 Fns.push_back(Function);
John McCall7453ed42009-11-22 00:44:51 +00002733 }
John McCallba135432009-11-21 08:51:07 +00002734 else {
2735 OverloadedFunctionDecl *Overload
2736 = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
John McCall7453ed42009-11-22 00:44:51 +00002737 Name = Overload->getDeclName();
John McCallba135432009-11-21 08:51:07 +00002738 Fns.append(Overload->function_begin(), Overload->function_end());
2739 }
John McCall7453ed42009-11-22 00:44:51 +00002740 Overloaded = true;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002741 HasExplicitTemplateArguments = true;
2742 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2743 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2744
2745 // C++ [temp.arg.explicit]p6:
2746 // [Note: For simple function names, argument dependent lookup (3.4.2)
2747 // applies even when the function name is not visible within the
2748 // scope of the call. This is because the call still has the syntactic
2749 // form of a function call (3.4.1). But when a function template with
2750 // explicit template arguments is used, the call does not have the
2751 // correct syntactic form unless there is a function template with
2752 // that name visible at the point of the call. If no such name is
2753 // visible, the call is not syntactically well-formed and
2754 // argument-dependent lookup does not apply. If some such name is
2755 // visible, argument dependent lookup applies and additional function
2756 // templates may be found in other namespaces.
2757 //
2758 // The summary of this paragraph is that, if we get to this point and the
2759 // template-id was not a qualified name, then argument-dependent lookup
2760 // is still possible.
2761 if ((Qualifier = TemplateIdRef->getQualifier())) {
2762 ArgumentDependentLookup = false;
2763 QualifierRange = TemplateIdRef->getQualifierRange();
2764 }
2765 break;
2766 } else {
2767 // Any kind of name that does not refer to a declaration (or
2768 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2769 ArgumentDependentLookup = false;
2770 break;
2771 }
2772 }
2773}
2774
Steve Narofff69936d2007-09-16 03:34:24 +00002775/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002776/// This provides the location of the left/right parens and a list of comma
2777/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002778Action::OwningExprResult
2779Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2780 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002781 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002782 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002783
2784 // Since this might be a postfix expression, get rid of ParenListExprs.
2785 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002787 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002788 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002789 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Douglas Gregor88a35142008-12-22 05:46:06 +00002791 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002792 // If this is a pseudo-destructor expression, build the call immediately.
2793 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2794 if (NumArgs > 0) {
2795 // Pseudo-destructor calls should not have any arguments.
2796 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2797 << CodeModificationHint::CreateRemoval(
2798 SourceRange(Args[0]->getLocStart(),
2799 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Douglas Gregora71d8192009-09-04 17:36:40 +00002801 for (unsigned I = 0; I != NumArgs; ++I)
2802 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Douglas Gregora71d8192009-09-04 17:36:40 +00002804 NumArgs = 0;
2805 }
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Douglas Gregora71d8192009-09-04 17:36:40 +00002807 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2808 RParenLoc));
2809 }
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Douglas Gregor17330012009-02-04 15:01:18 +00002811 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002812 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002813 // FIXME: Will need to cache the results of name lookup (including ADL) in
2814 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002815 bool Dependent = false;
2816 if (Fn->isTypeDependent())
2817 Dependent = true;
2818 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2819 Dependent = true;
2820
2821 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002822 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002823 Context.DependentTy, RParenLoc));
2824
2825 // Determine whether this is a call to an object (C++ [over.call.object]).
2826 if (Fn->getType()->isRecordType())
2827 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2828 CommaLocs, RParenLoc));
2829
Douglas Gregorfa047642009-02-04 00:32:51 +00002830 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002831 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2832 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2833 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2834 isa<CXXMethodDecl>(MemDecl) ||
2835 (isa<FunctionTemplateDecl>(MemDecl) &&
2836 isa<CXXMethodDecl>(
2837 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002838 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2839 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002840 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002841
2842 // Determine whether this is a call to a pointer-to-member function.
2843 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2844 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2845 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002846 if (const FunctionProtoType *FPT =
2847 dyn_cast<FunctionProtoType>(BO->getType())) {
2848 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002849
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002850 ExprOwningPtr<CXXMemberCallExpr>
2851 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2852 NumArgs, ResultTy,
2853 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002854
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002855 if (CheckCallReturnType(FPT->getResultType(),
2856 BO->getRHS()->getSourceRange().getBegin(),
2857 TheCall.get(), 0))
2858 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002859
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002860 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2861 RParenLoc))
2862 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002863
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002864 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2865 }
2866 return ExprError(Diag(Fn->getLocStart(),
2867 diag::err_typecheck_call_not_function)
2868 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002869 }
2870 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002871 }
2872
Douglas Gregorfa047642009-02-04 00:32:51 +00002873 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002874 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002875 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00002876 llvm::SmallVector<NamedDecl*,8> Fns;
2877 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00002878 bool Overloaded;
2879 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002880 bool HasExplicitTemplateArgs = 0;
John McCall833ca992009-10-29 08:12:44 +00002881 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002882 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002883 NestedNameSpecifier *Qualifier = 0;
2884 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00002885 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00002886 ADL, Overloaded, HasExplicitTemplateArgs,
2887 ExplicitTemplateArgs, NumExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002888
John McCall7453ed42009-11-22 00:44:51 +00002889 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
2890 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00002891
John McCall7453ed42009-11-22 00:44:51 +00002892 if (Overloaded || ADL) {
2893#ifndef NDEBUG
2894 if (ADL) {
2895 // To do ADL, we must have found an unqualified name.
2896 assert(UnqualifiedName && "found no unqualified name for ADL");
2897
2898 // We don't perform ADL for implicit declarations of builtins.
2899 // Verify that this was correctly set up.
2900 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
2901 FDecl->getBuiltinID() && FDecl->isImplicit())
2902 assert(0 && "performing ADL for builtin");
2903
2904 // We don't perform ADL in C.
2905 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
2906 }
2907
2908 if (Overloaded) {
2909 // To be overloaded, we must either have multiple functions or
2910 // at least one function template (which is effectively an
2911 // infinite set of functions).
2912 assert((Fns.size() > 1 ||
2913 (Fns.size() == 1 &&
2914 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
2915 && "unrecognized overload situation");
2916 }
2917#endif
2918
2919 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
2920 HasExplicitTemplateArgs,
2921 ExplicitTemplateArgs,
2922 NumExplicitTemplateArgs,
2923 LParenLoc, Args, NumArgs, CommaLocs,
2924 RParenLoc, ADL);
2925 if (!FDecl)
2926 return ExprError();
2927
2928 Fn = FixOverloadedFunctionReference(Fn, FDecl);
2929
2930 NDecl = FDecl;
2931 } else {
2932 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
2933 if (Fns.empty())
2934 NDecl = FDecl = 0;
2935 else {
2936 NDecl = Fns[0];
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002937 FDecl = dyn_cast<FunctionDecl>(NDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002938 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002939 }
Chris Lattner04421082008-04-08 04:40:51 +00002940
2941 // Promote the function operand.
2942 UsualUnaryConversions(Fn);
2943
Chris Lattner925e60d2007-12-28 05:29:59 +00002944 // Make the call expr early, before semantic checks. This guarantees cleanup
2945 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002946 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2947 Args, NumArgs,
2948 Context.BoolTy,
2949 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002950
Steve Naroffdd972f22008-09-05 22:11:13 +00002951 const FunctionType *FuncT;
2952 if (!Fn->getType()->isBlockPointerType()) {
2953 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2954 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002955 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002956 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002957 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2958 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002959 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002960 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002961 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002962 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002963 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002964 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002965 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2966 << Fn->getType() << Fn->getSourceRange());
2967
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002968 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002969 if (CheckCallReturnType(FuncT->getResultType(),
2970 Fn->getSourceRange().getBegin(), TheCall.get(),
2971 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002972 return ExprError();
2973
Chris Lattner925e60d2007-12-28 05:29:59 +00002974 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002975 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002976
Douglas Gregor72564e72009-02-26 23:50:07 +00002977 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002978 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002979 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002980 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002981 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002982 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002983
Douglas Gregor74734d52009-04-02 15:37:10 +00002984 if (FDecl) {
2985 // Check if we have too few/too many template arguments, based
2986 // on our knowledge of the function definition.
2987 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002988 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002989 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002990 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002991 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2992 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2993 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2994 }
2995 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002996 }
2997
Steve Naroffb291ab62007-08-28 23:30:39 +00002998 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002999 for (unsigned i = 0; i != NumArgs; i++) {
3000 Expr *Arg = Args[i];
3001 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003002 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3003 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003004 PDiag(diag::err_call_incomplete_argument)
3005 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003006 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003007 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003008 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003009 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003010
Douglas Gregor88a35142008-12-22 05:46:06 +00003011 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3012 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003013 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3014 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003015
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003016 // Check for sentinels
3017 if (NDecl)
3018 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Chris Lattner59907c42007-08-10 20:18:51 +00003020 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003021 if (FDecl) {
3022 if (CheckFunctionCall(FDecl, TheCall.get()))
3023 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003025 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003026 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3027 } else if (NDecl) {
3028 if (CheckBlockCall(NDecl, TheCall.get()))
3029 return ExprError();
3030 }
Chris Lattner59907c42007-08-10 20:18:51 +00003031
Anders Carlssonec74c592009-08-16 03:06:32 +00003032 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003033}
3034
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003035Action::OwningExprResult
3036Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3037 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003038 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003039 //FIXME: Preserve type source info.
3040 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003041 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003042 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003043 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003044
Eli Friedman6223c222008-05-20 05:22:08 +00003045 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003046 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003047 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3048 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003049 } else if (!literalType->isDependentType() &&
3050 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003051 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003052 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003053 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003054 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003055
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003056 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003057 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003058 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003059
Chris Lattner371f2582008-12-04 23:50:19 +00003060 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003061 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003062 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003063 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003064 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003065 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003066 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003067 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003068}
3069
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003070Action::OwningExprResult
3071Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003072 SourceLocation RBraceLoc) {
3073 unsigned NumInit = initlist.size();
3074 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003075
Steve Naroff08d92e42007-09-15 18:49:24 +00003076 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003077 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003078
Mike Stumpeed9cac2009-02-19 03:04:26 +00003079 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003080 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003081 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003082 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003083}
3084
Anders Carlsson82debc72009-10-18 18:12:03 +00003085static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3086 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003087 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003088 return CastExpr::CK_NoOp;
3089
3090 if (SrcTy->hasPointerRepresentation()) {
3091 if (DestTy->hasPointerRepresentation())
3092 return CastExpr::CK_BitCast;
3093 if (DestTy->isIntegerType())
3094 return CastExpr::CK_PointerToIntegral;
3095 }
3096
3097 if (SrcTy->isIntegerType()) {
3098 if (DestTy->isIntegerType())
3099 return CastExpr::CK_IntegralCast;
3100 if (DestTy->hasPointerRepresentation())
3101 return CastExpr::CK_IntegralToPointer;
3102 if (DestTy->isRealFloatingType())
3103 return CastExpr::CK_IntegralToFloating;
3104 }
3105
3106 if (SrcTy->isRealFloatingType()) {
3107 if (DestTy->isRealFloatingType())
3108 return CastExpr::CK_FloatingCast;
3109 if (DestTy->isIntegerType())
3110 return CastExpr::CK_FloatingToIntegral;
3111 }
3112
3113 // FIXME: Assert here.
3114 // assert(false && "Unhandled cast combination!");
3115 return CastExpr::CK_Unknown;
3116}
3117
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003118/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003119bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003120 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003121 CXXMethodDecl *& ConversionDecl,
3122 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003123 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003124 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3125 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003126
Eli Friedman199ea952009-08-15 19:02:19 +00003127 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003128
3129 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3130 // type needs to be scalar.
3131 if (castType->isVoidType()) {
3132 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003133 Kind = CastExpr::CK_ToVoid;
3134 return false;
3135 }
3136
3137 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003138 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003139 (castType->isStructureType() || castType->isUnionType())) {
3140 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003141 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003142 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3143 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003144 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003145 return false;
3146 }
3147
3148 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003149 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003150 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003151 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003152 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003153 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003154 if (Context.hasSameUnqualifiedType(Field->getType(),
3155 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003156 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3157 << castExpr->getSourceRange();
3158 break;
3159 }
3160 }
3161 if (Field == FieldEnd)
3162 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3163 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003164 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003165 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003166 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003167
3168 // Reject any other conversions to non-scalar types.
3169 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3170 << castType << castExpr->getSourceRange();
3171 }
3172
3173 if (!castExpr->getType()->isScalarType() &&
3174 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003175 return Diag(castExpr->getLocStart(),
3176 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003177 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003178 }
3179
Anders Carlsson16a89042009-10-16 05:23:41 +00003180 if (castType->isExtVectorType())
3181 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3182
Anders Carlssonc3516322009-10-16 02:48:28 +00003183 if (castType->isVectorType())
3184 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3185 if (castExpr->getType()->isVectorType())
3186 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3187
3188 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003189 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003190
Anders Carlsson16a89042009-10-16 05:23:41 +00003191 if (isa<ObjCSelectorExpr>(castExpr))
3192 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3193
Anders Carlssonc3516322009-10-16 02:48:28 +00003194 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003195 QualType castExprType = castExpr->getType();
3196 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3197 return Diag(castExpr->getLocStart(),
3198 diag::err_cast_pointer_from_non_pointer_int)
3199 << castExprType << castExpr->getSourceRange();
3200 } else if (!castExpr->getType()->isArithmeticType()) {
3201 if (!castType->isIntegralType() && castType->isArithmeticType())
3202 return Diag(castExpr->getLocStart(),
3203 diag::err_cast_pointer_to_non_pointer_int)
3204 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003205 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003206
3207 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003208 return false;
3209}
3210
Anders Carlssonc3516322009-10-16 02:48:28 +00003211bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3212 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003213 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003214
Anders Carlssona64db8f2007-11-27 05:51:55 +00003215 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003216 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003217 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003218 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003219 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003220 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003221 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003222 } else
3223 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003224 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003225 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003226
Anders Carlssonc3516322009-10-16 02:48:28 +00003227 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003228 return false;
3229}
3230
Anders Carlsson16a89042009-10-16 05:23:41 +00003231bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3232 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003233 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003234
3235 QualType SrcTy = CastExpr->getType();
3236
Nate Begeman9b10da62009-06-27 22:05:55 +00003237 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3238 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003239 if (SrcTy->isVectorType()) {
3240 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3241 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3242 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003243 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003244 return false;
3245 }
3246
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003247 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003248 // conversion will take place first from scalar to elt type, and then
3249 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003250 if (SrcTy->isPointerType())
3251 return Diag(R.getBegin(),
3252 diag::err_invalid_conversion_between_vector_and_scalar)
3253 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003254
3255 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3256 ImpCastExprToType(CastExpr, DestElemTy,
3257 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003258
3259 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003260 return false;
3261}
3262
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003263Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003264Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003265 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003266 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003268 assert((Ty != 0) && (Op.get() != 0) &&
3269 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003270
Nate Begeman2ef13e52009-08-10 23:49:36 +00003271 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003272 //FIXME: Preserve type source info.
3273 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Nate Begeman2ef13e52009-08-10 23:49:36 +00003275 // If the Expr being casted is a ParenListExpr, handle it specially.
3276 if (isa<ParenListExpr>(castExpr))
3277 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003278 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003279 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003280 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003281 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003282
3283 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003284 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003285 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003286
Anders Carlsson0aebc812009-09-09 21:33:21 +00003287 if (CastArg.isInvalid())
3288 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003289
Anders Carlsson0aebc812009-09-09 21:33:21 +00003290 castExpr = CastArg.takeAs<Expr>();
3291 } else {
3292 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003293 }
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003295 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003296 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003297 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003298}
3299
Nate Begeman2ef13e52009-08-10 23:49:36 +00003300/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3301/// of comma binary operators.
3302Action::OwningExprResult
3303Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3304 Expr *expr = EA.takeAs<Expr>();
3305 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3306 if (!E)
3307 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Nate Begeman2ef13e52009-08-10 23:49:36 +00003309 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Nate Begeman2ef13e52009-08-10 23:49:36 +00003311 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3312 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3313 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Nate Begeman2ef13e52009-08-10 23:49:36 +00003315 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3316}
3317
3318Action::OwningExprResult
3319Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3320 SourceLocation RParenLoc, ExprArg Op,
3321 QualType Ty) {
3322 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003323
3324 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003325 // then handle it as such.
3326 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3327 if (PE->getNumExprs() == 0) {
3328 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3329 return ExprError();
3330 }
3331
3332 llvm::SmallVector<Expr *, 8> initExprs;
3333 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3334 initExprs.push_back(PE->getExpr(i));
3335
3336 // FIXME: This means that pretty-printing the final AST will produce curly
3337 // braces instead of the original commas.
3338 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003339 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003340 initExprs.size(), RParenLoc);
3341 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003342 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003343 Owned(E));
3344 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003345 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003346 // sequence of BinOp comma operators.
3347 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3348 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3349 }
3350}
3351
3352Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3353 SourceLocation R,
3354 MultiExprArg Val) {
3355 unsigned nexprs = Val.size();
3356 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3357 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3358 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3359 return Owned(expr);
3360}
3361
Sebastian Redl28507842009-02-26 14:39:58 +00003362/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3363/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003364/// C99 6.5.15
3365QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3366 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003367 // C++ is sufficiently different to merit its own checker.
3368 if (getLangOptions().CPlusPlus)
3369 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3370
John McCallb13c87f2009-11-05 09:23:39 +00003371 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3372
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003373 UsualUnaryConversions(Cond);
3374 UsualUnaryConversions(LHS);
3375 UsualUnaryConversions(RHS);
3376 QualType CondTy = Cond->getType();
3377 QualType LHSTy = LHS->getType();
3378 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003379
Reid Spencer5f016e22007-07-11 17:01:13 +00003380 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003381 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3382 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3383 << CondTy;
3384 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003385 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003386
Chris Lattner70d67a92008-01-06 22:42:25 +00003387 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003388 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3389 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003390
Chris Lattner70d67a92008-01-06 22:42:25 +00003391 // If both operands have arithmetic type, do the usual arithmetic conversions
3392 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003393 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3394 UsualArithmeticConversions(LHS, RHS);
3395 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003396 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003397
Chris Lattner70d67a92008-01-06 22:42:25 +00003398 // If both operands are the same structure or union type, the result is that
3399 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003400 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3401 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003402 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003403 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003404 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003405 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003406 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003407 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003408
Chris Lattner70d67a92008-01-06 22:42:25 +00003409 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003410 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003411 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3412 if (!LHSTy->isVoidType())
3413 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3414 << RHS->getSourceRange();
3415 if (!RHSTy->isVoidType())
3416 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3417 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003418 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3419 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003420 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003421 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003422 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3423 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003424 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003425 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003426 // promote the null to a pointer.
3427 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003428 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003429 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003430 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003431 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003432 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003433 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003434 }
David Chisnall0f436562009-08-17 16:35:33 +00003435 // Handle things like Class and struct objc_class*. Here we case the result
3436 // to the pseudo-builtin, because that will be implicitly cast back to the
3437 // redefinition type if an attempt is made to access its fields.
3438 if (LHSTy->isObjCClassType() &&
3439 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003440 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003441 return LHSTy;
3442 }
3443 if (RHSTy->isObjCClassType() &&
3444 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003445 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003446 return RHSTy;
3447 }
3448 // And the same for struct objc_object* / id
3449 if (LHSTy->isObjCIdType() &&
3450 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003451 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003452 return LHSTy;
3453 }
3454 if (RHSTy->isObjCIdType() &&
3455 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003456 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003457 return RHSTy;
3458 }
Steve Naroff7154a772009-07-01 14:36:47 +00003459 // Handle block pointer types.
3460 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3461 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3462 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3463 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003464 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3465 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003466 return destType;
3467 }
3468 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3469 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3470 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003471 }
Steve Naroff7154a772009-07-01 14:36:47 +00003472 // We have 2 block pointer types.
3473 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3474 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003475 return LHSTy;
3476 }
Steve Naroff7154a772009-07-01 14:36:47 +00003477 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003478 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3479 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003480
Steve Naroff7154a772009-07-01 14:36:47 +00003481 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3482 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003483 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3484 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3485 // In this situation, we assume void* type. No especially good
3486 // reason, but this is what gcc does, and we do have to pick
3487 // to get a consistent AST.
3488 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003489 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3490 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003491 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003492 }
Steve Naroff7154a772009-07-01 14:36:47 +00003493 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003494 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3495 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003496 return LHSTy;
3497 }
Steve Naroff7154a772009-07-01 14:36:47 +00003498 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003499 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003500
Steve Naroff7154a772009-07-01 14:36:47 +00003501 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3502 // Two identical object pointer types are always compatible.
3503 return LHSTy;
3504 }
John McCall183700f2009-09-21 23:43:11 +00003505 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3506 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003507 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Steve Naroff7154a772009-07-01 14:36:47 +00003509 // If both operands are interfaces and either operand can be
3510 // assigned to the other, use that type as the composite
3511 // type. This allows
3512 // xxx ? (A*) a : (B*) b
3513 // where B is a subclass of A.
3514 //
3515 // Additionally, as for assignment, if either type is 'id'
3516 // allow silent coercion. Finally, if the types are
3517 // incompatible then make sure to use 'id' as the composite
3518 // type so the result is acceptable for sending messages to.
3519
3520 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3521 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003522 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003523 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003524 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003525 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003526 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003527 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003528 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003529 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003530 // GCC allows qualified id and any Objective-C type to devolve to
3531 // id. Currently localizing to here until clear this should be
3532 // part of ObjCQualifiedIdTypesAreCompatible.
3533 compositeType = Context.getObjCIdType();
3534 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003535 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003536 } else if (!(compositeType =
3537 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3538 ;
3539 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003540 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3541 << LHSTy << RHSTy
3542 << LHS->getSourceRange() << RHS->getSourceRange();
3543 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003544 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3545 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003546 return incompatTy;
3547 }
3548 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003549 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3550 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003551 return compositeType;
3552 }
Steve Naroffc715e782009-07-29 15:09:39 +00003553 // Check Objective-C object pointer types and 'void *'
3554 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003555 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003556 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003557 QualType destPointee
3558 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003559 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003560 // Add qualifiers if necessary.
3561 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3562 // Promote to void*.
3563 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003564 return destType;
3565 }
3566 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003567 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003568 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003569 QualType destPointee
3570 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003571 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003572 // Add qualifiers if necessary.
3573 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3574 // Promote to void*.
3575 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003576 return destType;
3577 }
Steve Naroff7154a772009-07-01 14:36:47 +00003578 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3579 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3580 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003581 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3582 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003583
3584 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3585 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3586 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003587 QualType destPointee
3588 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003589 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003590 // Add qualifiers if necessary.
3591 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3592 // Promote to void*.
3593 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003594 return destType;
3595 }
3596 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003597 QualType destPointee
3598 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003599 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003600 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003601 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003602 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003603 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003604 return destType;
3605 }
3606
3607 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3608 // Two identical pointer types are always compatible.
3609 return LHSTy;
3610 }
3611 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3612 rhptee.getUnqualifiedType())) {
3613 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3614 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3615 // In this situation, we assume void* type. No especially good
3616 // reason, but this is what gcc does, and we do have to pick
3617 // to get a consistent AST.
3618 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003619 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3620 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003621 return incompatTy;
3622 }
3623 // The pointer types are compatible.
3624 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3625 // differently qualified versions of compatible types, the result type is
3626 // a pointer to an appropriately qualified version of the *composite*
3627 // type.
3628 // FIXME: Need to calculate the composite type.
3629 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003630 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3631 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003632 return LHSTy;
3633 }
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Steve Naroff7154a772009-07-01 14:36:47 +00003635 // GCC compatibility: soften pointer/integer mismatch.
3636 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3637 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3638 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003639 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003640 return RHSTy;
3641 }
3642 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3643 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3644 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003645 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003646 return LHSTy;
3647 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003648
Chris Lattner70d67a92008-01-06 22:42:25 +00003649 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003650 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3651 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003652 return QualType();
3653}
3654
Steve Narofff69936d2007-09-16 03:34:24 +00003655/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003656/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003657Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3658 SourceLocation ColonLoc,
3659 ExprArg Cond, ExprArg LHS,
3660 ExprArg RHS) {
3661 Expr *CondExpr = (Expr *) Cond.get();
3662 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003663
3664 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3665 // was the condition.
3666 bool isLHSNull = LHSExpr == 0;
3667 if (isLHSNull)
3668 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003669
3670 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003671 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003672 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003673 return ExprError();
3674
3675 Cond.release();
3676 LHS.release();
3677 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003678 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003679 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003680 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003681}
3682
Reid Spencer5f016e22007-07-11 17:01:13 +00003683// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003684// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003685// routine is it effectively iqnores the qualifiers on the top level pointee.
3686// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3687// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003688Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003689Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3690 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003691
David Chisnall0f436562009-08-17 16:35:33 +00003692 if ((lhsType->isObjCClassType() &&
3693 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3694 (rhsType->isObjCClassType() &&
3695 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3696 return Compatible;
3697 }
3698
Reid Spencer5f016e22007-07-11 17:01:13 +00003699 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003700 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3701 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003702
Reid Spencer5f016e22007-07-11 17:01:13 +00003703 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003704 lhptee = Context.getCanonicalType(lhptee);
3705 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003706
Chris Lattner5cf216b2008-01-04 18:04:52 +00003707 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003708
3709 // C99 6.5.16.1p1: This following citation is common to constraints
3710 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3711 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003712 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003713 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003714 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003715
Mike Stumpeed9cac2009-02-19 03:04:26 +00003716 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3717 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003718 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003719 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003720 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003721 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003722
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003723 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003724 assert(rhptee->isFunctionType());
3725 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003726 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003727
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003728 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003729 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003730 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003731
3732 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003733 assert(lhptee->isFunctionType());
3734 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003735 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003736 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003737 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003738 lhptee = lhptee.getUnqualifiedType();
3739 rhptee = rhptee.getUnqualifiedType();
3740 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3741 // Check if the pointee types are compatible ignoring the sign.
3742 // We explicitly check for char so that we catch "char" vs
3743 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003744 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003745 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003746 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003747 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003748
3749 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003750 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003751 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003752 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003753
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003754 if (lhptee == rhptee) {
3755 // Types are compatible ignoring the sign. Qualifier incompatibility
3756 // takes priority over sign incompatibility because the sign
3757 // warning can be disabled.
3758 if (ConvTy != Compatible)
3759 return ConvTy;
3760 return IncompatiblePointerSign;
3761 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003762
3763 // If we are a multi-level pointer, it's possible that our issue is simply
3764 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3765 // the eventual target type is the same and the pointers have the same
3766 // level of indirection, this must be the issue.
3767 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3768 do {
3769 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3770 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3771
3772 lhptee = Context.getCanonicalType(lhptee);
3773 rhptee = Context.getCanonicalType(rhptee);
3774 } while (lhptee->isPointerType() && rhptee->isPointerType());
3775
Douglas Gregora4923eb2009-11-16 21:35:15 +00003776 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00003777 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003778 }
3779
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003780 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003781 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003782 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003783 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003784}
3785
Steve Naroff1c7d0672008-09-04 15:10:53 +00003786/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3787/// block pointer types are compatible or whether a block and normal pointer
3788/// are compatible. It is more restrict than comparing two function pointer
3789// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003790Sema::AssignConvertType
3791Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003792 QualType rhsType) {
3793 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003794
Steve Naroff1c7d0672008-09-04 15:10:53 +00003795 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003796 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3797 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003798
Steve Naroff1c7d0672008-09-04 15:10:53 +00003799 // make sure we operate on the canonical type
3800 lhptee = Context.getCanonicalType(lhptee);
3801 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003802
Steve Naroff1c7d0672008-09-04 15:10:53 +00003803 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003804
Steve Naroff1c7d0672008-09-04 15:10:53 +00003805 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003806 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00003807 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003808
Eli Friedman26784c12009-06-08 05:08:54 +00003809 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003810 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003811 return ConvTy;
3812}
3813
Mike Stumpeed9cac2009-02-19 03:04:26 +00003814/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3815/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003816/// pointers. Here are some objectionable examples that GCC considers warnings:
3817///
3818/// int a, *pint;
3819/// short *pshort;
3820/// struct foo *pfoo;
3821///
3822/// pint = pshort; // warning: assignment from incompatible pointer type
3823/// a = pint; // warning: assignment makes integer from pointer without a cast
3824/// pint = a; // warning: assignment makes pointer from integer without a cast
3825/// pint = pfoo; // warning: assignment from incompatible pointer type
3826///
3827/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003828/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003829///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003830Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003831Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003832 // Get canonical types. We're not formatting these types, just comparing
3833 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003834 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3835 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003836
3837 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003838 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003839
David Chisnall0f436562009-08-17 16:35:33 +00003840 if ((lhsType->isObjCClassType() &&
3841 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3842 (rhsType->isObjCClassType() &&
3843 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3844 return Compatible;
3845 }
3846
Douglas Gregor9d293df2008-10-28 00:22:11 +00003847 // If the left-hand side is a reference type, then we are in a
3848 // (rare!) case where we've allowed the use of references in C,
3849 // e.g., as a parameter type in a built-in function. In this case,
3850 // just make sure that the type referenced is compatible with the
3851 // right-hand side type. The caller is responsible for adjusting
3852 // lhsType so that the resulting expression does not have reference
3853 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003854 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003855 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003856 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003857 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003858 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003859 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3860 // to the same ExtVector type.
3861 if (lhsType->isExtVectorType()) {
3862 if (rhsType->isExtVectorType())
3863 return lhsType == rhsType ? Compatible : Incompatible;
3864 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3865 return Compatible;
3866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Nate Begemanbe2341d2008-07-14 18:02:46 +00003868 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003869 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003870 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003871 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003872 if (getLangOptions().LaxVectorConversions &&
3873 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003874 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003875 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003876 }
3877 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003878 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003879
Chris Lattnere8b3e962008-01-04 23:32:24 +00003880 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003881 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003882
Chris Lattner78eca282008-04-07 06:49:41 +00003883 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003884 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003885 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003886
Chris Lattner78eca282008-04-07 06:49:41 +00003887 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003888 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003889
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003890 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003891 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003892 if (lhsType->isVoidPointerType()) // an exception to the rule.
3893 return Compatible;
3894 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003895 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 if (rhsType->getAs<BlockPointerType>()) {
3897 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003898 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003899
3900 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003901 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003902 return Compatible;
3903 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003904 return Incompatible;
3905 }
3906
3907 if (isa<BlockPointerType>(lhsType)) {
3908 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003909 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003910
Steve Naroffb4406862008-09-29 18:10:17 +00003911 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003912 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003913 return Compatible;
3914
Steve Naroff1c7d0672008-09-04 15:10:53 +00003915 if (rhsType->isBlockPointerType())
3916 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003917
Ted Kremenek6217b802009-07-29 21:53:49 +00003918 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003919 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003920 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003921 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003922 return Incompatible;
3923 }
3924
Steve Naroff14108da2009-07-10 23:34:53 +00003925 if (isa<ObjCObjectPointerType>(lhsType)) {
3926 if (rhsType->isIntegerType())
3927 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003929 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003930 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003931 if (rhsType->isVoidPointerType()) // an exception to the rule.
3932 return Compatible;
3933 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003934 }
3935 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003936 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3937 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003938 if (Context.typesAreCompatible(lhsType, rhsType))
3939 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003940 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3941 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003942 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003943 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003944 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003945 if (RHSPT->getPointeeType()->isVoidType())
3946 return Compatible;
3947 }
3948 // Treat block pointers as objects.
3949 if (rhsType->isBlockPointerType())
3950 return Compatible;
3951 return Incompatible;
3952 }
Chris Lattner78eca282008-04-07 06:49:41 +00003953 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003954 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003955 if (lhsType == Context.BoolTy)
3956 return Compatible;
3957
3958 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003959 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003960
Mike Stumpeed9cac2009-02-19 03:04:26 +00003961 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003962 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003963
3964 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003965 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003966 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003967 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003968 }
Steve Naroff14108da2009-07-10 23:34:53 +00003969 if (isa<ObjCObjectPointerType>(rhsType)) {
3970 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3971 if (lhsType == Context.BoolTy)
3972 return Compatible;
3973
3974 if (lhsType->isIntegerType())
3975 return PointerToInt;
3976
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003977 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003978 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003979 if (lhsType->isVoidPointerType()) // an exception to the rule.
3980 return Compatible;
3981 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003982 }
3983 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003984 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003985 return Compatible;
3986 return Incompatible;
3987 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003988
Chris Lattnerfc144e22008-01-04 23:18:45 +00003989 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003990 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003991 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003992 }
3993 return Incompatible;
3994}
3995
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003996/// \brief Constructs a transparent union from an expression that is
3997/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00003998static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003999 QualType UnionType, FieldDecl *Field) {
4000 // Build an initializer list that designates the appropriate member
4001 // of the transparent union.
4002 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4003 &E, 1,
4004 SourceLocation());
4005 Initializer->setType(UnionType);
4006 Initializer->setInitializedFieldInUnion(Field);
4007
4008 // Build a compound literal constructing a value of the transparent
4009 // union type from this initializer list.
4010 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4011 false);
4012}
4013
4014Sema::AssignConvertType
4015Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4016 QualType FromType = rExpr->getType();
4017
Mike Stump1eb44332009-09-09 15:08:12 +00004018 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004019 // transparent_union GCC extension.
4020 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004021 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004022 return Incompatible;
4023
4024 // The field to initialize within the transparent union.
4025 RecordDecl *UD = UT->getDecl();
4026 FieldDecl *InitField = 0;
4027 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004028 for (RecordDecl::field_iterator it = UD->field_begin(),
4029 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004030 it != itend; ++it) {
4031 if (it->getType()->isPointerType()) {
4032 // If the transparent union contains a pointer type, we allow:
4033 // 1) void pointer
4034 // 2) null pointer constant
4035 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004036 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004037 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004038 InitField = *it;
4039 break;
4040 }
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Douglas Gregorce940492009-09-25 04:25:58 +00004042 if (rExpr->isNullPointerConstant(Context,
4043 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004044 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004045 InitField = *it;
4046 break;
4047 }
4048 }
4049
4050 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4051 == Compatible) {
4052 InitField = *it;
4053 break;
4054 }
4055 }
4056
4057 if (!InitField)
4058 return Incompatible;
4059
4060 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4061 return Compatible;
4062}
4063
Chris Lattner5cf216b2008-01-04 18:04:52 +00004064Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004065Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004066 if (getLangOptions().CPlusPlus) {
4067 if (!lhsType->isRecordType()) {
4068 // C++ 5.17p3: If the left operand is not of class type, the
4069 // expression is implicitly converted (C++ 4) to the
4070 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004071 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4072 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004073 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004074 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004075 }
4076
4077 // FIXME: Currently, we fall through and treat C++ classes like C
4078 // structures.
4079 }
4080
Steve Naroff529a4ad2007-11-27 17:58:44 +00004081 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4082 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004083 if ((lhsType->isPointerType() ||
4084 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004085 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004086 && rExpr->isNullPointerConstant(Context,
4087 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004088 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004089 return Compatible;
4090 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004091
Chris Lattner943140e2007-10-16 02:55:40 +00004092 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004093 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004094 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004095 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004096 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004097 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004098 if (!lhsType->isReferenceType())
4099 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004100
Chris Lattner5cf216b2008-01-04 18:04:52 +00004101 Sema::AssignConvertType result =
4102 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004103
Steve Narofff1120de2007-08-24 22:33:52 +00004104 // C99 6.5.16.1p2: The value of the right operand is converted to the
4105 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004106 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4107 // so that we can use references in built-in functions even in C.
4108 // The getNonReferenceType() call makes sure that the resulting expression
4109 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004110 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004111 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4112 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004113 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004114}
4115
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004116QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004117 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004118 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004119 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004120 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004121}
4122
Mike Stumpeed9cac2009-02-19 03:04:26 +00004123inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004124 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004125 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004126 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004127 QualType lhsType =
4128 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4129 QualType rhsType =
4130 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004131
Nate Begemanbe2341d2008-07-14 18:02:46 +00004132 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004133 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004134 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004135
Nate Begemanbe2341d2008-07-14 18:02:46 +00004136 // Handle the case of a vector & extvector type of the same size and element
4137 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004138 if (getLangOptions().LaxVectorConversions) {
4139 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004140 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4141 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004142 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004143 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004144 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004145 }
4146 }
4147 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004148
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004149 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4150 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4151 bool swapped = false;
4152 if (rhsType->isExtVectorType()) {
4153 swapped = true;
4154 std::swap(rex, lex);
4155 std::swap(rhsType, lhsType);
4156 }
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Nate Begemandde25982009-06-28 19:12:57 +00004158 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004159 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004160 QualType EltTy = LV->getElementType();
4161 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4162 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004163 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004164 if (swapped) std::swap(rex, lex);
4165 return lhsType;
4166 }
4167 }
4168 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4169 rhsType->isRealFloatingType()) {
4170 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004171 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004172 if (swapped) std::swap(rex, lex);
4173 return lhsType;
4174 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004175 }
4176 }
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Nate Begemandde25982009-06-28 19:12:57 +00004178 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004179 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004180 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004181 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004182 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004183}
4184
Reid Spencer5f016e22007-07-11 17:01:13 +00004185inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004186 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004187 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004188 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004189
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004190 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004191
Steve Naroffa4332e22007-07-17 00:58:39 +00004192 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004193 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004194 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004195}
4196
4197inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004198 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004199 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4200 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4201 return CheckVectorOperands(Loc, lex, rex);
4202 return InvalidOperands(Loc, lex, rex);
4203 }
Steve Naroff90045e82007-07-13 23:32:42 +00004204
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004205 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004206
Steve Naroffa4332e22007-07-17 00:58:39 +00004207 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004208 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004209 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004210}
4211
4212inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004213 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004214 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4215 QualType compType = CheckVectorOperands(Loc, lex, rex);
4216 if (CompLHSTy) *CompLHSTy = compType;
4217 return compType;
4218 }
Steve Naroff49b45262007-07-13 16:58:59 +00004219
Eli Friedmanab3a8522009-03-28 01:22:36 +00004220 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004221
Reid Spencer5f016e22007-07-11 17:01:13 +00004222 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004223 if (lex->getType()->isArithmeticType() &&
4224 rex->getType()->isArithmeticType()) {
4225 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004226 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004227 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004228
Eli Friedmand72d16e2008-05-18 18:08:51 +00004229 // Put any potential pointer into PExp
4230 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004231 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004232 std::swap(PExp, IExp);
4233
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004234 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Eli Friedmand72d16e2008-05-18 18:08:51 +00004236 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004237 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004238
Chris Lattnerb5f15622009-04-24 23:50:08 +00004239 // Check for arithmetic on pointers to incomplete types.
4240 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004241 if (getLangOptions().CPlusPlus) {
4242 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004243 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004244 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004245 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004246
4247 // GNU extension: arithmetic on pointer to void
4248 Diag(Loc, diag::ext_gnu_void_ptr)
4249 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004250 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004251 if (getLangOptions().CPlusPlus) {
4252 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4253 << lex->getType() << lex->getSourceRange();
4254 return QualType();
4255 }
4256
4257 // GNU extension: arithmetic on pointer to function
4258 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4259 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004260 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004261 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004262 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004263 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004264 PExp->getType()->isObjCObjectPointerType()) &&
4265 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004266 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4267 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004268 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004269 return QualType();
4270 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004271 // Diagnose bad cases where we step over interface counts.
4272 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4273 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4274 << PointeeTy << PExp->getSourceRange();
4275 return QualType();
4276 }
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Eli Friedmanab3a8522009-03-28 01:22:36 +00004278 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004279 QualType LHSTy = Context.isPromotableBitField(lex);
4280 if (LHSTy.isNull()) {
4281 LHSTy = lex->getType();
4282 if (LHSTy->isPromotableIntegerType())
4283 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004284 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004285 *CompLHSTy = LHSTy;
4286 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004287 return PExp->getType();
4288 }
4289 }
4290
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004291 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004292}
4293
Chris Lattnereca7be62008-04-07 05:30:13 +00004294// C99 6.5.6
4295QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004296 SourceLocation Loc, QualType* CompLHSTy) {
4297 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4298 QualType compType = CheckVectorOperands(Loc, lex, rex);
4299 if (CompLHSTy) *CompLHSTy = compType;
4300 return compType;
4301 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004302
Eli Friedmanab3a8522009-03-28 01:22:36 +00004303 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004304
Chris Lattner6e4ab612007-12-09 21:53:25 +00004305 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004306
Chris Lattner6e4ab612007-12-09 21:53:25 +00004307 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004308 if (lex->getType()->isArithmeticType()
4309 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004310 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004311 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004312 }
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Chris Lattner6e4ab612007-12-09 21:53:25 +00004314 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004315 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004316 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004317
Douglas Gregore7450f52009-03-24 19:52:54 +00004318 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004319
Douglas Gregore7450f52009-03-24 19:52:54 +00004320 bool ComplainAboutVoid = false;
4321 Expr *ComplainAboutFunc = 0;
4322 if (lpointee->isVoidType()) {
4323 if (getLangOptions().CPlusPlus) {
4324 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4325 << lex->getSourceRange() << rex->getSourceRange();
4326 return QualType();
4327 }
4328
4329 // GNU C extension: arithmetic on pointer to void
4330 ComplainAboutVoid = true;
4331 } else if (lpointee->isFunctionType()) {
4332 if (getLangOptions().CPlusPlus) {
4333 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004334 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004335 return QualType();
4336 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004337
4338 // GNU C extension: arithmetic on pointer to function
4339 ComplainAboutFunc = lex;
4340 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004341 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004342 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004343 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004344 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004345 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004346
Chris Lattnerb5f15622009-04-24 23:50:08 +00004347 // Diagnose bad cases where we step over interface counts.
4348 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4349 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4350 << lpointee << lex->getSourceRange();
4351 return QualType();
4352 }
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Chris Lattner6e4ab612007-12-09 21:53:25 +00004354 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004355 if (rex->getType()->isIntegerType()) {
4356 if (ComplainAboutVoid)
4357 Diag(Loc, diag::ext_gnu_void_ptr)
4358 << lex->getSourceRange() << rex->getSourceRange();
4359 if (ComplainAboutFunc)
4360 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004361 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004362 << ComplainAboutFunc->getSourceRange();
4363
Eli Friedmanab3a8522009-03-28 01:22:36 +00004364 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004365 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004366 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004367
Chris Lattner6e4ab612007-12-09 21:53:25 +00004368 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004369 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004370 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004371
Douglas Gregore7450f52009-03-24 19:52:54 +00004372 // RHS must be a completely-type object type.
4373 // Handle the GNU void* extension.
4374 if (rpointee->isVoidType()) {
4375 if (getLangOptions().CPlusPlus) {
4376 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4377 << lex->getSourceRange() << rex->getSourceRange();
4378 return QualType();
4379 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004380
Douglas Gregore7450f52009-03-24 19:52:54 +00004381 ComplainAboutVoid = true;
4382 } else if (rpointee->isFunctionType()) {
4383 if (getLangOptions().CPlusPlus) {
4384 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004385 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004386 return QualType();
4387 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004388
4389 // GNU extension: arithmetic on pointer to function
4390 if (!ComplainAboutFunc)
4391 ComplainAboutFunc = rex;
4392 } else if (!rpointee->isDependentType() &&
4393 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004394 PDiag(diag::err_typecheck_sub_ptr_object)
4395 << rex->getSourceRange()
4396 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004397 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004398
Eli Friedman88d936b2009-05-16 13:54:38 +00004399 if (getLangOptions().CPlusPlus) {
4400 // Pointee types must be the same: C++ [expr.add]
4401 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4402 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4403 << lex->getType() << rex->getType()
4404 << lex->getSourceRange() << rex->getSourceRange();
4405 return QualType();
4406 }
4407 } else {
4408 // Pointee types must be compatible C99 6.5.6p3
4409 if (!Context.typesAreCompatible(
4410 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4411 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4412 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4413 << lex->getType() << rex->getType()
4414 << lex->getSourceRange() << rex->getSourceRange();
4415 return QualType();
4416 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004417 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004418
Douglas Gregore7450f52009-03-24 19:52:54 +00004419 if (ComplainAboutVoid)
4420 Diag(Loc, diag::ext_gnu_void_ptr)
4421 << lex->getSourceRange() << rex->getSourceRange();
4422 if (ComplainAboutFunc)
4423 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004424 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004425 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004426
4427 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004428 return Context.getPointerDiffType();
4429 }
4430 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004431
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004432 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004433}
4434
Chris Lattnereca7be62008-04-07 05:30:13 +00004435// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004436QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004437 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004438 // C99 6.5.7p2: Each of the operands shall have integer type.
4439 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004440 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004441
Nate Begeman2207d792009-10-25 02:26:48 +00004442 // Vector shifts promote their scalar inputs to vector type.
4443 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4444 return CheckVectorOperands(Loc, lex, rex);
4445
Chris Lattnerca5eede2007-12-12 05:47:28 +00004446 // Shifts don't perform usual arithmetic conversions, they just do integer
4447 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004448 QualType LHSTy = Context.isPromotableBitField(lex);
4449 if (LHSTy.isNull()) {
4450 LHSTy = lex->getType();
4451 if (LHSTy->isPromotableIntegerType())
4452 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004453 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004454 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004455 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004456
Chris Lattnerca5eede2007-12-12 05:47:28 +00004457 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004458
Ryan Flynnd0439682009-08-07 16:20:20 +00004459 // Sanity-check shift operands
4460 llvm::APSInt Right;
4461 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004462 if (!rex->isValueDependent() &&
4463 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004464 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004465 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4466 else {
4467 llvm::APInt LeftBits(Right.getBitWidth(),
4468 Context.getTypeSize(lex->getType()));
4469 if (Right.uge(LeftBits))
4470 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4471 }
4472 }
4473
Chris Lattnerca5eede2007-12-12 05:47:28 +00004474 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004475 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004476}
4477
John McCall5dbad3d2009-11-06 08:49:08 +00004478/// \brief Implements -Wsign-compare.
4479///
4480/// \param lex the left-hand expression
4481/// \param rex the right-hand expression
4482/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004483/// \param Equality whether this is an "equality-like" join, which
4484/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004485void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004486 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004487 // Don't warn if we're in an unevaluated context.
4488 if (ExprEvalContext == Unevaluated)
4489 return;
4490
John McCall45aa4552009-11-05 00:40:04 +00004491 QualType lt = lex->getType(), rt = rex->getType();
4492
4493 // Only warn if both operands are integral.
4494 if (!lt->isIntegerType() || !rt->isIntegerType())
4495 return;
4496
Sebastian Redl732429c2009-11-05 21:09:23 +00004497 // If either expression is value-dependent, don't warn. We'll get another
4498 // chance at instantiation time.
4499 if (lex->isValueDependent() || rex->isValueDependent())
4500 return;
4501
John McCall45aa4552009-11-05 00:40:04 +00004502 // The rule is that the signed operand becomes unsigned, so isolate the
4503 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004504 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004505 if (lt->isSignedIntegerType()) {
4506 if (rt->isSignedIntegerType()) return;
4507 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004508 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004509 } else {
4510 if (!rt->isSignedIntegerType()) return;
4511 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004512 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004513 }
4514
John McCall5dbad3d2009-11-06 08:49:08 +00004515 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004516 // then (1) the result type will be signed and (2) the unsigned
4517 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004518 // of the comparison will be exact.
4519 if (Context.getIntWidth(signedOperand->getType()) >
4520 Context.getIntWidth(unsignedOperand->getType()))
4521 return;
4522
John McCall45aa4552009-11-05 00:40:04 +00004523 // If the value is a non-negative integer constant, then the
4524 // signed->unsigned conversion won't change it.
4525 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004526 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004527 assert(value.isSigned() && "result of signed expression not signed");
4528
4529 if (value.isNonNegative())
4530 return;
4531 }
4532
John McCall5dbad3d2009-11-06 08:49:08 +00004533 if (Equality) {
4534 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004535 // constant which cannot collide with a overflowed signed operand,
4536 // then reinterpreting the signed operand as unsigned will not
4537 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004538 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4539 assert(!value.isSigned() && "result of unsigned expression is signed");
4540
4541 // 2's complement: test the top bit.
4542 if (value.isNonNegative())
4543 return;
4544 }
4545 }
4546
John McCallb13c87f2009-11-05 09:23:39 +00004547 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004548 << lex->getType() << rex->getType()
4549 << lex->getSourceRange() << rex->getSourceRange();
4550}
4551
Douglas Gregor0c6db942009-05-04 06:07:12 +00004552// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004553QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004554 unsigned OpaqueOpc, bool isRelational) {
4555 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4556
Nate Begemanbe2341d2008-07-14 18:02:46 +00004557 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004558 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004559
John McCall5dbad3d2009-11-06 08:49:08 +00004560 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4561 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00004562
Chris Lattnera5937dd2007-08-26 01:18:55 +00004563 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004564 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4565 UsualArithmeticConversions(lex, rex);
4566 else {
4567 UsualUnaryConversions(lex);
4568 UsualUnaryConversions(rex);
4569 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004570 QualType lType = lex->getType();
4571 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004572
Mike Stumpaf199f32009-05-07 18:43:07 +00004573 if (!lType->isFloatingType()
4574 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004575 // For non-floating point types, check for self-comparisons of the form
4576 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4577 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004578 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004579 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004580 Expr *LHSStripped = lex->IgnoreParens();
4581 Expr *RHSStripped = rex->IgnoreParens();
4582 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4583 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004584 if (DRL->getDecl() == DRR->getDecl() &&
4585 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004586 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Chris Lattner55660a72009-03-08 19:39:53 +00004588 if (isa<CastExpr>(LHSStripped))
4589 LHSStripped = LHSStripped->IgnoreParenCasts();
4590 if (isa<CastExpr>(RHSStripped))
4591 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Chris Lattner55660a72009-03-08 19:39:53 +00004593 // Warn about comparisons against a string constant (unless the other
4594 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004595 Expr *literalString = 0;
4596 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004597 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004598 !RHSStripped->isNullPointerConstant(Context,
4599 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004600 literalString = lex;
4601 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004602 } else if ((isa<StringLiteral>(RHSStripped) ||
4603 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004604 !LHSStripped->isNullPointerConstant(Context,
4605 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004606 literalString = rex;
4607 literalStringStripped = RHSStripped;
4608 }
4609
4610 if (literalString) {
4611 std::string resultComparison;
4612 switch (Opc) {
4613 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4614 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4615 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4616 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4617 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4618 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4619 default: assert(false && "Invalid comparison operator");
4620 }
4621 Diag(Loc, diag::warn_stringcompare)
4622 << isa<ObjCEncodeExpr>(literalStringStripped)
4623 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004624 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4625 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4626 "strcmp(")
4627 << CodeModificationHint::CreateInsertion(
4628 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004629 resultComparison);
4630 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004631 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004632
Douglas Gregor447b69e2008-11-19 03:25:36 +00004633 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004634 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004635
Chris Lattnera5937dd2007-08-26 01:18:55 +00004636 if (isRelational) {
4637 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004638 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004639 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004640 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004641 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004642 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004643 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004644 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004645
Chris Lattnera5937dd2007-08-26 01:18:55 +00004646 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004647 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004648 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004649
Douglas Gregorce940492009-09-25 04:25:58 +00004650 bool LHSIsNull = lex->isNullPointerConstant(Context,
4651 Expr::NPC_ValueDependentIsNull);
4652 bool RHSIsNull = rex->isNullPointerConstant(Context,
4653 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004654
Chris Lattnera5937dd2007-08-26 01:18:55 +00004655 // All of the following pointer related warnings are GCC extensions, except
4656 // when handling null pointer constants. One day, we can consider making them
4657 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004658 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004659 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004660 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004661 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004662 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004663
Douglas Gregor0c6db942009-05-04 06:07:12 +00004664 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004665 if (LCanPointeeTy == RCanPointeeTy)
4666 return ResultTy;
4667
Douglas Gregor0c6db942009-05-04 06:07:12 +00004668 // C++ [expr.rel]p2:
4669 // [...] Pointer conversions (4.10) and qualification
4670 // conversions (4.4) are performed on pointer operands (or on
4671 // a pointer operand and a null pointer constant) to bring
4672 // them to their composite pointer type. [...]
4673 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004674 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004675 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004676 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004677 if (T.isNull()) {
4678 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4679 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4680 return QualType();
4681 }
4682
Eli Friedman73c39ab2009-10-20 08:27:19 +00004683 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4684 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004685 return ResultTy;
4686 }
Eli Friedman3075e762009-08-23 00:27:47 +00004687 // C99 6.5.9p2 and C99 6.5.8p2
4688 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4689 RCanPointeeTy.getUnqualifiedType())) {
4690 // Valid unless a relational comparison of function pointers
4691 if (isRelational && LCanPointeeTy->isFunctionType()) {
4692 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4693 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4694 }
4695 } else if (!isRelational &&
4696 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4697 // Valid unless comparison between non-null pointer and function pointer
4698 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4699 && !LHSIsNull && !RHSIsNull) {
4700 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4701 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4702 }
4703 } else {
4704 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004705 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004706 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004707 }
Eli Friedman3075e762009-08-23 00:27:47 +00004708 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004709 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004710 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004711 }
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004713 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004714 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004715 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004716 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004717 (lType->isPointerType() ||
4718 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004719 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004720 return ResultTy;
4721 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004722 if (LHSIsNull &&
4723 (rType->isPointerType() ||
4724 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004725 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004726 return ResultTy;
4727 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004728
4729 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004730 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004731 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4732 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004733 // In addition, pointers to members can be compared, or a pointer to
4734 // member and a null pointer constant. Pointer to member conversions
4735 // (4.11) and qualification conversions (4.4) are performed to bring
4736 // them to a common type. If one operand is a null pointer constant,
4737 // the common type is the type of the other operand. Otherwise, the
4738 // common type is a pointer to member type similar (4.4) to the type
4739 // of one of the operands, with a cv-qualification signature (4.4)
4740 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004741 // types.
4742 QualType T = FindCompositePointerType(lex, rex);
4743 if (T.isNull()) {
4744 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4745 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4746 return QualType();
4747 }
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Eli Friedman73c39ab2009-10-20 08:27:19 +00004749 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4750 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004751 return ResultTy;
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Douglas Gregor20b3e992009-08-24 17:42:35 +00004754 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004755 if (lType->isNullPtrType() && rType->isNullPtrType())
4756 return ResultTy;
4757 }
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Naroff1c7d0672008-09-04 15:10:53 +00004759 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004760 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004761 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4762 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004763
Steve Naroff1c7d0672008-09-04 15:10:53 +00004764 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004765 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004766 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004767 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004768 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004769 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004770 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004771 }
Steve Naroff59f53942008-09-28 01:11:11 +00004772 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004773 if (!isRelational
4774 && ((lType->isBlockPointerType() && rType->isPointerType())
4775 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004776 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004777 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004778 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004779 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004780 ->getPointeeType()->isVoidType())))
4781 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4782 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004783 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004784 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004785 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004786 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004787
Steve Naroff14108da2009-07-10 23:34:53 +00004788 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004789 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004790 const PointerType *LPT = lType->getAs<PointerType>();
4791 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004792 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004793 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004794 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004795 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004796
Steve Naroffa8069f12008-11-17 19:49:16 +00004797 if (!LPtrToVoid && !RPtrToVoid &&
4798 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004799 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004800 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004801 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004802 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004803 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004804 }
Steve Naroff14108da2009-07-10 23:34:53 +00004805 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004806 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004807 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4808 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004809 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004810 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004811 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004812 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004813 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004814 unsigned DiagID = 0;
4815 if (RHSIsNull) {
4816 if (isRelational)
4817 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4818 } else if (isRelational)
4819 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4820 else
4821 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004822
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004823 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004824 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004825 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004826 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004827 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004828 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004829 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004830 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004831 unsigned DiagID = 0;
4832 if (LHSIsNull) {
4833 if (isRelational)
4834 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4835 } else if (isRelational)
4836 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4837 else
4838 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004839
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004840 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004841 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004842 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004843 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004844 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004845 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004846 }
Steve Naroff39218df2008-09-04 16:56:14 +00004847 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004848 if (!isRelational && RHSIsNull
4849 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004850 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004851 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004852 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004853 if (!isRelational && LHSIsNull
4854 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004855 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004856 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004857 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004858 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004859}
4860
Nate Begemanbe2341d2008-07-14 18:02:46 +00004861/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004862/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004863/// like a scalar comparison, a vector comparison produces a vector of integer
4864/// types.
4865QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004866 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004867 bool isRelational) {
4868 // Check to make sure we're operating on vectors of the same type and width,
4869 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004870 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004871 if (vType.isNull())
4872 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004873
Nate Begemanbe2341d2008-07-14 18:02:46 +00004874 QualType lType = lex->getType();
4875 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004876
Nate Begemanbe2341d2008-07-14 18:02:46 +00004877 // For non-floating point types, check for self-comparisons of the form
4878 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4879 // often indicate logic errors in the program.
4880 if (!lType->isFloatingType()) {
4881 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4882 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4883 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004884 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004885 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004886
Nate Begemanbe2341d2008-07-14 18:02:46 +00004887 // Check for comparisons of floating point operands using != and ==.
4888 if (!isRelational && lType->isFloatingType()) {
4889 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004890 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004891 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004892
Nate Begemanbe2341d2008-07-14 18:02:46 +00004893 // Return the type for the comparison, which is the same as vector type for
4894 // integer vectors, or an integer type of identical size and number of
4895 // elements for floating point vectors.
4896 if (lType->isIntegerType())
4897 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004898
John McCall183700f2009-09-21 23:43:11 +00004899 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004900 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004901 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004902 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004903 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004904 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4905
Mike Stumpeed9cac2009-02-19 03:04:26 +00004906 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004907 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004908 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4909}
4910
Reid Spencer5f016e22007-07-11 17:01:13 +00004911inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004912 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004913 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004914 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004915
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004916 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004917
Steve Naroffa4332e22007-07-17 00:58:39 +00004918 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004919 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004920 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004921}
4922
4923inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004924 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004925 UsualUnaryConversions(lex);
4926 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004927
Anders Carlsson04905012009-10-16 01:44:21 +00004928 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4929 return InvalidOperands(Loc, lex, rex);
4930
4931 if (Context.getLangOptions().CPlusPlus) {
4932 // C++ [expr.log.and]p2
4933 // C++ [expr.log.or]p2
4934 return Context.BoolTy;
4935 }
4936
4937 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004938}
4939
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004940/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4941/// is a read-only property; return true if so. A readonly property expression
4942/// depends on various declarations and thus must be treated specially.
4943///
Mike Stump1eb44332009-09-09 15:08:12 +00004944static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004945 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4946 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4947 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4948 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004949 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004950 BaseType->getAsObjCInterfacePointerType())
4951 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4952 if (S.isPropertyReadonly(PDecl, IFace))
4953 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004954 }
4955 }
4956 return false;
4957}
4958
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004959/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4960/// emit an error and return true. If so, return false.
4961static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004962 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004963 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004964 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004965 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4966 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004967 if (IsLV == Expr::MLV_Valid)
4968 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004969
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004970 unsigned Diag = 0;
4971 bool NeedType = false;
4972 switch (IsLV) { // C99 6.5.16p2
4973 default: assert(0 && "Unknown result from isModifiableLvalue!");
4974 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004975 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004976 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4977 NeedType = true;
4978 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004979 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004980 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4981 NeedType = true;
4982 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004983 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004984 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4985 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004986 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004987 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4988 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004989 case Expr::MLV_IncompleteType:
4990 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004991 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004992 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4993 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004994 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004995 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4996 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004997 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004998 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4999 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005000 case Expr::MLV_ReadonlyProperty:
5001 Diag = diag::error_readonly_property_assignment;
5002 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005003 case Expr::MLV_NoSetterProperty:
5004 Diag = diag::error_nosetter_property_assignment;
5005 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005006 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005007
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005008 SourceRange Assign;
5009 if (Loc != OrigLoc)
5010 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005011 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005012 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005013 else
Mike Stump1eb44332009-09-09 15:08:12 +00005014 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005015 return true;
5016}
5017
5018
5019
5020// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005021QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5022 SourceLocation Loc,
5023 QualType CompoundType) {
5024 // Verify that LHS is a modifiable lvalue, and emit error if not.
5025 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005026 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005027
5028 QualType LHSType = LHS->getType();
5029 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005030
Chris Lattner5cf216b2008-01-04 18:04:52 +00005031 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005032 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005033 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005034 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005035 // Special case of NSObject attributes on c-style pointer types.
5036 if (ConvTy == IncompatiblePointer &&
5037 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005038 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005039 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005040 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005041 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005042
Chris Lattner2c156472008-08-21 18:04:13 +00005043 // If the RHS is a unary plus or minus, check to see if they = and + are
5044 // right next to each other. If so, the user may have typo'd "x =+ 4"
5045 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005046 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005047 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5048 RHSCheck = ICE->getSubExpr();
5049 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5050 if ((UO->getOpcode() == UnaryOperator::Plus ||
5051 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005052 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005053 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005054 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5055 // And there is a space or other character before the subexpr of the
5056 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005057 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5058 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005059 Diag(Loc, diag::warn_not_compound_assign)
5060 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5061 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005062 }
Chris Lattner2c156472008-08-21 18:04:13 +00005063 }
5064 } else {
5065 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005066 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005067 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005068
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005069 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5070 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005071 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005072
Reid Spencer5f016e22007-07-11 17:01:13 +00005073 // C99 6.5.16p3: The type of an assignment expression is the type of the
5074 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005075 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005076 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5077 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005078 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005079 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005080 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005081}
5082
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005083// C99 6.5.17
5084QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005085 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005086 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005087
5088 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5089 // incomplete in C++).
5090
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005091 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005092}
5093
Steve Naroff49b45262007-07-13 16:58:59 +00005094/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5095/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005096QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5097 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005098 if (Op->isTypeDependent())
5099 return Context.DependentTy;
5100
Chris Lattner3528d352008-11-21 07:05:48 +00005101 QualType ResType = Op->getType();
5102 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005103
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005104 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5105 // Decrement of bool is not allowed.
5106 if (!isInc) {
5107 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5108 return QualType();
5109 }
5110 // Increment of bool sets it to true, but is deprecated.
5111 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5112 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005113 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005114 } else if (ResType->isAnyPointerType()) {
5115 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005116
Chris Lattner3528d352008-11-21 07:05:48 +00005117 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005118 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005119 if (getLangOptions().CPlusPlus) {
5120 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5121 << Op->getSourceRange();
5122 return QualType();
5123 }
5124
5125 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005126 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005127 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005128 if (getLangOptions().CPlusPlus) {
5129 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5130 << Op->getType() << Op->getSourceRange();
5131 return QualType();
5132 }
5133
5134 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005135 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005136 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005137 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005138 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005139 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005140 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005141 // Diagnose bad cases where we step over interface counts.
5142 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5143 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5144 << PointeeTy << Op->getSourceRange();
5145 return QualType();
5146 }
Chris Lattner3528d352008-11-21 07:05:48 +00005147 } else if (ResType->isComplexType()) {
5148 // C99 does not support ++/-- on complex types, we allow as an extension.
5149 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005150 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005151 } else {
5152 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005153 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005154 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005155 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005156 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005157 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005158 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005159 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005160 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005161}
5162
Anders Carlsson369dee42008-02-01 07:15:58 +00005163/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005164/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005165/// where the declaration is needed for type checking. We only need to
5166/// handle cases when the expression references a function designator
5167/// or is an lvalue. Here are some examples:
5168/// - &(x) => x
5169/// - &*****f => f for f a function designator.
5170/// - &s.xx => s
5171/// - &s.zz[1].yy -> s, if zz is an array
5172/// - *(x + 1) -> x, if x is an array
5173/// - &"123"[2] -> 0
5174/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005175static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005176 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005177 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005178 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005179 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005180 // If this is an arrow operator, the address is an offset from
5181 // the base's value, so the object the base refers to is
5182 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005183 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005184 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005185 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005186 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005187 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005188 // FIXME: This code shouldn't be necessary! We should catch the implicit
5189 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005190 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5191 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5192 if (ICE->getSubExpr()->getType()->isArrayType())
5193 return getPrimaryDecl(ICE->getSubExpr());
5194 }
5195 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005196 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005197 case Stmt::UnaryOperatorClass: {
5198 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005199
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005200 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005201 case UnaryOperator::Real:
5202 case UnaryOperator::Imag:
5203 case UnaryOperator::Extension:
5204 return getPrimaryDecl(UO->getSubExpr());
5205 default:
5206 return 0;
5207 }
5208 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005209 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005210 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005211 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005212 // If the result of an implicit cast is an l-value, we care about
5213 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005214 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005215 default:
5216 return 0;
5217 }
5218}
5219
5220/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005221/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005222/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005223/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005224/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005225/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005226/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005227QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005228 // Make sure to ignore parentheses in subsequent checks
5229 op = op->IgnoreParens();
5230
Douglas Gregor9103bb22008-12-17 22:52:20 +00005231 if (op->isTypeDependent())
5232 return Context.DependentTy;
5233
Steve Naroff08f19672008-01-13 17:10:08 +00005234 if (getLangOptions().C99) {
5235 // Implement C99-only parts of addressof rules.
5236 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5237 if (uOp->getOpcode() == UnaryOperator::Deref)
5238 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5239 // (assuming the deref expression is valid).
5240 return uOp->getSubExpr()->getType();
5241 }
5242 // Technically, there should be a check for array subscript
5243 // expressions here, but the result of one is always an lvalue anyway.
5244 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005245 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005246 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005247
Eli Friedman441cf102009-05-16 23:27:50 +00005248 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5249 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005250 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005251 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005252 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005253 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5254 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005255 return QualType();
5256 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005257 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005258 // The operand cannot be a bit-field
5259 Diag(OpLoc, diag::err_typecheck_address_of)
5260 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005261 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005262 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5263 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005264 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005265 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005266 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005267 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005268 } else if (isa<ObjCPropertyRefExpr>(op)) {
5269 // cannot take address of a property expression.
5270 Diag(OpLoc, diag::err_typecheck_address_of)
5271 << "property expression" << op->getSourceRange();
5272 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005273 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5274 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005275 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5276 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005277 } else if (isa<UnresolvedLookupExpr>(op)) {
5278 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005279 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005280 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005281 // with the register storage-class specifier.
5282 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5283 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005284 Diag(OpLoc, diag::err_typecheck_address_of)
5285 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005286 return QualType();
5287 }
John McCallba135432009-11-21 08:51:07 +00005288 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005289 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005290 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005291 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005292 // Could be a pointer to member, though, if there is an explicit
5293 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005294 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005295 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005296 if (Ctx && Ctx->isRecord()) {
5297 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005298 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005299 diag::err_cannot_form_pointer_to_member_of_reference_type)
5300 << FD->getDeclName() << FD->getType();
5301 return QualType();
5302 }
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Sebastian Redlebc07d52009-02-03 20:19:35 +00005304 return Context.getMemberPointerType(op->getType(),
5305 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005306 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005307 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005308 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005309 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005310 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005311 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5312 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005313 return Context.getMemberPointerType(op->getType(),
5314 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5315 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005316 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005317 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005318
Eli Friedman441cf102009-05-16 23:27:50 +00005319 if (lval == Expr::LV_IncompleteVoidType) {
5320 // Taking the address of a void variable is technically illegal, but we
5321 // allow it in cases which are otherwise valid.
5322 // Example: "extern void x; void* y = &x;".
5323 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5324 }
5325
Reid Spencer5f016e22007-07-11 17:01:13 +00005326 // If the operand has type "type", the result has type "pointer to type".
5327 return Context.getPointerType(op->getType());
5328}
5329
Chris Lattner22caddc2008-11-23 09:13:29 +00005330QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005331 if (Op->isTypeDependent())
5332 return Context.DependentTy;
5333
Chris Lattner22caddc2008-11-23 09:13:29 +00005334 UsualUnaryConversions(Op);
5335 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005336
Chris Lattner22caddc2008-11-23 09:13:29 +00005337 // Note that per both C89 and C99, this is always legal, even if ptype is an
5338 // incomplete type or void. It would be possible to warn about dereferencing
5339 // a void pointer, but it's completely well-defined, and such a warning is
5340 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005341 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005342 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005343
John McCall183700f2009-09-21 23:43:11 +00005344 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005345 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005346
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005347 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005348 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005349 return QualType();
5350}
5351
5352static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5353 tok::TokenKind Kind) {
5354 BinaryOperator::Opcode Opc;
5355 switch (Kind) {
5356 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005357 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5358 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005359 case tok::star: Opc = BinaryOperator::Mul; break;
5360 case tok::slash: Opc = BinaryOperator::Div; break;
5361 case tok::percent: Opc = BinaryOperator::Rem; break;
5362 case tok::plus: Opc = BinaryOperator::Add; break;
5363 case tok::minus: Opc = BinaryOperator::Sub; break;
5364 case tok::lessless: Opc = BinaryOperator::Shl; break;
5365 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5366 case tok::lessequal: Opc = BinaryOperator::LE; break;
5367 case tok::less: Opc = BinaryOperator::LT; break;
5368 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5369 case tok::greater: Opc = BinaryOperator::GT; break;
5370 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5371 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5372 case tok::amp: Opc = BinaryOperator::And; break;
5373 case tok::caret: Opc = BinaryOperator::Xor; break;
5374 case tok::pipe: Opc = BinaryOperator::Or; break;
5375 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5376 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5377 case tok::equal: Opc = BinaryOperator::Assign; break;
5378 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5379 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5380 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5381 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5382 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5383 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5384 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5385 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5386 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5387 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5388 case tok::comma: Opc = BinaryOperator::Comma; break;
5389 }
5390 return Opc;
5391}
5392
5393static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5394 tok::TokenKind Kind) {
5395 UnaryOperator::Opcode Opc;
5396 switch (Kind) {
5397 default: assert(0 && "Unknown unary op!");
5398 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5399 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5400 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5401 case tok::star: Opc = UnaryOperator::Deref; break;
5402 case tok::plus: Opc = UnaryOperator::Plus; break;
5403 case tok::minus: Opc = UnaryOperator::Minus; break;
5404 case tok::tilde: Opc = UnaryOperator::Not; break;
5405 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005406 case tok::kw___real: Opc = UnaryOperator::Real; break;
5407 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5408 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5409 }
5410 return Opc;
5411}
5412
Douglas Gregoreaebc752008-11-06 23:29:22 +00005413/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5414/// operator @p Opc at location @c TokLoc. This routine only supports
5415/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005416Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5417 unsigned Op,
5418 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005419 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005420 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005421 // The following two variables are used for compound assignment operators
5422 QualType CompLHSTy; // Type of LHS after promotions for computation
5423 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005424
5425 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005426 case BinaryOperator::Assign:
5427 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5428 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005429 case BinaryOperator::PtrMemD:
5430 case BinaryOperator::PtrMemI:
5431 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5432 Opc == BinaryOperator::PtrMemI);
5433 break;
5434 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005435 case BinaryOperator::Div:
5436 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5437 break;
5438 case BinaryOperator::Rem:
5439 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5440 break;
5441 case BinaryOperator::Add:
5442 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5443 break;
5444 case BinaryOperator::Sub:
5445 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5446 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005447 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005448 case BinaryOperator::Shr:
5449 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5450 break;
5451 case BinaryOperator::LE:
5452 case BinaryOperator::LT:
5453 case BinaryOperator::GE:
5454 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005455 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005456 break;
5457 case BinaryOperator::EQ:
5458 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005459 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005460 break;
5461 case BinaryOperator::And:
5462 case BinaryOperator::Xor:
5463 case BinaryOperator::Or:
5464 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5465 break;
5466 case BinaryOperator::LAnd:
5467 case BinaryOperator::LOr:
5468 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5469 break;
5470 case BinaryOperator::MulAssign:
5471 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005472 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5473 CompLHSTy = CompResultTy;
5474 if (!CompResultTy.isNull())
5475 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005476 break;
5477 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005478 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5479 CompLHSTy = CompResultTy;
5480 if (!CompResultTy.isNull())
5481 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005482 break;
5483 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005484 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5485 if (!CompResultTy.isNull())
5486 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005487 break;
5488 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005489 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5490 if (!CompResultTy.isNull())
5491 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005492 break;
5493 case BinaryOperator::ShlAssign:
5494 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005495 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5496 CompLHSTy = CompResultTy;
5497 if (!CompResultTy.isNull())
5498 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005499 break;
5500 case BinaryOperator::AndAssign:
5501 case BinaryOperator::XorAssign:
5502 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005503 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5504 CompLHSTy = CompResultTy;
5505 if (!CompResultTy.isNull())
5506 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005507 break;
5508 case BinaryOperator::Comma:
5509 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5510 break;
5511 }
5512 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005513 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005514 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005515 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5516 else
5517 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005518 CompLHSTy, CompResultTy,
5519 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005520}
5521
Sebastian Redlaee3c932009-10-27 12:10:02 +00005522/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5523/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005524static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5525 const PartialDiagnostic &PD,
5526 SourceRange ParenRange)
5527{
5528 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5529 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5530 // We can't display the parentheses, so just dig the
5531 // warning/error and return.
5532 Self.Diag(Loc, PD);
5533 return;
5534 }
5535
5536 Self.Diag(Loc, PD)
5537 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5538 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5539}
5540
Sebastian Redlaee3c932009-10-27 12:10:02 +00005541/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5542/// operators are mixed in a way that suggests that the programmer forgot that
5543/// comparison operators have higher precedence. The most typical example of
5544/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005545static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5546 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005547 typedef BinaryOperator BinOp;
5548 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5549 rhsopc = static_cast<BinOp::Opcode>(-1);
5550 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005551 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005552 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005553 rhsopc = BO->getOpcode();
5554
5555 // Subs are not binary operators.
5556 if (lhsopc == -1 && rhsopc == -1)
5557 return;
5558
5559 // Bitwise operations are sometimes used as eager logical ops.
5560 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005561 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5562 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005563 return;
5564
Sebastian Redlaee3c932009-10-27 12:10:02 +00005565 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005566 SuggestParentheses(Self, OpLoc,
5567 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005568 << SourceRange(lhs->getLocStart(), OpLoc)
5569 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5570 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5571 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005572 SuggestParentheses(Self, OpLoc,
5573 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005574 << SourceRange(OpLoc, rhs->getLocEnd())
5575 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5576 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005577}
5578
5579/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5580/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5581/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5582static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5583 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005584 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005585 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5586}
5587
Reid Spencer5f016e22007-07-11 17:01:13 +00005588// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005589Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5590 tok::TokenKind Kind,
5591 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005592 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005593 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005594
Steve Narofff69936d2007-09-16 03:34:24 +00005595 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5596 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005597
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005598 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5599 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5600
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005601 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5602}
5603
5604Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5605 BinaryOperator::Opcode Opc,
5606 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005607 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005608 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005609 rhs->getType()->isOverloadableType())) {
5610 // Find all of the overloaded operators visible from this
5611 // point. We perform both an operator-name lookup from the local
5612 // scope and an argument-dependent lookup based on the types of
5613 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005614 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005615 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5616 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005617 if (S)
5618 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5619 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00005620 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005621 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005622 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005623 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005624 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005625
Douglas Gregor063daf62009-03-13 18:40:31 +00005626 // Build the (potentially-overloaded, potentially-dependent)
5627 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005628 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005629 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005630
Douglas Gregoreaebc752008-11-06 23:29:22 +00005631 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005632 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005633}
5634
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005635Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005636 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005637 ExprArg InputArg) {
5638 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005639
Mike Stump390b4cc2009-05-16 07:39:55 +00005640 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005641 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005642 QualType resultType;
5643 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005644 case UnaryOperator::OffsetOf:
5645 assert(false && "Invalid unary operator");
5646 break;
5647
Reid Spencer5f016e22007-07-11 17:01:13 +00005648 case UnaryOperator::PreInc:
5649 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005650 case UnaryOperator::PostInc:
5651 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005652 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005653 Opc == UnaryOperator::PreInc ||
5654 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005655 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005656 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005657 resultType = CheckAddressOfOperand(Input, OpLoc);
5658 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005659 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005660 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005661 resultType = CheckIndirectionOperand(Input, OpLoc);
5662 break;
5663 case UnaryOperator::Plus:
5664 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005665 UsualUnaryConversions(Input);
5666 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005667 if (resultType->isDependentType())
5668 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005669 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5670 break;
5671 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5672 resultType->isEnumeralType())
5673 break;
5674 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5675 Opc == UnaryOperator::Plus &&
5676 resultType->isPointerType())
5677 break;
5678
Sebastian Redl0eb23302009-01-19 00:08:26 +00005679 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5680 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005681 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005682 UsualUnaryConversions(Input);
5683 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005684 if (resultType->isDependentType())
5685 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005686 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5687 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5688 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005689 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005690 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005691 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005692 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5693 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005694 break;
5695 case UnaryOperator::LNot: // logical negation
5696 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005697 DefaultFunctionArrayConversion(Input);
5698 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005699 if (resultType->isDependentType())
5700 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005701 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005702 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5703 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005704 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005705 // In C++, it's bool. C++ 5.3.1p8
5706 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005707 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005708 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005709 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005710 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005711 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005712 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005713 resultType = Input->getType();
5714 break;
5715 }
5716 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005717 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005718
5719 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005720 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005721}
5722
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005723Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5724 UnaryOperator::Opcode Opc,
5725 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005726 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00005727 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5728 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005729 // Find all of the overloaded operators visible from this
5730 // point. We perform both an operator-name lookup from the local
5731 // scope and an argument-dependent lookup based on the types of
5732 // the arguments.
5733 FunctionSet Functions;
5734 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5735 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005736 if (S)
5737 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5738 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005739 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005740 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005741 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005742 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005743
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005744 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5745 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005746
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005747 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5748}
5749
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005750// Unary Operators. 'Tok' is the token for the operator.
5751Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5752 tok::TokenKind Op, ExprArg input) {
5753 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5754}
5755
Steve Naroff1b273c42007-09-16 14:56:35 +00005756/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005757Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5758 SourceLocation LabLoc,
5759 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005760 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005761 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005762
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005763 // If we haven't seen this label yet, create a forward reference. It
5764 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005765 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005766 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005767
Reid Spencer5f016e22007-07-11 17:01:13 +00005768 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005769 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5770 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005771}
5772
Sebastian Redlf53597f2009-03-15 17:47:39 +00005773Sema::OwningExprResult
5774Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5775 SourceLocation RPLoc) { // "({..})"
5776 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005777 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5778 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5779
Eli Friedmandca2b732009-01-24 23:09:00 +00005780 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005781 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005782 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005783
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005784 // FIXME: there are a variety of strange constraints to enforce here, for
5785 // example, it is not possible to goto into a stmt expression apparently.
5786 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005787
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005788 // If there are sub stmts in the compound stmt, take the type of the last one
5789 // as the type of the stmtexpr.
5790 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005791
Chris Lattner611b2ec2008-07-26 19:51:01 +00005792 if (!Compound->body_empty()) {
5793 Stmt *LastStmt = Compound->body_back();
5794 // If LastStmt is a label, skip down through into the body.
5795 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5796 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005797
Chris Lattner611b2ec2008-07-26 19:51:01 +00005798 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005799 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005800 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005801
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005802 // FIXME: Check that expression type is complete/non-abstract; statement
5803 // expressions are not lvalues.
5804
Sebastian Redlf53597f2009-03-15 17:47:39 +00005805 substmt.release();
5806 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005807}
Steve Naroffd34e9152007-08-01 22:05:33 +00005808
Sebastian Redlf53597f2009-03-15 17:47:39 +00005809Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5810 SourceLocation BuiltinLoc,
5811 SourceLocation TypeLoc,
5812 TypeTy *argty,
5813 OffsetOfComponent *CompPtr,
5814 unsigned NumComponents,
5815 SourceLocation RPLoc) {
5816 // FIXME: This function leaks all expressions in the offset components on
5817 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005818 // FIXME: Preserve type source info.
5819 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005820 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005821
Sebastian Redl28507842009-02-26 14:39:58 +00005822 bool Dependent = ArgTy->isDependentType();
5823
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005824 // We must have at least one component that refers to the type, and the first
5825 // one is known to be a field designator. Verify that the ArgTy represents
5826 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005827 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005828 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005829
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005830 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5831 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005832
Eli Friedman35183ac2009-02-27 06:44:11 +00005833 // Otherwise, create a null pointer as the base, and iteratively process
5834 // the offsetof designators.
5835 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5836 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005837 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005838 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005839
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005840 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5841 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005842 // FIXME: This diagnostic isn't actually visible because the location is in
5843 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005844 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005845 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5846 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005847
Sebastian Redl28507842009-02-26 14:39:58 +00005848 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005849 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005850
John McCalld00f2002009-11-04 03:03:43 +00005851 if (RequireCompleteType(TypeLoc, Res->getType(),
5852 diag::err_offsetof_incomplete_type))
5853 return ExprError();
5854
Sebastian Redl28507842009-02-26 14:39:58 +00005855 // FIXME: Dependent case loses a lot of information here. And probably
5856 // leaks like a sieve.
5857 for (unsigned i = 0; i != NumComponents; ++i) {
5858 const OffsetOfComponent &OC = CompPtr[i];
5859 if (OC.isBrackets) {
5860 // Offset of an array sub-field. TODO: Should we allow vector elements?
5861 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5862 if (!AT) {
5863 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005864 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5865 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005866 }
5867
5868 // FIXME: C++: Verify that operator[] isn't overloaded.
5869
Eli Friedman35183ac2009-02-27 06:44:11 +00005870 // Promote the array so it looks more like a normal array subscript
5871 // expression.
5872 DefaultFunctionArrayConversion(Res);
5873
Sebastian Redl28507842009-02-26 14:39:58 +00005874 // C99 6.5.2.1p1
5875 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005876 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005877 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005878 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005879 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005880 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005881
5882 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5883 OC.LocEnd);
5884 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005885 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005886
Ted Kremenek6217b802009-07-29 21:53:49 +00005887 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005888 if (!RC) {
5889 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005890 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5891 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005892 }
Chris Lattner704fe352007-08-30 17:59:59 +00005893
Sebastian Redl28507842009-02-26 14:39:58 +00005894 // Get the decl corresponding to this.
5895 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005896 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005897 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005898 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5899 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5900 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005901 DidWarnAboutNonPOD = true;
5902 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005903 }
Mike Stump1eb44332009-09-09 15:08:12 +00005904
John McCalla24dc2e2009-11-17 02:14:36 +00005905 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5906 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00005907
Sebastian Redl28507842009-02-26 14:39:58 +00005908 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005909 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005910 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005911 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005912 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5913 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005914
Sebastian Redl28507842009-02-26 14:39:58 +00005915 // FIXME: C++: Verify that MemberDecl isn't a static field.
5916 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005917 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005918 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00005919 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005920 } else {
5921 // MemberDecl->getType() doesn't get the right qualifiers, but it
5922 // doesn't matter here.
5923 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5924 MemberDecl->getType().getNonReferenceType());
5925 }
Sebastian Redl28507842009-02-26 14:39:58 +00005926 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005927 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005928
Sebastian Redlf53597f2009-03-15 17:47:39 +00005929 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5930 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005931}
5932
5933
Sebastian Redlf53597f2009-03-15 17:47:39 +00005934Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5935 TypeTy *arg1,TypeTy *arg2,
5936 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005937 // FIXME: Preserve type source info.
5938 QualType argT1 = GetTypeFromParser(arg1);
5939 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005940
Steve Naroffd34e9152007-08-01 22:05:33 +00005941 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005942
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005943 if (getLangOptions().CPlusPlus) {
5944 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5945 << SourceRange(BuiltinLoc, RPLoc);
5946 return ExprError();
5947 }
5948
Sebastian Redlf53597f2009-03-15 17:47:39 +00005949 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5950 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005951}
5952
Sebastian Redlf53597f2009-03-15 17:47:39 +00005953Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5954 ExprArg cond,
5955 ExprArg expr1, ExprArg expr2,
5956 SourceLocation RPLoc) {
5957 Expr *CondExpr = static_cast<Expr*>(cond.get());
5958 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5959 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005960
Steve Naroffd04fdd52007-08-03 21:21:27 +00005961 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5962
Sebastian Redl28507842009-02-26 14:39:58 +00005963 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005964 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005965 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005966 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005967 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005968 } else {
5969 // The conditional expression is required to be a constant expression.
5970 llvm::APSInt condEval(32);
5971 SourceLocation ExpLoc;
5972 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005973 return ExprError(Diag(ExpLoc,
5974 diag::err_typecheck_choose_expr_requires_constant)
5975 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005976
Sebastian Redl28507842009-02-26 14:39:58 +00005977 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5978 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00005979 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5980 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00005981 }
5982
Sebastian Redlf53597f2009-03-15 17:47:39 +00005983 cond.release(); expr1.release(); expr2.release();
5984 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00005985 resType, RPLoc,
5986 resType->isDependentType(),
5987 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005988}
5989
Steve Naroff4eb206b2008-09-03 18:15:37 +00005990//===----------------------------------------------------------------------===//
5991// Clang Extensions.
5992//===----------------------------------------------------------------------===//
5993
5994/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005995void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005996 // Analyze block parameters.
5997 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005998
Steve Naroff4eb206b2008-09-03 18:15:37 +00005999 // Add BSI to CurBlock.
6000 BSI->PrevBlockInfo = CurBlock;
6001 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006002
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006003 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006004 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006005 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006006 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006007 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6008 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006009
Steve Naroff090276f2008-10-10 01:28:17 +00006010 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006011 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006012}
6013
Mike Stump98eb8a72009-02-04 22:31:32 +00006014void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006015 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006016
6017 if (ParamInfo.getNumTypeObjects() == 0
6018 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006019 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006020 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6021
Mike Stump4eeab842009-04-28 01:10:27 +00006022 if (T->isArrayType()) {
6023 Diag(ParamInfo.getSourceRange().getBegin(),
6024 diag::err_block_returns_array);
6025 return;
6026 }
6027
Mike Stump98eb8a72009-02-04 22:31:32 +00006028 // The parameter list is optional, if there was none, assume ().
6029 if (!T->isFunctionType())
6030 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6031
6032 CurBlock->hasPrototype = true;
6033 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006034 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006035 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006036 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006037 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006038 // FIXME: remove the attribute.
6039 }
John McCall183700f2009-09-21 23:43:11 +00006040 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006041
Chris Lattner9097af12009-04-11 19:27:54 +00006042 // Do not allow returning a objc interface by-value.
6043 if (RetTy->isObjCInterfaceType()) {
6044 Diag(ParamInfo.getSourceRange().getBegin(),
6045 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6046 return;
6047 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006048 return;
6049 }
6050
Steve Naroff4eb206b2008-09-03 18:15:37 +00006051 // Analyze arguments to block.
6052 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6053 "Not a function declarator!");
6054 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006055
Steve Naroff090276f2008-10-10 01:28:17 +00006056 CurBlock->hasPrototype = FTI.hasPrototype;
6057 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006058
Steve Naroff4eb206b2008-09-03 18:15:37 +00006059 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6060 // no arguments, not a function that takes a single void argument.
6061 if (FTI.hasPrototype &&
6062 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006063 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6064 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006065 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006066 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006067 } else if (FTI.hasPrototype) {
6068 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006069 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006070 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006071 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006072 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006073 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006074 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006075 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006076 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6077 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6078 // If this has an identifier, add it to the scope stack.
6079 if ((*AI)->getIdentifier())
6080 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006081
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006082 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006083 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006084 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006085 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006086 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006087 // FIXME: remove the attribute.
6088 }
Mike Stump1eb44332009-09-09 15:08:12 +00006089
Chris Lattner9097af12009-04-11 19:27:54 +00006090 // Analyze the return type.
6091 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006092 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006093
Chris Lattner9097af12009-04-11 19:27:54 +00006094 // Do not allow returning a objc interface by-value.
6095 if (RetTy->isObjCInterfaceType()) {
6096 Diag(ParamInfo.getSourceRange().getBegin(),
6097 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6098 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006099 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006100}
6101
6102/// ActOnBlockError - If there is an error parsing a block, this callback
6103/// is invoked to pop the information about the block from the action impl.
6104void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6105 // Ensure that CurBlock is deleted.
6106 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006107
Chris Lattner17a78302009-04-19 05:28:12 +00006108 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6109
Steve Naroff4eb206b2008-09-03 18:15:37 +00006110 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006111 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006112 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006113 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006114}
6115
6116/// ActOnBlockStmtExpr - This is called when the body of a block statement
6117/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006118Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6119 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006120 // If blocks are disabled, emit an error.
6121 if (!LangOpts.Blocks)
6122 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006123
Steve Naroff4eb206b2008-09-03 18:15:37 +00006124 // Ensure that CurBlock is deleted.
6125 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006126
Steve Naroff090276f2008-10-10 01:28:17 +00006127 PopDeclContext();
6128
Steve Naroff4eb206b2008-09-03 18:15:37 +00006129 // Pop off CurBlock, handle nested blocks.
6130 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006131
Steve Naroff4eb206b2008-09-03 18:15:37 +00006132 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006133 if (!BSI->ReturnType.isNull())
6134 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006135
Steve Naroff4eb206b2008-09-03 18:15:37 +00006136 llvm::SmallVector<QualType, 8> ArgTypes;
6137 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6138 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006139
Mike Stump56925862009-07-28 22:04:01 +00006140 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006141 QualType BlockTy;
6142 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006143 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6144 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006145 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006146 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006147 BSI->isVariadic, 0, false, false, 0, 0,
6148 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006149
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006150 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006151 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006152 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006153
Chris Lattner17a78302009-04-19 05:28:12 +00006154 // If needed, diagnose invalid gotos and switches in the block.
6155 if (CurFunctionNeedsScopeChecking)
6156 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6157 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006158
Anders Carlssone9146f22009-05-01 19:49:17 +00006159 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006160 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006161 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6162 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006163}
6164
Sebastian Redlf53597f2009-03-15 17:47:39 +00006165Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6166 ExprArg expr, TypeTy *type,
6167 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006168 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006169 Expr *E = static_cast<Expr*>(expr.get());
6170 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006171
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006172 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006173
6174 // Get the va_list type
6175 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006176 if (VaListType->isArrayType()) {
6177 // Deal with implicit array decay; for example, on x86-64,
6178 // va_list is an array, but it's supposed to decay to
6179 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006180 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006181 // Make sure the input expression also decays appropriately.
6182 UsualUnaryConversions(E);
6183 } else {
6184 // Otherwise, the va_list argument must be an l-value because
6185 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006186 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006187 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006188 return ExprError();
6189 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006190
Douglas Gregordd027302009-05-19 23:10:31 +00006191 if (!E->isTypeDependent() &&
6192 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006193 return ExprError(Diag(E->getLocStart(),
6194 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006195 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006196 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006197
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006198 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006199 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006200
Sebastian Redlf53597f2009-03-15 17:47:39 +00006201 expr.release();
6202 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6203 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006204}
6205
Sebastian Redlf53597f2009-03-15 17:47:39 +00006206Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006207 // The type of __null will be int or long, depending on the size of
6208 // pointers on the target.
6209 QualType Ty;
6210 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6211 Ty = Context.IntTy;
6212 else
6213 Ty = Context.LongTy;
6214
Sebastian Redlf53597f2009-03-15 17:47:39 +00006215 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006216}
6217
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006218static void
6219MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6220 QualType DstType,
6221 Expr *SrcExpr,
6222 CodeModificationHint &Hint) {
6223 if (!SemaRef.getLangOptions().ObjC1)
6224 return;
6225
6226 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6227 if (!PT)
6228 return;
6229
6230 // Check if the destination is of type 'id'.
6231 if (!PT->isObjCIdType()) {
6232 // Check if the destination is the 'NSString' interface.
6233 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6234 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6235 return;
6236 }
6237
6238 // Strip off any parens and casts.
6239 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6240 if (!SL || SL->isWide())
6241 return;
6242
6243 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6244}
6245
Chris Lattner5cf216b2008-01-04 18:04:52 +00006246bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6247 SourceLocation Loc,
6248 QualType DstType, QualType SrcType,
6249 Expr *SrcExpr, const char *Flavor) {
6250 // Decode the result (notice that AST's are still created for extensions).
6251 bool isInvalid = false;
6252 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006253 CodeModificationHint Hint;
6254
Chris Lattner5cf216b2008-01-04 18:04:52 +00006255 switch (ConvTy) {
6256 default: assert(0 && "Unknown conversion type");
6257 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006258 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006259 DiagKind = diag::ext_typecheck_convert_pointer_int;
6260 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006261 case IntToPointer:
6262 DiagKind = diag::ext_typecheck_convert_int_pointer;
6263 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006264 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006265 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006266 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6267 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006268 case IncompatiblePointerSign:
6269 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6270 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006271 case FunctionVoidPointer:
6272 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6273 break;
6274 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006275 // If the qualifiers lost were because we were applying the
6276 // (deprecated) C++ conversion from a string literal to a char*
6277 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6278 // Ideally, this check would be performed in
6279 // CheckPointerTypesForAssignment. However, that would require a
6280 // bit of refactoring (so that the second argument is an
6281 // expression, rather than a type), which should be done as part
6282 // of a larger effort to fix CheckPointerTypesForAssignment for
6283 // C++ semantics.
6284 if (getLangOptions().CPlusPlus &&
6285 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6286 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006287 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6288 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006289 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006290 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006291 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006292 case IntToBlockPointer:
6293 DiagKind = diag::err_int_to_block_pointer;
6294 break;
6295 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006296 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006297 break;
Steve Naroff39579072008-10-14 22:18:38 +00006298 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006299 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006300 // it can give a more specific diagnostic.
6301 DiagKind = diag::warn_incompatible_qualified_id;
6302 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006303 case IncompatibleVectors:
6304 DiagKind = diag::warn_incompatible_vectors;
6305 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006306 case Incompatible:
6307 DiagKind = diag::err_typecheck_convert_incompatible;
6308 isInvalid = true;
6309 break;
6310 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006311
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006312 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006313 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006314 return isInvalid;
6315}
Anders Carlssone21555e2008-11-30 19:50:32 +00006316
Chris Lattner3bf68932009-04-25 21:59:05 +00006317bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006318 llvm::APSInt ICEResult;
6319 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6320 if (Result)
6321 *Result = ICEResult;
6322 return false;
6323 }
6324
Anders Carlssone21555e2008-11-30 19:50:32 +00006325 Expr::EvalResult EvalResult;
6326
Mike Stumpeed9cac2009-02-19 03:04:26 +00006327 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006328 EvalResult.HasSideEffects) {
6329 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6330
6331 if (EvalResult.Diag) {
6332 // We only show the note if it's not the usual "invalid subexpression"
6333 // or if it's actually in a subexpression.
6334 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6335 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6336 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6337 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006338
Anders Carlssone21555e2008-11-30 19:50:32 +00006339 return true;
6340 }
6341
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006342 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6343 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006344
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006345 if (EvalResult.Diag &&
6346 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6347 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006348
Anders Carlssone21555e2008-11-30 19:50:32 +00006349 if (Result)
6350 *Result = EvalResult.Val.getInt();
6351 return false;
6352}
Douglas Gregore0762c92009-06-19 23:52:42 +00006353
Mike Stump1eb44332009-09-09 15:08:12 +00006354Sema::ExpressionEvaluationContext
6355Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006356 // Introduce a new set of potentially referenced declarations to the stack.
6357 if (NewContext == PotentiallyPotentiallyEvaluated)
6358 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump1eb44332009-09-09 15:08:12 +00006359
Douglas Gregorac7610d2009-06-22 20:57:11 +00006360 std::swap(ExprEvalContext, NewContext);
6361 return NewContext;
6362}
6363
Mike Stump1eb44332009-09-09 15:08:12 +00006364void
Douglas Gregorac7610d2009-06-22 20:57:11 +00006365Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6366 ExpressionEvaluationContext NewContext) {
6367 ExprEvalContext = NewContext;
6368
6369 if (OldContext == PotentiallyPotentiallyEvaluated) {
6370 // Mark any remaining declarations in the current position of the stack
6371 // as "referenced". If they were not meant to be referenced, semantic
6372 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6373 PotentiallyReferencedDecls RemainingDecls;
6374 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6375 PotentiallyReferencedDeclStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00006376
Douglas Gregorac7610d2009-06-22 20:57:11 +00006377 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6378 IEnd = RemainingDecls.end();
6379 I != IEnd; ++I)
6380 MarkDeclarationReferenced(I->first, I->second);
6381 }
6382}
Douglas Gregore0762c92009-06-19 23:52:42 +00006383
6384/// \brief Note that the given declaration was referenced in the source code.
6385///
6386/// This routine should be invoke whenever a given declaration is referenced
6387/// in the source code, and where that reference occurred. If this declaration
6388/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6389/// C99 6.9p3), then the declaration will be marked as used.
6390///
6391/// \param Loc the location where the declaration was referenced.
6392///
6393/// \param D the declaration that has been referenced by the source code.
6394void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6395 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006396
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006397 if (D->isUsed())
6398 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006399
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006400 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6401 // template or not. The reason for this is that unevaluated expressions
6402 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6403 // -Wunused-parameters)
6404 if (isa<ParmVarDecl>(D) ||
6405 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006406 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006407
Douglas Gregore0762c92009-06-19 23:52:42 +00006408 // Do not mark anything as "used" within a dependent context; wait for
6409 // an instantiation.
6410 if (CurContext->isDependentContext())
6411 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006412
Douglas Gregorac7610d2009-06-22 20:57:11 +00006413 switch (ExprEvalContext) {
6414 case Unevaluated:
6415 // We are in an expression that is not potentially evaluated; do nothing.
6416 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006417
Douglas Gregorac7610d2009-06-22 20:57:11 +00006418 case PotentiallyEvaluated:
6419 // We are in a potentially-evaluated expression, so this declaration is
6420 // "used"; handle this below.
6421 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006422
Douglas Gregorac7610d2009-06-22 20:57:11 +00006423 case PotentiallyPotentiallyEvaluated:
6424 // We are in an expression that may be potentially evaluated; queue this
6425 // declaration reference until we know whether the expression is
6426 // potentially evaluated.
6427 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6428 return;
6429 }
Mike Stump1eb44332009-09-09 15:08:12 +00006430
Douglas Gregore0762c92009-06-19 23:52:42 +00006431 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006432 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006433 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006434 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6435 if (!Constructor->isUsed())
6436 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006437 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006438 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006439 if (!Constructor->isUsed())
6440 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6441 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006442 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6443 if (Destructor->isImplicit() && !Destructor->isUsed())
6444 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006445
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006446 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6447 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6448 MethodDecl->getOverloadedOperator() == OO_Equal) {
6449 if (!MethodDecl->isUsed())
6450 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6451 }
6452 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006453 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006454 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006455 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006456 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006457 bool AlreadyInstantiated = false;
6458 if (FunctionTemplateSpecializationInfo *SpecInfo
6459 = Function->getTemplateSpecializationInfo()) {
6460 if (SpecInfo->getPointOfInstantiation().isInvalid())
6461 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006462 else if (SpecInfo->getTemplateSpecializationKind()
6463 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006464 AlreadyInstantiated = true;
6465 } else if (MemberSpecializationInfo *MSInfo
6466 = Function->getMemberSpecializationInfo()) {
6467 if (MSInfo->getPointOfInstantiation().isInvalid())
6468 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006469 else if (MSInfo->getTemplateSpecializationKind()
6470 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006471 AlreadyInstantiated = true;
6472 }
6473
6474 if (!AlreadyInstantiated)
6475 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6476 }
6477
Douglas Gregore0762c92009-06-19 23:52:42 +00006478 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006479 Function->setUsed(true);
6480 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006481 }
Mike Stump1eb44332009-09-09 15:08:12 +00006482
Douglas Gregore0762c92009-06-19 23:52:42 +00006483 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006484 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006485 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006486 Var->getInstantiatedFromStaticDataMember()) {
6487 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6488 assert(MSInfo && "Missing member specialization information?");
6489 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6490 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6491 MSInfo->setPointOfInstantiation(Loc);
6492 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6493 }
6494 }
Mike Stump1eb44332009-09-09 15:08:12 +00006495
Douglas Gregore0762c92009-06-19 23:52:42 +00006496 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006497
Douglas Gregore0762c92009-06-19 23:52:42 +00006498 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006499 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006500 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006501}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006502
6503bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6504 CallExpr *CE, FunctionDecl *FD) {
6505 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6506 return false;
6507
6508 PartialDiagnostic Note =
6509 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6510 << FD->getDeclName() : PDiag();
6511 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6512
6513 if (RequireCompleteType(Loc, ReturnType,
6514 FD ?
6515 PDiag(diag::err_call_function_incomplete_return)
6516 << CE->getSourceRange() << FD->getDeclName() :
6517 PDiag(diag::err_call_incomplete_return)
6518 << CE->getSourceRange(),
6519 std::make_pair(NoteLoc, Note)))
6520 return true;
6521
6522 return false;
6523}
6524
John McCall5a881bb2009-10-12 21:59:07 +00006525// Diagnose the common s/=/==/ typo. Note that adding parentheses
6526// will prevent this condition from triggering, which is what we want.
6527void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6528 SourceLocation Loc;
6529
John McCalla52ef082009-11-11 02:41:58 +00006530 unsigned diagnostic = diag::warn_condition_is_assignment;
6531
John McCall5a881bb2009-10-12 21:59:07 +00006532 if (isa<BinaryOperator>(E)) {
6533 BinaryOperator *Op = cast<BinaryOperator>(E);
6534 if (Op->getOpcode() != BinaryOperator::Assign)
6535 return;
6536
John McCallc8d8ac52009-11-12 00:06:05 +00006537 // Greylist some idioms by putting them into a warning subcategory.
6538 if (ObjCMessageExpr *ME
6539 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6540 Selector Sel = ME->getSelector();
6541
John McCallc8d8ac52009-11-12 00:06:05 +00006542 // self = [<foo> init...]
6543 if (isSelfExpr(Op->getLHS())
6544 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6545 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6546
6547 // <foo> = [<bar> nextObject]
6548 else if (Sel.isUnarySelector() &&
6549 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6550 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6551 }
John McCalla52ef082009-11-11 02:41:58 +00006552
John McCall5a881bb2009-10-12 21:59:07 +00006553 Loc = Op->getOperatorLoc();
6554 } else if (isa<CXXOperatorCallExpr>(E)) {
6555 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6556 if (Op->getOperator() != OO_Equal)
6557 return;
6558
6559 Loc = Op->getOperatorLoc();
6560 } else {
6561 // Not an assignment.
6562 return;
6563 }
6564
John McCall5a881bb2009-10-12 21:59:07 +00006565 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006566 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006567
John McCalla52ef082009-11-11 02:41:58 +00006568 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00006569 << E->getSourceRange()
6570 << CodeModificationHint::CreateInsertion(Open, "(")
6571 << CodeModificationHint::CreateInsertion(Close, ")");
6572}
6573
6574bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6575 DiagnoseAssignmentAsCondition(E);
6576
6577 if (!E->isTypeDependent()) {
6578 DefaultFunctionArrayConversion(E);
6579
6580 QualType T = E->getType();
6581
6582 if (getLangOptions().CPlusPlus) {
6583 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6584 return true;
6585 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6586 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6587 << T << E->getSourceRange();
6588 return true;
6589 }
6590 }
6591
6592 return false;
6593}