blob: 42b49c5d0b5ee16864c5546abacc76d687f44f6b [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
John McCalld5532b62009-11-23 01:53:49 +0000913 0, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000915 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
916}
917
John McCallba135432009-11-21 08:51:07 +0000918/// Builds an implicit member access expression from the given
919/// unqualified lookup set, which is known to contain only class
920/// members.
John McCall5b3f9132009-11-22 01:44:31 +0000921Sema::OwningExprResult
922Sema::BuildImplicitMemberReferenceExpr(const CXXScopeSpec *SS,
923 LookupResult &R) {
924 NamedDecl *D = R.getAsSingleDecl(Context);
John McCallba135432009-11-21 08:51:07 +0000925 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +0000926
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000927 // We may have found a field within an anonymous union or struct
928 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000929 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000930 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
931 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +0000932 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000933
John McCallba135432009-11-21 08:51:07 +0000934 QualType ThisType;
935 QualType MemberType;
John McCall5b3f9132009-11-22 01:44:31 +0000936 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
937 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
938 MarkDeclarationReferenced(Loc, D);
939 if (PerformObjectMemberConversion(This, D))
940 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +0000941
Douglas Gregore961afb2009-10-22 07:08:30 +0000942 bool ShouldCheckUse = true;
943 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
944 // Don't diagnose the use of a virtual member function unless it's
945 // explicitly qualified.
946 if (MD->isVirtual() && (!SS || !SS->isSet()))
947 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +0000948 }
Douglas Gregore961afb2009-10-22 07:08:30 +0000949
John McCall5b3f9132009-11-22 01:44:31 +0000950 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
951 return ExprError();
952 return Owned(BuildMemberExpr(Context, This, true, SS, D, Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000953 }
954
John McCallba135432009-11-21 08:51:07 +0000955 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +0000956 if (!Method->isStatic())
957 return ExprError(Diag(Loc, diag::err_member_call_without_object));
John McCallba135432009-11-21 08:51:07 +0000958 }
959
960 if (isa<FieldDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +0000961 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
John McCallba135432009-11-21 08:51:07 +0000962 if (MD->isStatic()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000963 // "invalid use of member 'x' in static member function"
John McCall5b3f9132009-11-22 01:44:31 +0000964 Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallba135432009-11-21 08:51:07 +0000965 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +0000966 return ExprError();
John McCallba135432009-11-21 08:51:07 +0000967 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000968 }
969
Douglas Gregor88a35142008-12-22 05:46:06 +0000970 // Any other ways we could have found the field in a well-formed
971 // program would have been turned into implicit member expressions
972 // above.
John McCall5b3f9132009-11-22 01:44:31 +0000973 Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallba135432009-11-21 08:51:07 +0000974 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +0000975 return ExprError();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000976 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000977
John McCall5b3f9132009-11-22 01:44:31 +0000978 // We're not in an implicit member-reference context, but the lookup
979 // results might not require an instance. Try to build a non-member
980 // decl reference.
981 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
John McCallba135432009-11-21 08:51:07 +0000982}
983
John McCall5b3f9132009-11-22 01:44:31 +0000984bool Sema::UseArgumentDependentLookup(const CXXScopeSpec *SS,
985 const LookupResult &R,
986 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +0000987 // Only when used directly as the postfix-expression of a call.
988 if (!HasTrailingLParen)
989 return false;
990
991 // Never if a scope specifier was provided.
992 if (SS && SS->isSet())
993 return false;
994
995 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +0000996 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +0000997 return false;
998
999 // Turn off ADL when we find certain kinds of declarations during
1000 // normal lookup:
1001 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1002 NamedDecl *D = *I;
1003
1004 // C++0x [basic.lookup.argdep]p3:
1005 // -- a declaration of a class member
1006 // Since using decls preserve this property, we check this on the
1007 // original decl.
1008 if (D->getDeclContext()->isRecord())
1009 return false;
1010
1011 // C++0x [basic.lookup.argdep]p3:
1012 // -- a block-scope function declaration that is not a
1013 // using-declaration
1014 // NOTE: we also trigger this for function templates (in fact, we
1015 // don't check the decl type at all, since all other decl types
1016 // turn off ADL anyway).
1017 if (isa<UsingShadowDecl>(D))
1018 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1019 else if (D->getDeclContext()->isFunctionOrMethod())
1020 return false;
1021
1022 // C++0x [basic.lookup.argdep]p3:
1023 // -- a declaration that is neither a function or a function
1024 // template
1025 // And also for builtin functions.
1026 if (isa<FunctionDecl>(D)) {
1027 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1028
1029 // But also builtin functions.
1030 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1031 return false;
1032 } else if (!isa<FunctionTemplateDecl>(D))
1033 return false;
1034 }
1035
1036 return true;
1037}
1038
1039
John McCallba135432009-11-21 08:51:07 +00001040/// Diagnoses obvious problems with the use of the given declaration
1041/// as an expression. This is only actually called for lookups that
1042/// were not overloaded, and it doesn't promise that the declaration
1043/// will in fact be used.
1044static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1045 if (isa<TypedefDecl>(D)) {
1046 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1047 return true;
1048 }
1049
1050 if (isa<ObjCInterfaceDecl>(D)) {
1051 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1052 return true;
1053 }
1054
1055 if (isa<NamespaceDecl>(D)) {
1056 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1057 return true;
1058 }
1059
1060 return false;
1061}
1062
1063Sema::OwningExprResult
1064Sema::BuildDeclarationNameExpr(const CXXScopeSpec *SS,
John McCall5b3f9132009-11-22 01:44:31 +00001065 LookupResult &R,
1066 bool NeedsADL) {
1067 assert(R.getResultKind() != LookupResult::FoundUnresolvedValue);
1068
1069 if (!NeedsADL && !R.isOverloadedResult())
1070 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001071
1072 // We only need to check the declaration if there's exactly one
1073 // result, because in the overloaded case the results can only be
1074 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001075 if (R.isSingleResult() &&
1076 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001077 return ExprError();
1078
1079 UnresolvedLookupExpr *ULE
1080 = UnresolvedLookupExpr::Create(Context,
1081 SS ? (NestedNameSpecifier *)SS->getScopeRep() : 0,
John McCall7453ed42009-11-22 00:44:51 +00001082 SS ? SS->getRange() : SourceRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001083 R.getLookupName(), R.getNameLoc(),
1084 NeedsADL, R.isOverloadedResult());
1085 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1086 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001087
1088 return Owned(ULE);
1089}
1090
1091
1092/// \brief Complete semantic analysis for a reference to the given declaration.
1093Sema::OwningExprResult
1094Sema::BuildDeclarationNameExpr(const CXXScopeSpec *SS,
1095 SourceLocation Loc, NamedDecl *D) {
1096 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001097 assert(!isa<FunctionTemplateDecl>(D) &&
1098 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001099 DeclarationName Name = D->getDeclName();
1100
1101 if (CheckDeclInExpr(*this, Loc, D))
1102 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001103
Steve Naroffdd972f22008-09-05 22:11:13 +00001104 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001105
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001106 // Check whether this declaration can be used. Note that we suppress
1107 // this check when we're going to perform argument-dependent lookup
1108 // on this function name, because this might not be the function
1109 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001110 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001111 return ExprError();
1112
Steve Naroffdd972f22008-09-05 22:11:13 +00001113 // Only create DeclRefExpr's for valid Decl's.
1114 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001115 return ExprError();
1116
Chris Lattner639e2d32008-10-20 05:16:36 +00001117 // If the identifier reference is inside a block, and it refers to a value
1118 // that is outside the block, create a BlockDeclRefExpr instead of a
1119 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1120 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001121 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001122 // We do not do this for things like enum constants, global variables, etc,
1123 // as they do not get snapshotted.
1124 //
1125 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001126 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001127 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001128 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001129 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001130 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001131 // This is to record that a 'const' was actually synthesize and added.
1132 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001133 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Eli Friedman5fdeae12009-03-22 23:00:19 +00001135 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001136 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001137 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001138 }
1139 // If this reference is not in a block or if the referenced variable is
1140 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001141
Douglas Gregor898574e2008-12-05 23:32:09 +00001142 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001143 bool ValueDependent = false;
1144 if (getLangOptions().CPlusPlus) {
1145 // C++ [temp.dep.expr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001146 // An id-expression is type-dependent if it contains:
Douglas Gregor83f96f62008-12-10 20:57:37 +00001147 // - an identifier that was declared with a dependent type,
1148 if (VD->getType()->isDependentType())
1149 TypeDependent = true;
1150 // - FIXME: a template-id that is dependent,
1151 // - a conversion-function-id that specifies a dependent type,
1152 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1153 Name.getCXXNameType()->isDependentType())
1154 TypeDependent = true;
1155 // - a nested-name-specifier that contains a class-name that
1156 // names a dependent type.
John McCallba135432009-11-21 08:51:07 +00001157 else {
1158 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001159 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001160 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001161 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1162 if (Context.getTypeDeclType(Record)->isDependentType()) {
1163 TypeDependent = true;
1164 break;
1165 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001166 }
1167 }
1168 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001169
Douglas Gregor83f96f62008-12-10 20:57:37 +00001170 // C++ [temp.dep.constexpr]p2:
1171 //
1172 // An identifier is value-dependent if it is:
1173 // - a name declared with a dependent type,
1174 if (TypeDependent)
1175 ValueDependent = true;
1176 // - the name of a non-type template parameter,
1177 else if (isa<NonTypeTemplateParmDecl>(VD))
1178 ValueDependent = true;
1179 // - a constant with integral or enumeration type and is
1180 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001181 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
Mike Stumpfbf68702009-11-03 22:20:01 +00001182 if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1183 == Qualifiers::Const &&
Eli Friedmanc1494122009-06-11 01:11:20 +00001184 Dcl->getInit()) {
1185 ValueDependent = Dcl->getInit()->isValueDependent();
1186 }
1187 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001188 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001189
Anders Carlssone41590d2009-06-24 00:10:43 +00001190 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1191 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001192}
1193
Sebastian Redlcd965b92009-01-18 18:53:16 +00001194Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1195 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001196 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001197
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001199 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001200 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1201 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1202 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001204
Chris Lattnerfa28b302008-01-12 08:14:25 +00001205 // Pre-defined identifiers are of type char[x], where x is the length of the
1206 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Anders Carlsson3a082d82009-09-08 18:24:21 +00001208 Decl *currentDecl = getCurFunctionOrMethodDecl();
1209 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001210 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001211 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001212 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001213
Anders Carlsson773f3972009-09-11 01:22:35 +00001214 QualType ResTy;
1215 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1216 ResTy = Context.DependentTy;
1217 } else {
1218 unsigned Length =
1219 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001220
Anders Carlsson773f3972009-09-11 01:22:35 +00001221 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001222 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001223 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1224 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001225 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001226}
1227
Sebastian Redlcd965b92009-01-18 18:53:16 +00001228Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 llvm::SmallString<16> CharBuffer;
1230 CharBuffer.resize(Tok.getLength());
1231 const char *ThisTokBegin = &CharBuffer[0];
1232 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001233
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1235 Tok.getLocation(), PP);
1236 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001237 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001238
1239 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1240
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001241 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1242 Literal.isWide(),
1243 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001244}
1245
Sebastian Redlcd965b92009-01-18 18:53:16 +00001246Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1247 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1249 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001250 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001251 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001252 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001253 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 }
Ted Kremenek28396602009-01-13 23:19:12 +00001255
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001257 // Add padding so that NumericLiteralParser can overread by one character.
1258 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // Get the spelling of the token, which eliminates trigraphs, etc.
1262 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001263
Mike Stump1eb44332009-09-09 15:08:12 +00001264 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 Tok.getLocation(), PP);
1266 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001267 return ExprError();
1268
Chris Lattner5d661452007-08-26 03:42:43 +00001269 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001270
Chris Lattner5d661452007-08-26 03:42:43 +00001271 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001272 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001273 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001274 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001275 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001276 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001277 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001278 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001279
1280 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1281
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001282 // isExact will be set by GetFloatValue().
1283 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001284 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1285 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001286
Chris Lattner5d661452007-08-26 03:42:43 +00001287 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001288 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001289 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001290 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001291
Neil Boothb9449512007-08-29 22:00:19 +00001292 // long long is a C99 feature.
1293 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001294 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001295 Diag(Tok.getLocation(), diag::ext_longlong);
1296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001298 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001299
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 if (Literal.GetIntegerValue(ResultVal)) {
1301 // If this value didn't fit into uintmax_t, warn and force to ull.
1302 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001303 Ty = Context.UnsignedLongLongTy;
1304 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001305 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 } else {
1307 // If this value fits into a ULL, try to figure out what else it fits into
1308 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001309
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1311 // be an unsigned int.
1312 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1313
1314 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001315 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001316 if (!Literal.isLong && !Literal.isLongLong) {
1317 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001318 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001319
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 // Does it fit in a unsigned int?
1321 if (ResultVal.isIntN(IntSize)) {
1322 // Does it fit in a signed int?
1323 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001324 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001326 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001327 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001332 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001333 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001334
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 // Does it fit in a unsigned long?
1336 if (ResultVal.isIntN(LongSize)) {
1337 // Does it fit in a signed long?
1338 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001339 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001341 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001342 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001344 }
1345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001347 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001348 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001349
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 // Does it fit in a unsigned long long?
1351 if (ResultVal.isIntN(LongLongSize)) {
1352 // Does it fit in a signed long long?
1353 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001354 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001356 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001357 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 }
1359 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // If we still couldn't decide a type, we probably have something that
1362 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001363 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001365 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001366 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001368
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001369 if (ResultVal.getBitWidth() != Width)
1370 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001372 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001374
Chris Lattner5d661452007-08-26 03:42:43 +00001375 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1376 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001377 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001378 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001379
1380 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001381}
1382
Sebastian Redlcd965b92009-01-18 18:53:16 +00001383Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1384 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001385 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001386 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001387 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001388}
1389
1390/// The UsualUnaryConversions() function is *not* called by this routine.
1391/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001392bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001393 SourceLocation OpLoc,
1394 const SourceRange &ExprRange,
1395 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001396 if (exprType->isDependentType())
1397 return false;
1398
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001400 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001401 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001402 if (isSizeof)
1403 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1404 return false;
1405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Chris Lattner1efaa952009-04-24 00:30:45 +00001407 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001408 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001409 Diag(OpLoc, diag::ext_sizeof_void_type)
1410 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001411 return false;
1412 }
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Chris Lattner1efaa952009-04-24 00:30:45 +00001414 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001415 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001416 PDiag(diag::err_alignof_incomplete_type)
1417 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001418 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattner1efaa952009-04-24 00:30:45 +00001420 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001421 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001422 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001423 << exprType << isSizeof << ExprRange;
1424 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Chris Lattner1efaa952009-04-24 00:30:45 +00001427 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001428}
1429
Chris Lattner31e21e02009-01-24 20:17:12 +00001430bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1431 const SourceRange &ExprRange) {
1432 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001433
Mike Stump1eb44332009-09-09 15:08:12 +00001434 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001435 if (isa<DeclRefExpr>(E))
1436 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001437
1438 // Cannot know anything else if the expression is dependent.
1439 if (E->isTypeDependent())
1440 return false;
1441
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001442 if (E->getBitField()) {
1443 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1444 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001445 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001446
1447 // Alignment of a field access is always okay, so long as it isn't a
1448 // bit-field.
1449 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001450 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001451 return false;
1452
Chris Lattner31e21e02009-01-24 20:17:12 +00001453 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1454}
1455
Douglas Gregorba498172009-03-13 21:01:28 +00001456/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001457Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001458Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1459 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001460 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001461 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001462 return ExprError();
1463
John McCall5ab75172009-11-04 07:28:41 +00001464 QualType T = DInfo->getType();
1465
Douglas Gregorba498172009-03-13 21:01:28 +00001466 if (!T->isDependentType() &&
1467 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1468 return ExprError();
1469
1470 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001471 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001472 Context.getSizeType(), OpLoc,
1473 R.getEnd()));
1474}
1475
1476/// \brief Build a sizeof or alignof expression given an expression
1477/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001478Action::OwningExprResult
1479Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001480 bool isSizeOf, SourceRange R) {
1481 // Verify that the operand is valid.
1482 bool isInvalid = false;
1483 if (E->isTypeDependent()) {
1484 // Delay type-checking for type-dependent expressions.
1485 } else if (!isSizeOf) {
1486 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001487 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001488 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1489 isInvalid = true;
1490 } else {
1491 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1492 }
1493
1494 if (isInvalid)
1495 return ExprError();
1496
1497 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1498 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1499 Context.getSizeType(), OpLoc,
1500 R.getEnd()));
1501}
1502
Sebastian Redl05189992008-11-11 17:56:53 +00001503/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1504/// the same for @c alignof and @c __alignof
1505/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001506Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001507Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1508 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001510 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001511
Sebastian Redl05189992008-11-11 17:56:53 +00001512 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001513 DeclaratorInfo *DInfo;
1514 (void) GetTypeFromParser(TyOrEx, &DInfo);
1515 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001516 }
Sebastian Redl05189992008-11-11 17:56:53 +00001517
Douglas Gregorba498172009-03-13 21:01:28 +00001518 Expr *ArgEx = (Expr *)TyOrEx;
1519 Action::OwningExprResult Result
1520 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1521
1522 if (Result.isInvalid())
1523 DeleteExpr(ArgEx);
1524
1525 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526}
1527
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001528QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001529 if (V->isTypeDependent())
1530 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Chris Lattnercc26ed72007-08-26 05:39:26 +00001532 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001533 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001534 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Chris Lattnercc26ed72007-08-26 05:39:26 +00001536 // Otherwise they pass through real integer and floating point types here.
1537 if (V->getType()->isArithmeticType())
1538 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Chris Lattnercc26ed72007-08-26 05:39:26 +00001540 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001541 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1542 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001543 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001544}
1545
1546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547
Sebastian Redl0eb23302009-01-19 00:08:26 +00001548Action::OwningExprResult
1549Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1550 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 UnaryOperator::Opcode Opc;
1552 switch (Kind) {
1553 default: assert(0 && "Unknown unary op!");
1554 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1555 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1556 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001557
Eli Friedmane4216e92009-11-18 03:38:04 +00001558 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001559}
1560
Sebastian Redl0eb23302009-01-19 00:08:26 +00001561Action::OwningExprResult
1562Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1563 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001564 // Since this might be a postfix expression, get rid of ParenListExprs.
1565 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1566
Sebastian Redl0eb23302009-01-19 00:08:26 +00001567 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1568 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Douglas Gregor337c6b92008-11-19 17:17:41 +00001570 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001571 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1572 Base.release();
1573 Idx.release();
1574 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1575 Context.DependentTy, RLoc));
1576 }
1577
Mike Stump1eb44332009-09-09 15:08:12 +00001578 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001579 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001580 LHSExp->getType()->isEnumeralType() ||
1581 RHSExp->getType()->isRecordType() ||
1582 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001583 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001584 }
1585
Sebastian Redlf322ed62009-10-29 20:17:01 +00001586 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1587}
1588
1589
1590Action::OwningExprResult
1591Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1592 ExprArg Idx, SourceLocation RLoc) {
1593 Expr *LHSExp = static_cast<Expr*>(Base.get());
1594 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1595
Chris Lattner12d9ff62007-07-16 00:14:47 +00001596 // Perform default conversions.
1597 DefaultFunctionArrayConversion(LHSExp);
1598 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001599
Chris Lattner12d9ff62007-07-16 00:14:47 +00001600 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001601
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001603 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001604 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001606 Expr *BaseExpr, *IndexExpr;
1607 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001608 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1609 BaseExpr = LHSExp;
1610 IndexExpr = RHSExp;
1611 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001612 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001613 BaseExpr = LHSExp;
1614 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001615 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001616 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001617 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001618 BaseExpr = RHSExp;
1619 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001620 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001621 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001622 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001623 BaseExpr = LHSExp;
1624 IndexExpr = RHSExp;
1625 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001626 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001627 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001628 // Handle the uncommon case of "123[Ptr]".
1629 BaseExpr = RHSExp;
1630 IndexExpr = LHSExp;
1631 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001632 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001633 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001634 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001635
Chris Lattner12d9ff62007-07-16 00:14:47 +00001636 // FIXME: need to deal with const...
1637 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001638 } else if (LHSTy->isArrayType()) {
1639 // If we see an array that wasn't promoted by
1640 // DefaultFunctionArrayConversion, it must be an array that
1641 // wasn't promoted because of the C90 rule that doesn't
1642 // allow promoting non-lvalue arrays. Warn, then
1643 // force the promotion here.
1644 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1645 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001646 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1647 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001648 LHSTy = LHSExp->getType();
1649
1650 BaseExpr = LHSExp;
1651 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001652 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001653 } else if (RHSTy->isArrayType()) {
1654 // Same as previous, except for 123[f().a] case
1655 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1656 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001657 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1658 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001659 RHSTy = RHSExp->getType();
1660
1661 BaseExpr = RHSExp;
1662 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001663 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001665 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1666 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001667 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001669 if (!(IndexExpr->getType()->isIntegerType() &&
1670 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001671 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1672 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001673
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001674 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001675 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1676 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001677 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1678
Douglas Gregore7450f52009-03-24 19:52:54 +00001679 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001680 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1681 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001682 // incomplete types are not object types.
1683 if (ResultType->isFunctionType()) {
1684 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1685 << ResultType << BaseExpr->getSourceRange();
1686 return ExprError();
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregore7450f52009-03-24 19:52:54 +00001689 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001690 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001691 PDiag(diag::err_subscript_incomplete_type)
1692 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001693 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Chris Lattner1efaa952009-04-24 00:30:45 +00001695 // Diagnose bad cases where we step over interface counts.
1696 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1697 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1698 << ResultType << BaseExpr->getSourceRange();
1699 return ExprError();
1700 }
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Sebastian Redl0eb23302009-01-19 00:08:26 +00001702 Base.release();
1703 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001704 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001705 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001706}
1707
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001708QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001709CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001710 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001711 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001712 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1713 // see FIXME there.
1714 //
1715 // FIXME: This logic can be greatly simplified by splitting it along
1716 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001717 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001718
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001719 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001720 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001721
Mike Stumpeed9cac2009-02-19 03:04:26 +00001722 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001723 // special names that indicate a subset of exactly half the elements are
1724 // to be selected.
1725 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001726
Nate Begeman353417a2009-01-18 01:47:54 +00001727 // This flag determines whether or not CompName has an 's' char prefix,
1728 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001729 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001730
1731 // Check that we've found one of the special components, or that the component
1732 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001733 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001734 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1735 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001736 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001737 do
1738 compStr++;
1739 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001740 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001741 do
1742 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001743 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001744 }
Nate Begeman353417a2009-01-18 01:47:54 +00001745
Mike Stumpeed9cac2009-02-19 03:04:26 +00001746 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001747 // We didn't get to the end of the string. This means the component names
1748 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001749 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1750 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001751 return QualType();
1752 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001753
Nate Begeman353417a2009-01-18 01:47:54 +00001754 // Ensure no component accessor exceeds the width of the vector type it
1755 // operates on.
1756 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001757 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001758
1759 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001760 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001761
1762 while (*compStr) {
1763 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1764 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1765 << baseType << SourceRange(CompLoc);
1766 return QualType();
1767 }
1768 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001769 }
Nate Begeman8a997642008-05-09 06:41:27 +00001770
Nate Begeman353417a2009-01-18 01:47:54 +00001771 // If this is a halving swizzle, verify that the base type has an even
1772 // number of elements.
1773 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001774 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001775 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001776 return QualType();
1777 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001778
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001779 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001780 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001781 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001782 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001783 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001784 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001785 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001786 if (HexSwizzle)
1787 CompSize--;
1788
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001789 if (CompSize == 1)
1790 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001791
Nate Begeman213541a2008-04-18 23:10:10 +00001792 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001793 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001794 // diagostics look bad. We want extended vector types to appear built-in.
1795 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1796 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1797 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001798 }
1799 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001800}
1801
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001802static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001803 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001804 const Selector &Sel,
1805 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Anders Carlsson8f28f992009-08-26 18:25:21 +00001807 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001808 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001809 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001810 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001812 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1813 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001814 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001815 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001816 return D;
1817 }
1818 return 0;
1819}
1820
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001821static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001822 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001823 const Selector &Sel,
1824 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001825 // Check protocols on qualified interfaces.
1826 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001827 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001828 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001829 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001830 GDecl = PD;
1831 break;
1832 }
1833 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001834 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001835 GDecl = OMD;
1836 break;
1837 }
1838 }
1839 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001840 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001841 E = QIdTy->qual_end(); I != E; ++I) {
1842 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001843 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001844 if (GDecl)
1845 return GDecl;
1846 }
1847 }
1848 return GDecl;
1849}
Chris Lattner76a642f2009-02-15 22:43:40 +00001850
Mike Stump1eb44332009-09-09 15:08:12 +00001851Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001852Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001853 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001854 DeclarationName MemberName,
John McCalld5532b62009-11-23 01:53:49 +00001855 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001856 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1857 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001858 if (SS && SS->isInvalid())
1859 return ExprError();
1860
Nate Begeman2ef13e52009-08-10 23:49:36 +00001861 // Since this might be a postfix expression, get rid of ParenListExprs.
1862 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1863
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001864 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001865 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Steve Naroff3cc4af82007-12-16 21:42:28 +00001867 // Perform default conversions.
1868 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001869
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001870 QualType BaseType = BaseExpr->getType();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00001871
1872 // If the user is trying to apply -> or . to a function pointer
1873 // type, it's probably because the forgot parentheses to call that
1874 // function. Suggest the addition of those parentheses, build the
1875 // call, and continue on.
1876 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1877 if (const FunctionProtoType *Fun
1878 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1879 QualType ResultTy = Fun->getResultType();
1880 if (Fun->getNumArgs() == 0 &&
1881 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1882 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1883 ResultTy->getAs<PointerType>()->getPointeeType()
1884 ->isRecordType()))) {
1885 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1886 Diag(Loc, diag::err_member_reference_needs_call)
1887 << QualType(Fun, 0)
1888 << CodeModificationHint::CreateInsertion(Loc, "()");
1889
1890 OwningExprResult NewBase
1891 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1892 MultiExprArg(*this, 0, 0), 0, Loc);
1893 if (NewBase.isInvalid())
1894 return move(NewBase);
1895
1896 BaseExpr = NewBase.takeAs<Expr>();
1897 DefaultFunctionArrayConversion(BaseExpr);
1898 BaseType = BaseExpr->getType();
1899 }
1900 }
1901 }
1902
David Chisnall0f436562009-08-17 16:35:33 +00001903 // If this is an Objective-C pseudo-builtin and a definition is provided then
1904 // use that.
1905 if (BaseType->isObjCIdType()) {
1906 // We have an 'id' type. Rather than fall through, we check if this
1907 // is a reference to 'isa'.
1908 if (BaseType != Context.ObjCIdRedefinitionType) {
1909 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001910 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001911 }
David Chisnall0f436562009-08-17 16:35:33 +00001912 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001913 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001914
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001915 // Handle properties on ObjC 'Class' types.
1916 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1917 // Also must look for a getter name which uses property syntax.
1918 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1919 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1920 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1921 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1922 ObjCMethodDecl *Getter;
1923 // FIXME: need to also look locally in the implementation.
1924 if ((Getter = IFace->lookupClassMethod(Sel))) {
1925 // Check the use of this method.
1926 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1927 return ExprError();
1928 }
1929 // If we found a getter then this may be a valid dot-reference, we
1930 // will look for the matching setter, in case it is needed.
1931 Selector SetterSel =
1932 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1933 PP.getSelectorTable(), Member);
1934 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1935 if (!Setter) {
1936 // If this reference is in an @implementation, also check for 'private'
1937 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001938 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001939 }
1940 // Look through local category implementations associated with the class.
1941 if (!Setter)
1942 Setter = IFace->getCategoryClassMethod(SetterSel);
1943
1944 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1945 return ExprError();
1946
1947 if (Getter || Setter) {
1948 QualType PType;
1949
1950 if (Getter)
1951 PType = Getter->getResultType();
1952 else
1953 // Get the expression type from Setter's incoming parameter.
1954 PType = (*(Setter->param_end() -1))->getType();
1955 // FIXME: we must check that the setter has property type.
1956 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1957 PType,
1958 Setter, MemberLoc, BaseExpr));
1959 }
1960 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1961 << MemberName << BaseType);
1962 }
1963 }
1964
1965 if (BaseType->isObjCClassType() &&
1966 BaseType != Context.ObjCClassRedefinitionType) {
1967 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001968 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001969 }
1970
Chris Lattner68a057b2008-07-21 04:36:39 +00001971 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1972 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00001974 if (BaseType->isDependentType()) {
1975 NestedNameSpecifier *Qualifier = 0;
1976 if (SS) {
1977 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1978 if (!FirstQualifierInScope)
1979 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
John McCall865d4472009-11-19 22:55:06 +00001982 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001983 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00001984 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00001985 FirstQualifierInScope,
1986 MemberName,
1987 MemberLoc,
John McCalld5532b62009-11-23 01:53:49 +00001988 ExplicitTemplateArgs));
Douglas Gregorc68afe22009-09-03 21:38:09 +00001989 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001990 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001991 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00001992 else if (BaseType->isObjCObjectPointerType())
1993 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001994 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001995 return ExprError(Diag(MemberLoc,
1996 diag::err_typecheck_member_reference_arrow)
1997 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001998 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001999 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002000 // (so we'll report an error for)
2001 // T* t;
2002 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002003 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002004 // In Obj-C++, however, the above expression is valid, since it could be
2005 // accessing the 'f' property if T is an Obj-C interface. The extra check
2006 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002007 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002008
Mike Stump1eb44332009-09-09 15:08:12 +00002009 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002010 !PT->getPointeeType()->isRecordType())) {
2011 NestedNameSpecifier *Qualifier = 0;
2012 if (SS) {
2013 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2014 if (!FirstQualifierInScope)
2015 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2016 }
Mike Stump1eb44332009-09-09 15:08:12 +00002017
John McCall865d4472009-11-19 22:55:06 +00002018 return Owned(CXXDependentScopeMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002019 BaseExpr, false,
2020 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002021 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002022 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002023 FirstQualifierInScope,
2024 MemberName,
2025 MemberLoc,
John McCalld5532b62009-11-23 01:53:49 +00002026 ExplicitTemplateArgs));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002027 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002028 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002029
Chris Lattner68a057b2008-07-21 04:36:39 +00002030 // Handle field access to simple records. This also handles access to fields
2031 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002032 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002033 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002034 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002035 PDiag(diag::err_typecheck_incomplete_tag)
2036 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002037 return ExprError();
2038
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002039 DeclContext *DC = RDecl;
2040 if (SS && SS->isSet()) {
2041 // If the member name was a qualified-id, look into the
2042 // nested-name-specifier.
2043 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00002044
2045 if (!isa<TypeDecl>(DC)) {
2046 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2047 << DC << SS->getRange();
2048 return ExprError();
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
2051 // FIXME: If DC is not computable, we should build a
John McCall865d4472009-11-19 22:55:06 +00002052 // CXXDependentScopeMemberExpr.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002053 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2054 }
2055
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002056 // The record definition is complete, now make sure the member is valid.
John McCalla24dc2e2009-11-17 02:14:36 +00002057 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
2058 LookupQualifiedName(Result, DC);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002059
John McCallf36e02d2009-10-09 21:13:30 +00002060 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00002061 return ExprError(Diag(MemberLoc, diag::err_no_member)
2062 << MemberName << DC << BaseExpr->getSourceRange());
John McCalla24dc2e2009-11-17 02:14:36 +00002063 if (Result.isAmbiguous())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002064 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002065
John McCallf36e02d2009-10-09 21:13:30 +00002066 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2067
Douglas Gregora38c6872009-09-03 16:14:30 +00002068 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00002069 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002070 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002071 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002072 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00002073 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Douglas Gregora38c6872009-09-03 16:14:30 +00002075 if (BaseTypeCanon != MemberTypeCanon &&
2076 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2077 return ExprError(Diag(SS->getBeginLoc(),
2078 diag::err_not_direct_base_or_virtual)
2079 << MemberTypeCanon << BaseTypeCanon);
2080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Chris Lattner56cd21b2009-02-13 22:08:30 +00002082 // If the decl being referenced had an error, return an error for this
2083 // sub-expr without emitting another error, in order to avoid cascading
2084 // error cases.
2085 if (MemberDecl->isInvalidDecl())
2086 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002087
Anders Carlsson0f728562009-09-10 20:48:14 +00002088 bool ShouldCheckUse = true;
2089 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2090 // Don't diagnose the use of a virtual member function unless it's
2091 // explicitly qualified.
2092 if (MD->isVirtual() && (!SS || !SS->isSet()))
2093 ShouldCheckUse = false;
2094 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002095
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002096 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00002097 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002098 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002099
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002100 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002101 // We may have found a field within an anonymous union or struct
2102 // (C++ [class.union]).
2103 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002104 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002105 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002106
Douglas Gregor86f19402008-12-20 23:49:58 +00002107 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002108 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002109 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002110 MemberType = Ref->getPointeeType();
2111 else {
John McCall0953e762009-09-24 19:53:00 +00002112 Qualifiers BaseQuals = BaseType.getQualifiers();
2113 BaseQuals.removeObjCGCAttr();
2114 if (FD->isMutable()) BaseQuals.removeConst();
2115
2116 Qualifiers MemberQuals
2117 = Context.getCanonicalType(MemberType).getQualifiers();
2118
2119 Qualifiers Combined = BaseQuals + MemberQuals;
2120 if (Combined != MemberQuals)
2121 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002122 }
Eli Friedman51019072008-02-06 22:48:16 +00002123
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002124 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002125 if (PerformObjectMemberConversion(BaseExpr, FD))
2126 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002127 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002128 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002131 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2132 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002133 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2134 Var, MemberLoc,
2135 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002136 }
2137 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2138 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002139 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2140 MemberFn, MemberLoc,
2141 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002142 }
Mike Stump1eb44332009-09-09 15:08:12 +00002143 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002144 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2145 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
John McCalld5532b62009-11-23 01:53:49 +00002147 if (ExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002148 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2149 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002150 SS? SS->getRange() : SourceRange(),
John McCalld5532b62009-11-23 01:53:49 +00002151 FunTmpl, MemberLoc,
2152 ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002153 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002155 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2156 FunTmpl, MemberLoc,
2157 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002158 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002159 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002160 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
John McCalld5532b62009-11-23 01:53:49 +00002161 if (ExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002162 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2163 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002164 SS? SS->getRange() : SourceRange(),
John McCalld5532b62009-11-23 01:53:49 +00002165 Ovl, MemberLoc, ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002166 Context.OverloadTy));
2167
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002168 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2169 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002170 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002171 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2172 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002173 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2174 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002175 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002176 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002177 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002178 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002179
Douglas Gregor86f19402008-12-20 23:49:58 +00002180 // We found a declaration kind that we didn't expect. This is a
2181 // generic error message that tells the user that she can't refer
2182 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002183 return ExprError(Diag(MemberLoc,
2184 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002185 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002186 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002187
Douglas Gregora71d8192009-09-04 17:36:40 +00002188 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2189 // into a record type was handled above, any destructor we see here is a
2190 // pseudo-destructor.
2191 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2192 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002193 // The left hand side of the dot operator shall be of scalar type. The
2194 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002195 // type.
2196 if (!BaseType->isScalarType())
2197 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2198 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Douglas Gregora71d8192009-09-04 17:36:40 +00002200 // [...] The type designated by the pseudo-destructor-name shall be the
2201 // same as the object type.
2202 if (!MemberName.getCXXNameType()->isDependentType() &&
2203 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2204 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2205 << BaseType << MemberName.getCXXNameType()
2206 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002207
2208 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002209 // the form
2210 //
Mike Stump1eb44332009-09-09 15:08:12 +00002211 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2212 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002213 // shall designate the same scalar type.
2214 //
2215 // FIXME: DPG can't see any way to trigger this particular clause, so it
2216 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Douglas Gregora71d8192009-09-04 17:36:40 +00002218 // FIXME: We've lost the precise spelling of the type by going through
2219 // DeclarationName. Can we do better?
2220 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002221 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002222 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002223 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002224 SS? SS->getRange() : SourceRange(),
2225 MemberName.getCXXNameType(),
2226 MemberLoc));
2227 }
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Chris Lattnera38e6b12008-07-21 04:59:05 +00002229 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2230 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002231 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2232 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002233 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002234 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002235 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002236 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002237 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2238
Steve Naroffc70e8d92009-07-16 00:25:06 +00002239 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2240 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002241 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Steve Naroffc70e8d92009-07-16 00:25:06 +00002243 if (IV) {
2244 // If the decl being referenced had an error, return an error for this
2245 // sub-expr without emitting another error, in order to avoid cascading
2246 // error cases.
2247 if (IV->isInvalidDecl())
2248 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002249
Steve Naroffc70e8d92009-07-16 00:25:06 +00002250 // Check whether we can reference this field.
2251 if (DiagnoseUseOfDecl(IV, MemberLoc))
2252 return ExprError();
2253 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2254 IV->getAccessControl() != ObjCIvarDecl::Package) {
2255 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2256 if (ObjCMethodDecl *MD = getCurMethodDecl())
2257 ClassOfMethodDecl = MD->getClassInterface();
2258 else if (ObjCImpDecl && getCurFunctionDecl()) {
2259 // Case of a c-function declared inside an objc implementation.
2260 // FIXME: For a c-style function nested inside an objc implementation
2261 // class, there is no implementation context available, so we pass
2262 // down the context as argument to this routine. Ideally, this context
2263 // need be passed down in the AST node and somehow calculated from the
2264 // AST for a function decl.
2265 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002266 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002267 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2268 ClassOfMethodDecl = IMPD->getClassInterface();
2269 else if (ObjCCategoryImplDecl* CatImplClass =
2270 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2271 ClassOfMethodDecl = CatImplClass->getClassInterface();
2272 }
Mike Stump1eb44332009-09-09 15:08:12 +00002273
2274 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2275 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002276 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002277 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002278 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002279 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2280 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002281 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002282 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002283 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002284
2285 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2286 MemberLoc, BaseExpr,
2287 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002288 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002289 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002290 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002291 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002292 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002293 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002294 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002295 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002296 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002297 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002298 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Steve Naroff14108da2009-07-10 23:34:53 +00002300 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002301 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002302 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2303 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2304 // Check the use of this declaration
2305 if (DiagnoseUseOfDecl(PD, MemberLoc))
2306 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Steve Naroff14108da2009-07-10 23:34:53 +00002308 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2309 MemberLoc, BaseExpr));
2310 }
2311 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2312 // Check the use of this method.
2313 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2314 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Steve Naroff14108da2009-07-10 23:34:53 +00002316 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002317 OMD->getResultType(),
2318 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002319 NULL, 0));
2320 }
2321 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002322
Steve Naroff14108da2009-07-10 23:34:53 +00002323 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002324 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002325 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002326 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2327 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002328 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002329 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002330 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2331 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2332 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002333 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Daniel Dunbar2307d312008-09-03 01:05:41 +00002335 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002336 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002337 // Check whether we can reference this property.
2338 if (DiagnoseUseOfDecl(PD, MemberLoc))
2339 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002340 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002341 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002342 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002343 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2344 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002345 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002346 MemberLoc, BaseExpr));
2347 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002348 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002349 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2350 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002351 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002352 // Check whether we can reference this property.
2353 if (DiagnoseUseOfDecl(PD, MemberLoc))
2354 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002355
Steve Naroff6ece14c2009-01-21 00:14:39 +00002356 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002357 MemberLoc, BaseExpr));
2358 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002359 // If that failed, look for an "implicit" property by seeing if the nullary
2360 // selector is implemented.
2361
2362 // FIXME: The logic for looking up nullary and unary selectors should be
2363 // shared with the code in ActOnInstanceMessage.
2364
Anders Carlsson8f28f992009-08-26 18:25:21 +00002365 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002366 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002367
Daniel Dunbar2307d312008-09-03 01:05:41 +00002368 // If this reference is in an @implementation, check for 'private' methods.
2369 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002370 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002371
Steve Naroff7692ed62008-10-22 19:16:27 +00002372 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002373 if (!Getter)
2374 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002375 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002376 // Check if we can reference this property.
2377 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2378 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002379 }
2380 // If we found a getter then this may be a valid dot-reference, we
2381 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002382 Selector SetterSel =
2383 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002384 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002385 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002386 if (!Setter) {
2387 // If this reference is in an @implementation, also check for 'private'
2388 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002389 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002390 }
2391 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002392 if (!Setter)
2393 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002394
Steve Naroff1ca66942009-03-11 13:48:17 +00002395 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2396 return ExprError();
2397
2398 if (Getter || Setter) {
2399 QualType PType;
2400
2401 if (Getter)
2402 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002403 else
2404 // Get the expression type from Setter's incoming parameter.
2405 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002406 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002407 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002408 Setter, MemberLoc, BaseExpr));
2409 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002410 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002411 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002412 }
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Steve Narofff242b1b2009-07-24 17:54:45 +00002414 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002415 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002416 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002417 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002418 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2419 Context.getObjCIdType()));
2420
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002421 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002422 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002423 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002424 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2425 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002426 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002427 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002428 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002429 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002430
Douglas Gregor214f31a2009-03-27 06:00:30 +00002431 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2432 << BaseType << BaseExpr->getSourceRange();
2433
Douglas Gregor214f31a2009-03-27 06:00:30 +00002434 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002435}
2436
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002437Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2438 SourceLocation OpLoc,
2439 tok::TokenKind OpKind,
2440 const CXXScopeSpec &SS,
2441 UnqualifiedId &Member,
2442 DeclPtrTy ObjCImpDecl,
2443 bool HasTrailingLParen) {
2444 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2445 TemplateName Template
2446 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2447
2448 // FIXME: We're going to end up looking up the template based on its name,
2449 // twice!
2450 DeclarationName Name;
2451 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2452 Name = ActualTemplate->getDeclName();
2453 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2454 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002455 else {
2456 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2457 if (DTN->isIdentifier())
2458 Name = DTN->getIdentifier();
2459 else
2460 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2461 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002462
2463 // Translate the parser's template argument list in our AST format.
2464 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2465 Member.TemplateId->getTemplateArgs(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002466 Member.TemplateId->NumArgs);
2467
John McCalld5532b62009-11-23 01:53:49 +00002468 TemplateArgumentListInfo TemplateArgs;
2469 TemplateArgs.setLAngleLoc(Member.TemplateId->LAngleLoc);
2470 TemplateArgs.setRAngleLoc(Member.TemplateId->RAngleLoc);
2471 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002472 TemplateArgsPtr.release();
2473
2474 // Do we have the save the actual template name? We might need it...
2475 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2476 Member.TemplateId->TemplateNameLoc,
John McCalld5532b62009-11-23 01:53:49 +00002477 Name, &TemplateArgs, DeclPtrTy(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002478 &SS);
2479 }
2480
2481 // FIXME: We lose a lot of source information by mapping directly to the
2482 // DeclarationName.
2483 OwningExprResult Result
2484 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2485 Member.getSourceRange().getBegin(),
2486 GetNameFromUnqualifiedId(Member),
2487 ObjCImpDecl, &SS);
2488
2489 if (Result.isInvalid() || HasTrailingLParen ||
2490 Member.getKind() != UnqualifiedId::IK_DestructorName)
2491 return move(Result);
2492
2493 // The only way a reference to a destructor can be used is to
2494 // immediately call them. Since the next token is not a '(', produce a
2495 // diagnostic and build the call now.
2496 Expr *E = (Expr *)Result.get();
2497 SourceLocation ExpectedLParenLoc
2498 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2499 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2500 << isa<CXXPseudoDestructorExpr>(E)
2501 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2502
2503 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2504 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002505}
2506
Anders Carlsson56c5e332009-08-25 03:49:14 +00002507Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2508 FunctionDecl *FD,
2509 ParmVarDecl *Param) {
2510 if (Param->hasUnparsedDefaultArg()) {
2511 Diag (CallLoc,
2512 diag::err_use_of_default_argument_to_function_declared_later) <<
2513 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002514 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002515 diag::note_default_argument_declared_here);
2516 } else {
2517 if (Param->hasUninstantiatedDefaultArg()) {
2518 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2519
2520 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002521 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002522
Mike Stump1eb44332009-09-09 15:08:12 +00002523 InstantiatingTemplate Inst(*this, CallLoc, Param,
2524 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002525 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002526
John McCallce3ff2b2009-08-25 22:02:44 +00002527 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002528 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002529 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002530
2531 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002532 /*FIXME:EqualLoc*/
2533 UninstExpr->getSourceRange().getBegin()))
2534 return ExprError();
2535 }
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Anders Carlsson56c5e332009-08-25 03:49:14 +00002537 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Anders Carlsson56c5e332009-08-25 03:49:14 +00002539 // If the default expression creates temporaries, we need to
2540 // push them to the current stack of expression temporaries so they'll
2541 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002542 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002543 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002544 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002545 "Can't destroy temporaries in a default argument expr!");
2546 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2547 ExprTemporaries.push_back(E->getTemporary(I));
2548 }
2549 }
2550
2551 // We already type-checked the argument, so we know it works.
2552 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2553}
2554
Douglas Gregor88a35142008-12-22 05:46:06 +00002555/// ConvertArgumentsForCall - Converts the arguments specified in
2556/// Args/NumArgs to the parameter types of the function FDecl with
2557/// function prototype Proto. Call is the call expression itself, and
2558/// Fn is the function expression. For a C++ member function, this
2559/// routine does not attempt to convert the object argument. Returns
2560/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002561bool
2562Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002563 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002564 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002565 Expr **Args, unsigned NumArgs,
2566 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002567 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002568 // assignment, to the types of the corresponding parameter, ...
2569 unsigned NumArgsInProto = Proto->getNumArgs();
2570 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002571 bool Invalid = false;
2572
Douglas Gregor88a35142008-12-22 05:46:06 +00002573 // If too few arguments are available (and we don't have default
2574 // arguments for the remaining parameters), don't make the call.
2575 if (NumArgs < NumArgsInProto) {
2576 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2577 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2578 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2579 // Use default arguments for missing arguments
2580 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002581 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002582 }
2583
2584 // If too many are passed and not variadic, error on the extras and drop
2585 // them.
2586 if (NumArgs > NumArgsInProto) {
2587 if (!Proto->isVariadic()) {
2588 Diag(Args[NumArgsInProto]->getLocStart(),
2589 diag::err_typecheck_call_too_many_args)
2590 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2591 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2592 Args[NumArgs-1]->getLocEnd());
2593 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002594 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002595 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002596 }
2597 NumArgsToCheck = NumArgsInProto;
2598 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002599
Douglas Gregor88a35142008-12-22 05:46:06 +00002600 // Continue to check argument types (even if we have too few/many args).
2601 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2602 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002603
Douglas Gregor88a35142008-12-22 05:46:06 +00002604 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002605 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002606 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002607
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002608 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2609 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002610 PDiag(diag::err_call_incomplete_argument)
2611 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002612 return true;
2613
Douglas Gregor61366e92008-12-24 00:01:03 +00002614 // Pass the argument.
2615 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2616 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00002617
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00002618 if (!ProtoArgType->isReferenceType())
2619 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002620 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002621 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002622
2623 OwningExprResult ArgExpr =
Anders Carlsson56c5e332009-08-25 03:49:14 +00002624 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2625 FDecl, Param);
2626 if (ArgExpr.isInvalid())
2627 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Anders Carlsson56c5e332009-08-25 03:49:14 +00002629 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002630 }
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Douglas Gregor88a35142008-12-22 05:46:06 +00002632 Call->setArg(i, Arg);
2633 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002634
Douglas Gregor88a35142008-12-22 05:46:06 +00002635 // If this is a variadic call, handle args passed through "...".
2636 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002637 VariadicCallType CallType = VariadicFunction;
2638 if (Fn->getType()->isBlockPointerType())
2639 CallType = VariadicBlock; // Block
2640 else if (isa<MemberExpr>(Fn))
2641 CallType = VariadicMethod;
2642
Douglas Gregor88a35142008-12-22 05:46:06 +00002643 // Promote the arguments (C99 6.5.2.2p7).
Eli Friedman3e42ffd2009-11-14 04:43:10 +00002644 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002645 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002646 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002647 Call->setArg(i, Arg);
2648 }
2649 }
2650
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002651 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002652}
2653
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002654/// \brief "Deconstruct" the function argument of a call expression to find
2655/// the underlying declaration (if any), the name of the called function,
2656/// whether argument-dependent lookup is available, whether it has explicit
2657/// template arguments, etc.
2658void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00002659 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002660 DeclarationName &Name,
2661 NestedNameSpecifier *&Qualifier,
2662 SourceRange &QualifierRange,
2663 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00002664 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002665 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00002666 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002667 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002668 Name = DeclarationName();
2669 Qualifier = 0;
2670 QualifierRange = SourceRange();
2671 ArgumentDependentLookup = getLangOptions().CPlusPlus;
John McCall7453ed42009-11-22 00:44:51 +00002672 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002673 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00002674
2675 // Most of the explicit tracking of ArgumentDependentLookup in this
2676 // function can disappear when we handle unresolved
2677 // TemplateIdRefExprs properly.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002678
2679 // If we're directly calling a function, get the appropriate declaration.
2680 // Also, in C++, keep track of whether we should perform argument-dependent
2681 // lookup and whether there were any explicitly-specified template arguments.
2682 while (true) {
2683 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2684 FnExpr = IcExpr->getSubExpr();
2685 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2686 // Parentheses around a function disable ADL
2687 // (C++0x [basic.lookup.argdep]p1).
2688 ArgumentDependentLookup = false;
2689 FnExpr = PExpr->getSubExpr();
2690 } else if (isa<UnaryOperator>(FnExpr) &&
2691 cast<UnaryOperator>(FnExpr)->getOpcode()
2692 == UnaryOperator::AddrOf) {
2693 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002694 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00002695 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
2696 ArgumentDependentLookup = false;
2697 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00002698 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002699 break;
John McCallba135432009-11-21 08:51:07 +00002700 } else if (UnresolvedLookupExpr *UnresLookup
2701 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
2702 Name = UnresLookup->getName();
2703 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
2704 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00002705 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00002706 if ((Qualifier = UnresLookup->getQualifier()))
2707 QualifierRange = UnresLookup->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002708 break;
2709 } else if (TemplateIdRefExpr *TemplateIdRef
2710 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00002711 if (NamedDecl *Function
John McCall7453ed42009-11-22 00:44:51 +00002712 = TemplateIdRef->getTemplateName().getAsTemplateDecl()) {
2713 Name = Function->getDeclName();
John McCallba135432009-11-21 08:51:07 +00002714 Fns.push_back(Function);
John McCall7453ed42009-11-22 00:44:51 +00002715 }
John McCallba135432009-11-21 08:51:07 +00002716 else {
2717 OverloadedFunctionDecl *Overload
2718 = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
John McCall7453ed42009-11-22 00:44:51 +00002719 Name = Overload->getDeclName();
John McCallba135432009-11-21 08:51:07 +00002720 Fns.append(Overload->function_begin(), Overload->function_end());
2721 }
John McCall7453ed42009-11-22 00:44:51 +00002722 Overloaded = true;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002723 HasExplicitTemplateArguments = true;
John McCalld5532b62009-11-23 01:53:49 +00002724 TemplateIdRef->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002725
2726 // C++ [temp.arg.explicit]p6:
2727 // [Note: For simple function names, argument dependent lookup (3.4.2)
2728 // applies even when the function name is not visible within the
2729 // scope of the call. This is because the call still has the syntactic
2730 // form of a function call (3.4.1). But when a function template with
2731 // explicit template arguments is used, the call does not have the
2732 // correct syntactic form unless there is a function template with
2733 // that name visible at the point of the call. If no such name is
2734 // visible, the call is not syntactically well-formed and
2735 // argument-dependent lookup does not apply. If some such name is
2736 // visible, argument dependent lookup applies and additional function
2737 // templates may be found in other namespaces.
2738 //
2739 // The summary of this paragraph is that, if we get to this point and the
2740 // template-id was not a qualified name, then argument-dependent lookup
2741 // is still possible.
2742 if ((Qualifier = TemplateIdRef->getQualifier())) {
2743 ArgumentDependentLookup = false;
2744 QualifierRange = TemplateIdRef->getQualifierRange();
2745 }
2746 break;
2747 } else {
2748 // Any kind of name that does not refer to a declaration (or
2749 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2750 ArgumentDependentLookup = false;
2751 break;
2752 }
2753 }
2754}
2755
Steve Narofff69936d2007-09-16 03:34:24 +00002756/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002757/// This provides the location of the left/right parens and a list of comma
2758/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002759Action::OwningExprResult
2760Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2761 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002762 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002763 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002764
2765 // Since this might be a postfix expression, get rid of ParenListExprs.
2766 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002768 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002769 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002770 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Douglas Gregor88a35142008-12-22 05:46:06 +00002772 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002773 // If this is a pseudo-destructor expression, build the call immediately.
2774 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2775 if (NumArgs > 0) {
2776 // Pseudo-destructor calls should not have any arguments.
2777 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2778 << CodeModificationHint::CreateRemoval(
2779 SourceRange(Args[0]->getLocStart(),
2780 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Douglas Gregora71d8192009-09-04 17:36:40 +00002782 for (unsigned I = 0; I != NumArgs; ++I)
2783 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Douglas Gregora71d8192009-09-04 17:36:40 +00002785 NumArgs = 0;
2786 }
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Douglas Gregora71d8192009-09-04 17:36:40 +00002788 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2789 RParenLoc));
2790 }
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Douglas Gregor17330012009-02-04 15:01:18 +00002792 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002793 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002794 // FIXME: Will need to cache the results of name lookup (including ADL) in
2795 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002796 bool Dependent = false;
2797 if (Fn->isTypeDependent())
2798 Dependent = true;
2799 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2800 Dependent = true;
2801
2802 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002803 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002804 Context.DependentTy, RParenLoc));
2805
2806 // Determine whether this is a call to an object (C++ [over.call.object]).
2807 if (Fn->getType()->isRecordType())
2808 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2809 CommaLocs, RParenLoc));
2810
Douglas Gregorfa047642009-02-04 00:32:51 +00002811 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002812 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2813 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2814 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2815 isa<CXXMethodDecl>(MemDecl) ||
2816 (isa<FunctionTemplateDecl>(MemDecl) &&
2817 isa<CXXMethodDecl>(
2818 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002819 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2820 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002821 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002822
2823 // Determine whether this is a call to a pointer-to-member function.
2824 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2825 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2826 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002827 if (const FunctionProtoType *FPT =
2828 dyn_cast<FunctionProtoType>(BO->getType())) {
2829 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002830
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002831 ExprOwningPtr<CXXMemberCallExpr>
2832 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2833 NumArgs, ResultTy,
2834 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002835
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002836 if (CheckCallReturnType(FPT->getResultType(),
2837 BO->getRHS()->getSourceRange().getBegin(),
2838 TheCall.get(), 0))
2839 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002840
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002841 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2842 RParenLoc))
2843 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002844
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002845 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2846 }
2847 return ExprError(Diag(Fn->getLocStart(),
2848 diag::err_typecheck_call_not_function)
2849 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002850 }
2851 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002852 }
2853
Douglas Gregorfa047642009-02-04 00:32:51 +00002854 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002855 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002856 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00002857 llvm::SmallVector<NamedDecl*,8> Fns;
2858 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00002859 bool Overloaded;
2860 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002861 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00002862 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002863 NestedNameSpecifier *Qualifier = 0;
2864 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00002865 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00002866 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00002867 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002868
John McCall7453ed42009-11-22 00:44:51 +00002869 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
2870 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00002871
John McCall7453ed42009-11-22 00:44:51 +00002872 if (Overloaded || ADL) {
2873#ifndef NDEBUG
2874 if (ADL) {
2875 // To do ADL, we must have found an unqualified name.
2876 assert(UnqualifiedName && "found no unqualified name for ADL");
2877
2878 // We don't perform ADL for implicit declarations of builtins.
2879 // Verify that this was correctly set up.
2880 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
2881 FDecl->getBuiltinID() && FDecl->isImplicit())
2882 assert(0 && "performing ADL for builtin");
2883
2884 // We don't perform ADL in C.
2885 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
2886 }
2887
2888 if (Overloaded) {
2889 // To be overloaded, we must either have multiple functions or
2890 // at least one function template (which is effectively an
2891 // infinite set of functions).
2892 assert((Fns.size() > 1 ||
2893 (Fns.size() == 1 &&
2894 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
2895 && "unrecognized overload situation");
2896 }
2897#endif
2898
2899 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00002900 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00002901 LParenLoc, Args, NumArgs, CommaLocs,
2902 RParenLoc, ADL);
2903 if (!FDecl)
2904 return ExprError();
2905
2906 Fn = FixOverloadedFunctionReference(Fn, FDecl);
2907
2908 NDecl = FDecl;
2909 } else {
2910 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
2911 if (Fns.empty())
2912 NDecl = FDecl = 0;
2913 else {
2914 NDecl = Fns[0];
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002915 FDecl = dyn_cast<FunctionDecl>(NDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002916 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002917 }
Chris Lattner04421082008-04-08 04:40:51 +00002918
2919 // Promote the function operand.
2920 UsualUnaryConversions(Fn);
2921
Chris Lattner925e60d2007-12-28 05:29:59 +00002922 // Make the call expr early, before semantic checks. This guarantees cleanup
2923 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002924 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2925 Args, NumArgs,
2926 Context.BoolTy,
2927 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002928
Steve Naroffdd972f22008-09-05 22:11:13 +00002929 const FunctionType *FuncT;
2930 if (!Fn->getType()->isBlockPointerType()) {
2931 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2932 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002933 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002934 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002935 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2936 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002937 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002938 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002939 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002940 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002941 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002942 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002943 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2944 << Fn->getType() << Fn->getSourceRange());
2945
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002946 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002947 if (CheckCallReturnType(FuncT->getResultType(),
2948 Fn->getSourceRange().getBegin(), TheCall.get(),
2949 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002950 return ExprError();
2951
Chris Lattner925e60d2007-12-28 05:29:59 +00002952 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002953 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002954
Douglas Gregor72564e72009-02-26 23:50:07 +00002955 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002956 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002957 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002958 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002959 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002960 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002961
Douglas Gregor74734d52009-04-02 15:37:10 +00002962 if (FDecl) {
2963 // Check if we have too few/too many template arguments, based
2964 // on our knowledge of the function definition.
2965 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002966 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002967 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002968 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002969 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2970 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2971 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2972 }
2973 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002974 }
2975
Steve Naroffb291ab62007-08-28 23:30:39 +00002976 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002977 for (unsigned i = 0; i != NumArgs; i++) {
2978 Expr *Arg = Args[i];
2979 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002980 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2981 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002982 PDiag(diag::err_call_incomplete_argument)
2983 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002984 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002985 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002986 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002988
Douglas Gregor88a35142008-12-22 05:46:06 +00002989 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2990 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002991 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2992 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002993
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002994 // Check for sentinels
2995 if (NDecl)
2996 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Chris Lattner59907c42007-08-10 20:18:51 +00002998 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00002999 if (FDecl) {
3000 if (CheckFunctionCall(FDecl, TheCall.get()))
3001 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003003 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003004 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3005 } else if (NDecl) {
3006 if (CheckBlockCall(NDecl, TheCall.get()))
3007 return ExprError();
3008 }
Chris Lattner59907c42007-08-10 20:18:51 +00003009
Anders Carlssonec74c592009-08-16 03:06:32 +00003010 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003011}
3012
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003013Action::OwningExprResult
3014Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3015 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003016 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003017 //FIXME: Preserve type source info.
3018 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003019 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003020 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003021 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003022
Eli Friedman6223c222008-05-20 05:22:08 +00003023 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003024 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003025 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3026 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003027 } else if (!literalType->isDependentType() &&
3028 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003029 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003030 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003031 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003032 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003033
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003034 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003035 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003036 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003037
Chris Lattner371f2582008-12-04 23:50:19 +00003038 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003039 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003040 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003041 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003042 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003043 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003044 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003045 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003046}
3047
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003048Action::OwningExprResult
3049Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003050 SourceLocation RBraceLoc) {
3051 unsigned NumInit = initlist.size();
3052 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003053
Steve Naroff08d92e42007-09-15 18:49:24 +00003054 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003055 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003056
Mike Stumpeed9cac2009-02-19 03:04:26 +00003057 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003058 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003059 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003060 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003061}
3062
Anders Carlsson82debc72009-10-18 18:12:03 +00003063static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3064 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003065 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003066 return CastExpr::CK_NoOp;
3067
3068 if (SrcTy->hasPointerRepresentation()) {
3069 if (DestTy->hasPointerRepresentation())
3070 return CastExpr::CK_BitCast;
3071 if (DestTy->isIntegerType())
3072 return CastExpr::CK_PointerToIntegral;
3073 }
3074
3075 if (SrcTy->isIntegerType()) {
3076 if (DestTy->isIntegerType())
3077 return CastExpr::CK_IntegralCast;
3078 if (DestTy->hasPointerRepresentation())
3079 return CastExpr::CK_IntegralToPointer;
3080 if (DestTy->isRealFloatingType())
3081 return CastExpr::CK_IntegralToFloating;
3082 }
3083
3084 if (SrcTy->isRealFloatingType()) {
3085 if (DestTy->isRealFloatingType())
3086 return CastExpr::CK_FloatingCast;
3087 if (DestTy->isIntegerType())
3088 return CastExpr::CK_FloatingToIntegral;
3089 }
3090
3091 // FIXME: Assert here.
3092 // assert(false && "Unhandled cast combination!");
3093 return CastExpr::CK_Unknown;
3094}
3095
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003096/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003097bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003098 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003099 CXXMethodDecl *& ConversionDecl,
3100 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003101 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003102 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3103 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003104
Eli Friedman199ea952009-08-15 19:02:19 +00003105 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003106
3107 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3108 // type needs to be scalar.
3109 if (castType->isVoidType()) {
3110 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003111 Kind = CastExpr::CK_ToVoid;
3112 return false;
3113 }
3114
3115 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003116 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003117 (castType->isStructureType() || castType->isUnionType())) {
3118 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003119 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003120 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3121 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003122 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003123 return false;
3124 }
3125
3126 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003127 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003128 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003129 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003130 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003131 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003132 if (Context.hasSameUnqualifiedType(Field->getType(),
3133 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003134 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3135 << castExpr->getSourceRange();
3136 break;
3137 }
3138 }
3139 if (Field == FieldEnd)
3140 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3141 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003142 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003143 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003144 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003145
3146 // Reject any other conversions to non-scalar types.
3147 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3148 << castType << castExpr->getSourceRange();
3149 }
3150
3151 if (!castExpr->getType()->isScalarType() &&
3152 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003153 return Diag(castExpr->getLocStart(),
3154 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003155 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003156 }
3157
Anders Carlsson16a89042009-10-16 05:23:41 +00003158 if (castType->isExtVectorType())
3159 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3160
Anders Carlssonc3516322009-10-16 02:48:28 +00003161 if (castType->isVectorType())
3162 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3163 if (castExpr->getType()->isVectorType())
3164 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3165
3166 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003167 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003168
Anders Carlsson16a89042009-10-16 05:23:41 +00003169 if (isa<ObjCSelectorExpr>(castExpr))
3170 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3171
Anders Carlssonc3516322009-10-16 02:48:28 +00003172 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003173 QualType castExprType = castExpr->getType();
3174 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3175 return Diag(castExpr->getLocStart(),
3176 diag::err_cast_pointer_from_non_pointer_int)
3177 << castExprType << castExpr->getSourceRange();
3178 } else if (!castExpr->getType()->isArithmeticType()) {
3179 if (!castType->isIntegralType() && castType->isArithmeticType())
3180 return Diag(castExpr->getLocStart(),
3181 diag::err_cast_pointer_to_non_pointer_int)
3182 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003183 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003184
3185 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003186 return false;
3187}
3188
Anders Carlssonc3516322009-10-16 02:48:28 +00003189bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3190 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003191 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003192
Anders Carlssona64db8f2007-11-27 05:51:55 +00003193 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003194 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003195 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003196 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003197 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003198 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003199 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003200 } else
3201 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003202 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003203 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003204
Anders Carlssonc3516322009-10-16 02:48:28 +00003205 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003206 return false;
3207}
3208
Anders Carlsson16a89042009-10-16 05:23:41 +00003209bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3210 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003211 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003212
3213 QualType SrcTy = CastExpr->getType();
3214
Nate Begeman9b10da62009-06-27 22:05:55 +00003215 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3216 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003217 if (SrcTy->isVectorType()) {
3218 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3219 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3220 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003221 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003222 return false;
3223 }
3224
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003225 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003226 // conversion will take place first from scalar to elt type, and then
3227 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003228 if (SrcTy->isPointerType())
3229 return Diag(R.getBegin(),
3230 diag::err_invalid_conversion_between_vector_and_scalar)
3231 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003232
3233 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3234 ImpCastExprToType(CastExpr, DestElemTy,
3235 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003236
3237 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003238 return false;
3239}
3240
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003241Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003242Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003243 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003244 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003246 assert((Ty != 0) && (Op.get() != 0) &&
3247 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003248
Nate Begeman2ef13e52009-08-10 23:49:36 +00003249 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003250 //FIXME: Preserve type source info.
3251 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Nate Begeman2ef13e52009-08-10 23:49:36 +00003253 // If the Expr being casted is a ParenListExpr, handle it specially.
3254 if (isa<ParenListExpr>(castExpr))
3255 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003256 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003257 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003258 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003259 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003260
3261 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003262 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003263 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003264
Anders Carlsson0aebc812009-09-09 21:33:21 +00003265 if (CastArg.isInvalid())
3266 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003267
Anders Carlsson0aebc812009-09-09 21:33:21 +00003268 castExpr = CastArg.takeAs<Expr>();
3269 } else {
3270 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003273 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003274 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003275 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003276}
3277
Nate Begeman2ef13e52009-08-10 23:49:36 +00003278/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3279/// of comma binary operators.
3280Action::OwningExprResult
3281Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3282 Expr *expr = EA.takeAs<Expr>();
3283 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3284 if (!E)
3285 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Nate Begeman2ef13e52009-08-10 23:49:36 +00003287 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Nate Begeman2ef13e52009-08-10 23:49:36 +00003289 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3290 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3291 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Nate Begeman2ef13e52009-08-10 23:49:36 +00003293 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3294}
3295
3296Action::OwningExprResult
3297Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3298 SourceLocation RParenLoc, ExprArg Op,
3299 QualType Ty) {
3300 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003301
3302 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003303 // then handle it as such.
3304 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3305 if (PE->getNumExprs() == 0) {
3306 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3307 return ExprError();
3308 }
3309
3310 llvm::SmallVector<Expr *, 8> initExprs;
3311 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3312 initExprs.push_back(PE->getExpr(i));
3313
3314 // FIXME: This means that pretty-printing the final AST will produce curly
3315 // braces instead of the original commas.
3316 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003317 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003318 initExprs.size(), RParenLoc);
3319 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003320 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003321 Owned(E));
3322 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003323 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003324 // sequence of BinOp comma operators.
3325 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3326 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3327 }
3328}
3329
3330Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3331 SourceLocation R,
3332 MultiExprArg Val) {
3333 unsigned nexprs = Val.size();
3334 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3335 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3336 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3337 return Owned(expr);
3338}
3339
Sebastian Redl28507842009-02-26 14:39:58 +00003340/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3341/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003342/// C99 6.5.15
3343QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3344 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003345 // C++ is sufficiently different to merit its own checker.
3346 if (getLangOptions().CPlusPlus)
3347 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3348
John McCallb13c87f2009-11-05 09:23:39 +00003349 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3350
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003351 UsualUnaryConversions(Cond);
3352 UsualUnaryConversions(LHS);
3353 UsualUnaryConversions(RHS);
3354 QualType CondTy = Cond->getType();
3355 QualType LHSTy = LHS->getType();
3356 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003357
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003359 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3360 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3361 << CondTy;
3362 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003363 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003364
Chris Lattner70d67a92008-01-06 22:42:25 +00003365 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003366 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3367 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003368
Chris Lattner70d67a92008-01-06 22:42:25 +00003369 // If both operands have arithmetic type, do the usual arithmetic conversions
3370 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003371 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3372 UsualArithmeticConversions(LHS, RHS);
3373 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003374 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003375
Chris Lattner70d67a92008-01-06 22:42:25 +00003376 // If both operands are the same structure or union type, the result is that
3377 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003378 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3379 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003380 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003381 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003382 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003383 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003384 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003385 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003386
Chris Lattner70d67a92008-01-06 22:42:25 +00003387 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003388 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003389 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3390 if (!LHSTy->isVoidType())
3391 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3392 << RHS->getSourceRange();
3393 if (!RHSTy->isVoidType())
3394 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3395 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003396 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3397 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003398 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003399 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003400 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3401 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003402 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003403 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003404 // promote the null to a pointer.
3405 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003406 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003407 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003408 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003409 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003410 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003411 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003412 }
David Chisnall0f436562009-08-17 16:35:33 +00003413 // Handle things like Class and struct objc_class*. Here we case the result
3414 // to the pseudo-builtin, because that will be implicitly cast back to the
3415 // redefinition type if an attempt is made to access its fields.
3416 if (LHSTy->isObjCClassType() &&
3417 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003418 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003419 return LHSTy;
3420 }
3421 if (RHSTy->isObjCClassType() &&
3422 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003423 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003424 return RHSTy;
3425 }
3426 // And the same for struct objc_object* / id
3427 if (LHSTy->isObjCIdType() &&
3428 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003429 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003430 return LHSTy;
3431 }
3432 if (RHSTy->isObjCIdType() &&
3433 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003434 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003435 return RHSTy;
3436 }
Steve Naroff7154a772009-07-01 14:36:47 +00003437 // Handle block pointer types.
3438 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3439 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3440 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3441 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003442 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3443 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003444 return destType;
3445 }
3446 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3447 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3448 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003449 }
Steve Naroff7154a772009-07-01 14:36:47 +00003450 // We have 2 block pointer types.
3451 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3452 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003453 return LHSTy;
3454 }
Steve Naroff7154a772009-07-01 14:36:47 +00003455 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003456 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3457 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003458
Steve Naroff7154a772009-07-01 14:36:47 +00003459 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3460 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003461 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3462 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3463 // In this situation, we assume void* type. No especially good
3464 // reason, but this is what gcc does, and we do have to pick
3465 // to get a consistent AST.
3466 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003467 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3468 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003469 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003470 }
Steve Naroff7154a772009-07-01 14:36:47 +00003471 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003472 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3473 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003474 return LHSTy;
3475 }
Steve Naroff7154a772009-07-01 14:36:47 +00003476 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003477 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Steve Naroff7154a772009-07-01 14:36:47 +00003479 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3480 // Two identical object pointer types are always compatible.
3481 return LHSTy;
3482 }
John McCall183700f2009-09-21 23:43:11 +00003483 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3484 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003485 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003486
Steve Naroff7154a772009-07-01 14:36:47 +00003487 // If both operands are interfaces and either operand can be
3488 // assigned to the other, use that type as the composite
3489 // type. This allows
3490 // xxx ? (A*) a : (B*) b
3491 // where B is a subclass of A.
3492 //
3493 // Additionally, as for assignment, if either type is 'id'
3494 // allow silent coercion. Finally, if the types are
3495 // incompatible then make sure to use 'id' as the composite
3496 // type so the result is acceptable for sending messages to.
3497
3498 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3499 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003500 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003501 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003502 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003503 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003504 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003505 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003506 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003507 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003508 // GCC allows qualified id and any Objective-C type to devolve to
3509 // id. Currently localizing to here until clear this should be
3510 // part of ObjCQualifiedIdTypesAreCompatible.
3511 compositeType = Context.getObjCIdType();
3512 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003513 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003514 } else if (!(compositeType =
3515 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3516 ;
3517 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003518 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3519 << LHSTy << RHSTy
3520 << LHS->getSourceRange() << RHS->getSourceRange();
3521 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003522 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3523 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003524 return incompatTy;
3525 }
3526 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003527 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3528 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003529 return compositeType;
3530 }
Steve Naroffc715e782009-07-29 15:09:39 +00003531 // Check Objective-C object pointer types and 'void *'
3532 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003533 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003534 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003535 QualType destPointee
3536 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003537 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003538 // Add qualifiers if necessary.
3539 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3540 // Promote to void*.
3541 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003542 return destType;
3543 }
3544 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003545 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003546 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003547 QualType destPointee
3548 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003549 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003550 // Add qualifiers if necessary.
3551 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3552 // Promote to void*.
3553 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003554 return destType;
3555 }
Steve Naroff7154a772009-07-01 14:36:47 +00003556 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3557 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3558 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003559 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3560 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003561
3562 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3563 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3564 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003565 QualType destPointee
3566 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003567 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003568 // Add qualifiers if necessary.
3569 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3570 // Promote to void*.
3571 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003572 return destType;
3573 }
3574 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003575 QualType destPointee
3576 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003577 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003578 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003579 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003580 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003581 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003582 return destType;
3583 }
3584
3585 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3586 // Two identical pointer types are always compatible.
3587 return LHSTy;
3588 }
3589 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3590 rhptee.getUnqualifiedType())) {
3591 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3592 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3593 // In this situation, we assume void* type. No especially good
3594 // reason, but this is what gcc does, and we do have to pick
3595 // to get a consistent AST.
3596 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003597 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3598 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003599 return incompatTy;
3600 }
3601 // The pointer types are compatible.
3602 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3603 // differently qualified versions of compatible types, the result type is
3604 // a pointer to an appropriately qualified version of the *composite*
3605 // type.
3606 // FIXME: Need to calculate the composite type.
3607 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003608 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3609 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003610 return LHSTy;
3611 }
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Steve Naroff7154a772009-07-01 14:36:47 +00003613 // GCC compatibility: soften pointer/integer mismatch.
3614 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3615 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3616 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003617 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003618 return RHSTy;
3619 }
3620 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3621 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3622 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003623 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003624 return LHSTy;
3625 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003626
Chris Lattner70d67a92008-01-06 22:42:25 +00003627 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003628 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3629 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003630 return QualType();
3631}
3632
Steve Narofff69936d2007-09-16 03:34:24 +00003633/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003634/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003635Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3636 SourceLocation ColonLoc,
3637 ExprArg Cond, ExprArg LHS,
3638 ExprArg RHS) {
3639 Expr *CondExpr = (Expr *) Cond.get();
3640 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003641
3642 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3643 // was the condition.
3644 bool isLHSNull = LHSExpr == 0;
3645 if (isLHSNull)
3646 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003647
3648 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003649 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003650 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003651 return ExprError();
3652
3653 Cond.release();
3654 LHS.release();
3655 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003656 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003657 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003658 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003659}
3660
Reid Spencer5f016e22007-07-11 17:01:13 +00003661// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003662// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003663// routine is it effectively iqnores the qualifiers on the top level pointee.
3664// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3665// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003666Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003667Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3668 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003669
David Chisnall0f436562009-08-17 16:35:33 +00003670 if ((lhsType->isObjCClassType() &&
3671 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3672 (rhsType->isObjCClassType() &&
3673 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3674 return Compatible;
3675 }
3676
Reid Spencer5f016e22007-07-11 17:01:13 +00003677 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003678 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3679 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003680
Reid Spencer5f016e22007-07-11 17:01:13 +00003681 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003682 lhptee = Context.getCanonicalType(lhptee);
3683 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003684
Chris Lattner5cf216b2008-01-04 18:04:52 +00003685 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003686
3687 // C99 6.5.16.1p1: This following citation is common to constraints
3688 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3689 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003690 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003691 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003692 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003693
Mike Stumpeed9cac2009-02-19 03:04:26 +00003694 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3695 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003696 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003697 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003698 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003699 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003700
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003701 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003702 assert(rhptee->isFunctionType());
3703 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003704 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003705
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003706 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003707 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003708 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003709
3710 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003711 assert(lhptee->isFunctionType());
3712 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003713 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003714 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003715 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003716 lhptee = lhptee.getUnqualifiedType();
3717 rhptee = rhptee.getUnqualifiedType();
3718 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3719 // Check if the pointee types are compatible ignoring the sign.
3720 // We explicitly check for char so that we catch "char" vs
3721 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003722 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003723 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003724 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003725 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003726
3727 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003728 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003729 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003730 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003731
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003732 if (lhptee == rhptee) {
3733 // Types are compatible ignoring the sign. Qualifier incompatibility
3734 // takes priority over sign incompatibility because the sign
3735 // warning can be disabled.
3736 if (ConvTy != Compatible)
3737 return ConvTy;
3738 return IncompatiblePointerSign;
3739 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003740
3741 // If we are a multi-level pointer, it's possible that our issue is simply
3742 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3743 // the eventual target type is the same and the pointers have the same
3744 // level of indirection, this must be the issue.
3745 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3746 do {
3747 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3748 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3749
3750 lhptee = Context.getCanonicalType(lhptee);
3751 rhptee = Context.getCanonicalType(rhptee);
3752 } while (lhptee->isPointerType() && rhptee->isPointerType());
3753
Douglas Gregora4923eb2009-11-16 21:35:15 +00003754 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00003755 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003756 }
3757
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003758 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003759 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003760 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003761 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003762}
3763
Steve Naroff1c7d0672008-09-04 15:10:53 +00003764/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3765/// block pointer types are compatible or whether a block and normal pointer
3766/// are compatible. It is more restrict than comparing two function pointer
3767// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003768Sema::AssignConvertType
3769Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003770 QualType rhsType) {
3771 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003772
Steve Naroff1c7d0672008-09-04 15:10:53 +00003773 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003774 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3775 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003776
Steve Naroff1c7d0672008-09-04 15:10:53 +00003777 // make sure we operate on the canonical type
3778 lhptee = Context.getCanonicalType(lhptee);
3779 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003780
Steve Naroff1c7d0672008-09-04 15:10:53 +00003781 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003782
Steve Naroff1c7d0672008-09-04 15:10:53 +00003783 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003784 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00003785 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003786
Eli Friedman26784c12009-06-08 05:08:54 +00003787 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003788 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003789 return ConvTy;
3790}
3791
Mike Stumpeed9cac2009-02-19 03:04:26 +00003792/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3793/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003794/// pointers. Here are some objectionable examples that GCC considers warnings:
3795///
3796/// int a, *pint;
3797/// short *pshort;
3798/// struct foo *pfoo;
3799///
3800/// pint = pshort; // warning: assignment from incompatible pointer type
3801/// a = pint; // warning: assignment makes integer from pointer without a cast
3802/// pint = a; // warning: assignment makes pointer from integer without a cast
3803/// pint = pfoo; // warning: assignment from incompatible pointer type
3804///
3805/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003806/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003807///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003808Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003809Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003810 // Get canonical types. We're not formatting these types, just comparing
3811 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003812 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3813 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003814
3815 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003816 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003817
David Chisnall0f436562009-08-17 16:35:33 +00003818 if ((lhsType->isObjCClassType() &&
3819 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3820 (rhsType->isObjCClassType() &&
3821 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3822 return Compatible;
3823 }
3824
Douglas Gregor9d293df2008-10-28 00:22:11 +00003825 // If the left-hand side is a reference type, then we are in a
3826 // (rare!) case where we've allowed the use of references in C,
3827 // e.g., as a parameter type in a built-in function. In this case,
3828 // just make sure that the type referenced is compatible with the
3829 // right-hand side type. The caller is responsible for adjusting
3830 // lhsType so that the resulting expression does not have reference
3831 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003832 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003833 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003834 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003835 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003836 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003837 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3838 // to the same ExtVector type.
3839 if (lhsType->isExtVectorType()) {
3840 if (rhsType->isExtVectorType())
3841 return lhsType == rhsType ? Compatible : Incompatible;
3842 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3843 return Compatible;
3844 }
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Nate Begemanbe2341d2008-07-14 18:02:46 +00003846 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003847 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003848 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003849 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003850 if (getLangOptions().LaxVectorConversions &&
3851 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003852 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003853 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003854 }
3855 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003856 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003857
Chris Lattnere8b3e962008-01-04 23:32:24 +00003858 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003859 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003860
Chris Lattner78eca282008-04-07 06:49:41 +00003861 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003862 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003863 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003864
Chris Lattner78eca282008-04-07 06:49:41 +00003865 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003866 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003867
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003868 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003869 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003870 if (lhsType->isVoidPointerType()) // an exception to the rule.
3871 return Compatible;
3872 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003873 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003874 if (rhsType->getAs<BlockPointerType>()) {
3875 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003876 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003877
3878 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003879 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003880 return Compatible;
3881 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003882 return Incompatible;
3883 }
3884
3885 if (isa<BlockPointerType>(lhsType)) {
3886 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003887 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003888
Steve Naroffb4406862008-09-29 18:10:17 +00003889 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003890 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003891 return Compatible;
3892
Steve Naroff1c7d0672008-09-04 15:10:53 +00003893 if (rhsType->isBlockPointerType())
3894 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003895
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003897 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003898 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003899 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003900 return Incompatible;
3901 }
3902
Steve Naroff14108da2009-07-10 23:34:53 +00003903 if (isa<ObjCObjectPointerType>(lhsType)) {
3904 if (rhsType->isIntegerType())
3905 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003907 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003908 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003909 if (rhsType->isVoidPointerType()) // an exception to the rule.
3910 return Compatible;
3911 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003912 }
3913 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003914 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3915 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003916 if (Context.typesAreCompatible(lhsType, rhsType))
3917 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003918 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3919 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003920 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003921 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003922 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003923 if (RHSPT->getPointeeType()->isVoidType())
3924 return Compatible;
3925 }
3926 // Treat block pointers as objects.
3927 if (rhsType->isBlockPointerType())
3928 return Compatible;
3929 return Incompatible;
3930 }
Chris Lattner78eca282008-04-07 06:49:41 +00003931 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003932 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003933 if (lhsType == Context.BoolTy)
3934 return Compatible;
3935
3936 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003937 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003938
Mike Stumpeed9cac2009-02-19 03:04:26 +00003939 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003940 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003941
3942 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003943 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003944 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003945 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003946 }
Steve Naroff14108da2009-07-10 23:34:53 +00003947 if (isa<ObjCObjectPointerType>(rhsType)) {
3948 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3949 if (lhsType == Context.BoolTy)
3950 return Compatible;
3951
3952 if (lhsType->isIntegerType())
3953 return PointerToInt;
3954
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003955 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003956 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003957 if (lhsType->isVoidPointerType()) // an exception to the rule.
3958 return Compatible;
3959 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003960 }
3961 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003962 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003963 return Compatible;
3964 return Incompatible;
3965 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003966
Chris Lattnerfc144e22008-01-04 23:18:45 +00003967 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003968 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003969 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003970 }
3971 return Incompatible;
3972}
3973
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003974/// \brief Constructs a transparent union from an expression that is
3975/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00003976static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003977 QualType UnionType, FieldDecl *Field) {
3978 // Build an initializer list that designates the appropriate member
3979 // of the transparent union.
3980 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3981 &E, 1,
3982 SourceLocation());
3983 Initializer->setType(UnionType);
3984 Initializer->setInitializedFieldInUnion(Field);
3985
3986 // Build a compound literal constructing a value of the transparent
3987 // union type from this initializer list.
3988 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3989 false);
3990}
3991
3992Sema::AssignConvertType
3993Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3994 QualType FromType = rExpr->getType();
3995
Mike Stump1eb44332009-09-09 15:08:12 +00003996 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003997 // transparent_union GCC extension.
3998 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003999 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004000 return Incompatible;
4001
4002 // The field to initialize within the transparent union.
4003 RecordDecl *UD = UT->getDecl();
4004 FieldDecl *InitField = 0;
4005 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004006 for (RecordDecl::field_iterator it = UD->field_begin(),
4007 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004008 it != itend; ++it) {
4009 if (it->getType()->isPointerType()) {
4010 // If the transparent union contains a pointer type, we allow:
4011 // 1) void pointer
4012 // 2) null pointer constant
4013 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004014 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004015 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004016 InitField = *it;
4017 break;
4018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Douglas Gregorce940492009-09-25 04:25:58 +00004020 if (rExpr->isNullPointerConstant(Context,
4021 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004022 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004023 InitField = *it;
4024 break;
4025 }
4026 }
4027
4028 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4029 == Compatible) {
4030 InitField = *it;
4031 break;
4032 }
4033 }
4034
4035 if (!InitField)
4036 return Incompatible;
4037
4038 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4039 return Compatible;
4040}
4041
Chris Lattner5cf216b2008-01-04 18:04:52 +00004042Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004043Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004044 if (getLangOptions().CPlusPlus) {
4045 if (!lhsType->isRecordType()) {
4046 // C++ 5.17p3: If the left operand is not of class type, the
4047 // expression is implicitly converted (C++ 4) to the
4048 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004049 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4050 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004051 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004052 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004053 }
4054
4055 // FIXME: Currently, we fall through and treat C++ classes like C
4056 // structures.
4057 }
4058
Steve Naroff529a4ad2007-11-27 17:58:44 +00004059 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4060 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004061 if ((lhsType->isPointerType() ||
4062 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004063 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004064 && rExpr->isNullPointerConstant(Context,
4065 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004066 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004067 return Compatible;
4068 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004069
Chris Lattner943140e2007-10-16 02:55:40 +00004070 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004071 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004072 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004073 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004074 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004075 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004076 if (!lhsType->isReferenceType())
4077 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004078
Chris Lattner5cf216b2008-01-04 18:04:52 +00004079 Sema::AssignConvertType result =
4080 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004081
Steve Narofff1120de2007-08-24 22:33:52 +00004082 // C99 6.5.16.1p2: The value of the right operand is converted to the
4083 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004084 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4085 // so that we can use references in built-in functions even in C.
4086 // The getNonReferenceType() call makes sure that the resulting expression
4087 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004088 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004089 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4090 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004091 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004092}
4093
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004094QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004095 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004096 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004097 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004098 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004099}
4100
Mike Stumpeed9cac2009-02-19 03:04:26 +00004101inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004102 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004103 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004105 QualType lhsType =
4106 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4107 QualType rhsType =
4108 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004109
Nate Begemanbe2341d2008-07-14 18:02:46 +00004110 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004111 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004112 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004113
Nate Begemanbe2341d2008-07-14 18:02:46 +00004114 // Handle the case of a vector & extvector type of the same size and element
4115 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004116 if (getLangOptions().LaxVectorConversions) {
4117 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004118 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4119 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004120 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004121 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004122 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004123 }
4124 }
4125 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004126
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004127 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4128 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4129 bool swapped = false;
4130 if (rhsType->isExtVectorType()) {
4131 swapped = true;
4132 std::swap(rex, lex);
4133 std::swap(rhsType, lhsType);
4134 }
Mike Stump1eb44332009-09-09 15:08:12 +00004135
Nate Begemandde25982009-06-28 19:12:57 +00004136 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004137 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004138 QualType EltTy = LV->getElementType();
4139 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4140 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004141 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004142 if (swapped) std::swap(rex, lex);
4143 return lhsType;
4144 }
4145 }
4146 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4147 rhsType->isRealFloatingType()) {
4148 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004149 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004150 if (swapped) std::swap(rex, lex);
4151 return lhsType;
4152 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004153 }
4154 }
Mike Stump1eb44332009-09-09 15:08:12 +00004155
Nate Begemandde25982009-06-28 19:12:57 +00004156 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004157 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004158 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004159 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004160 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004161}
4162
Reid Spencer5f016e22007-07-11 17:01:13 +00004163inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004164 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004165 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004166 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004167
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004168 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004169
Steve Naroffa4332e22007-07-17 00:58:39 +00004170 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004171 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004172 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004173}
4174
4175inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004176 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004177 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4178 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4179 return CheckVectorOperands(Loc, lex, rex);
4180 return InvalidOperands(Loc, lex, rex);
4181 }
Steve Naroff90045e82007-07-13 23:32:42 +00004182
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004183 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004184
Steve Naroffa4332e22007-07-17 00:58:39 +00004185 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004186 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004187 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004188}
4189
4190inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004191 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004192 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4193 QualType compType = CheckVectorOperands(Loc, lex, rex);
4194 if (CompLHSTy) *CompLHSTy = compType;
4195 return compType;
4196 }
Steve Naroff49b45262007-07-13 16:58:59 +00004197
Eli Friedmanab3a8522009-03-28 01:22:36 +00004198 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004199
Reid Spencer5f016e22007-07-11 17:01:13 +00004200 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004201 if (lex->getType()->isArithmeticType() &&
4202 rex->getType()->isArithmeticType()) {
4203 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004204 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004205 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004206
Eli Friedmand72d16e2008-05-18 18:08:51 +00004207 // Put any potential pointer into PExp
4208 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004209 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004210 std::swap(PExp, IExp);
4211
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004212 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Eli Friedmand72d16e2008-05-18 18:08:51 +00004214 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004215 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004216
Chris Lattnerb5f15622009-04-24 23:50:08 +00004217 // Check for arithmetic on pointers to incomplete types.
4218 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004219 if (getLangOptions().CPlusPlus) {
4220 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004221 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004222 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004223 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004224
4225 // GNU extension: arithmetic on pointer to void
4226 Diag(Loc, diag::ext_gnu_void_ptr)
4227 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004228 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004229 if (getLangOptions().CPlusPlus) {
4230 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4231 << lex->getType() << lex->getSourceRange();
4232 return QualType();
4233 }
4234
4235 // GNU extension: arithmetic on pointer to function
4236 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4237 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004238 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004239 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004240 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004241 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004242 PExp->getType()->isObjCObjectPointerType()) &&
4243 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004244 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4245 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004246 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004247 return QualType();
4248 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004249 // Diagnose bad cases where we step over interface counts.
4250 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4251 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4252 << PointeeTy << PExp->getSourceRange();
4253 return QualType();
4254 }
Mike Stump1eb44332009-09-09 15:08:12 +00004255
Eli Friedmanab3a8522009-03-28 01:22:36 +00004256 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004257 QualType LHSTy = Context.isPromotableBitField(lex);
4258 if (LHSTy.isNull()) {
4259 LHSTy = lex->getType();
4260 if (LHSTy->isPromotableIntegerType())
4261 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004262 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004263 *CompLHSTy = LHSTy;
4264 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004265 return PExp->getType();
4266 }
4267 }
4268
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004269 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004270}
4271
Chris Lattnereca7be62008-04-07 05:30:13 +00004272// C99 6.5.6
4273QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004274 SourceLocation Loc, QualType* CompLHSTy) {
4275 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4276 QualType compType = CheckVectorOperands(Loc, lex, rex);
4277 if (CompLHSTy) *CompLHSTy = compType;
4278 return compType;
4279 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004280
Eli Friedmanab3a8522009-03-28 01:22:36 +00004281 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004282
Chris Lattner6e4ab612007-12-09 21:53:25 +00004283 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004284
Chris Lattner6e4ab612007-12-09 21:53:25 +00004285 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004286 if (lex->getType()->isArithmeticType()
4287 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004288 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004289 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004290 }
Mike Stump1eb44332009-09-09 15:08:12 +00004291
Chris Lattner6e4ab612007-12-09 21:53:25 +00004292 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004293 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004294 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004295
Douglas Gregore7450f52009-03-24 19:52:54 +00004296 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004297
Douglas Gregore7450f52009-03-24 19:52:54 +00004298 bool ComplainAboutVoid = false;
4299 Expr *ComplainAboutFunc = 0;
4300 if (lpointee->isVoidType()) {
4301 if (getLangOptions().CPlusPlus) {
4302 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4303 << lex->getSourceRange() << rex->getSourceRange();
4304 return QualType();
4305 }
4306
4307 // GNU C extension: arithmetic on pointer to void
4308 ComplainAboutVoid = true;
4309 } else if (lpointee->isFunctionType()) {
4310 if (getLangOptions().CPlusPlus) {
4311 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004312 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004313 return QualType();
4314 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004315
4316 // GNU C extension: arithmetic on pointer to function
4317 ComplainAboutFunc = lex;
4318 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004319 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004320 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004321 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004322 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004323 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004324
Chris Lattnerb5f15622009-04-24 23:50:08 +00004325 // Diagnose bad cases where we step over interface counts.
4326 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4327 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4328 << lpointee << lex->getSourceRange();
4329 return QualType();
4330 }
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Chris Lattner6e4ab612007-12-09 21:53:25 +00004332 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004333 if (rex->getType()->isIntegerType()) {
4334 if (ComplainAboutVoid)
4335 Diag(Loc, diag::ext_gnu_void_ptr)
4336 << lex->getSourceRange() << rex->getSourceRange();
4337 if (ComplainAboutFunc)
4338 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004339 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004340 << ComplainAboutFunc->getSourceRange();
4341
Eli Friedmanab3a8522009-03-28 01:22:36 +00004342 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004343 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004344 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004345
Chris Lattner6e4ab612007-12-09 21:53:25 +00004346 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004347 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004348 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004349
Douglas Gregore7450f52009-03-24 19:52:54 +00004350 // RHS must be a completely-type object type.
4351 // Handle the GNU void* extension.
4352 if (rpointee->isVoidType()) {
4353 if (getLangOptions().CPlusPlus) {
4354 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4355 << lex->getSourceRange() << rex->getSourceRange();
4356 return QualType();
4357 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004358
Douglas Gregore7450f52009-03-24 19:52:54 +00004359 ComplainAboutVoid = true;
4360 } else if (rpointee->isFunctionType()) {
4361 if (getLangOptions().CPlusPlus) {
4362 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004363 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004364 return QualType();
4365 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004366
4367 // GNU extension: arithmetic on pointer to function
4368 if (!ComplainAboutFunc)
4369 ComplainAboutFunc = rex;
4370 } else if (!rpointee->isDependentType() &&
4371 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004372 PDiag(diag::err_typecheck_sub_ptr_object)
4373 << rex->getSourceRange()
4374 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004375 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004376
Eli Friedman88d936b2009-05-16 13:54:38 +00004377 if (getLangOptions().CPlusPlus) {
4378 // Pointee types must be the same: C++ [expr.add]
4379 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4380 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4381 << lex->getType() << rex->getType()
4382 << lex->getSourceRange() << rex->getSourceRange();
4383 return QualType();
4384 }
4385 } else {
4386 // Pointee types must be compatible C99 6.5.6p3
4387 if (!Context.typesAreCompatible(
4388 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4389 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4390 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4391 << lex->getType() << rex->getType()
4392 << lex->getSourceRange() << rex->getSourceRange();
4393 return QualType();
4394 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004395 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004396
Douglas Gregore7450f52009-03-24 19:52:54 +00004397 if (ComplainAboutVoid)
4398 Diag(Loc, diag::ext_gnu_void_ptr)
4399 << lex->getSourceRange() << rex->getSourceRange();
4400 if (ComplainAboutFunc)
4401 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004402 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004403 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004404
4405 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004406 return Context.getPointerDiffType();
4407 }
4408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004409
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004410 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004411}
4412
Chris Lattnereca7be62008-04-07 05:30:13 +00004413// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004414QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004415 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004416 // C99 6.5.7p2: Each of the operands shall have integer type.
4417 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004418 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004419
Nate Begeman2207d792009-10-25 02:26:48 +00004420 // Vector shifts promote their scalar inputs to vector type.
4421 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4422 return CheckVectorOperands(Loc, lex, rex);
4423
Chris Lattnerca5eede2007-12-12 05:47:28 +00004424 // Shifts don't perform usual arithmetic conversions, they just do integer
4425 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004426 QualType LHSTy = Context.isPromotableBitField(lex);
4427 if (LHSTy.isNull()) {
4428 LHSTy = lex->getType();
4429 if (LHSTy->isPromotableIntegerType())
4430 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004431 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004432 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004433 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004434
Chris Lattnerca5eede2007-12-12 05:47:28 +00004435 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004436
Ryan Flynnd0439682009-08-07 16:20:20 +00004437 // Sanity-check shift operands
4438 llvm::APSInt Right;
4439 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004440 if (!rex->isValueDependent() &&
4441 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004442 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004443 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4444 else {
4445 llvm::APInt LeftBits(Right.getBitWidth(),
4446 Context.getTypeSize(lex->getType()));
4447 if (Right.uge(LeftBits))
4448 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4449 }
4450 }
4451
Chris Lattnerca5eede2007-12-12 05:47:28 +00004452 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004453 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004454}
4455
John McCall5dbad3d2009-11-06 08:49:08 +00004456/// \brief Implements -Wsign-compare.
4457///
4458/// \param lex the left-hand expression
4459/// \param rex the right-hand expression
4460/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004461/// \param Equality whether this is an "equality-like" join, which
4462/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004463void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004464 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004465 // Don't warn if we're in an unevaluated context.
4466 if (ExprEvalContext == Unevaluated)
4467 return;
4468
John McCall45aa4552009-11-05 00:40:04 +00004469 QualType lt = lex->getType(), rt = rex->getType();
4470
4471 // Only warn if both operands are integral.
4472 if (!lt->isIntegerType() || !rt->isIntegerType())
4473 return;
4474
Sebastian Redl732429c2009-11-05 21:09:23 +00004475 // If either expression is value-dependent, don't warn. We'll get another
4476 // chance at instantiation time.
4477 if (lex->isValueDependent() || rex->isValueDependent())
4478 return;
4479
John McCall45aa4552009-11-05 00:40:04 +00004480 // The rule is that the signed operand becomes unsigned, so isolate the
4481 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004482 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004483 if (lt->isSignedIntegerType()) {
4484 if (rt->isSignedIntegerType()) return;
4485 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004486 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004487 } else {
4488 if (!rt->isSignedIntegerType()) return;
4489 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004490 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004491 }
4492
John McCall5dbad3d2009-11-06 08:49:08 +00004493 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004494 // then (1) the result type will be signed and (2) the unsigned
4495 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004496 // of the comparison will be exact.
4497 if (Context.getIntWidth(signedOperand->getType()) >
4498 Context.getIntWidth(unsignedOperand->getType()))
4499 return;
4500
John McCall45aa4552009-11-05 00:40:04 +00004501 // If the value is a non-negative integer constant, then the
4502 // signed->unsigned conversion won't change it.
4503 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004504 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004505 assert(value.isSigned() && "result of signed expression not signed");
4506
4507 if (value.isNonNegative())
4508 return;
4509 }
4510
John McCall5dbad3d2009-11-06 08:49:08 +00004511 if (Equality) {
4512 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004513 // constant which cannot collide with a overflowed signed operand,
4514 // then reinterpreting the signed operand as unsigned will not
4515 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004516 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4517 assert(!value.isSigned() && "result of unsigned expression is signed");
4518
4519 // 2's complement: test the top bit.
4520 if (value.isNonNegative())
4521 return;
4522 }
4523 }
4524
John McCallb13c87f2009-11-05 09:23:39 +00004525 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004526 << lex->getType() << rex->getType()
4527 << lex->getSourceRange() << rex->getSourceRange();
4528}
4529
Douglas Gregor0c6db942009-05-04 06:07:12 +00004530// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004531QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004532 unsigned OpaqueOpc, bool isRelational) {
4533 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4534
Nate Begemanbe2341d2008-07-14 18:02:46 +00004535 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004536 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004537
John McCall5dbad3d2009-11-06 08:49:08 +00004538 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4539 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00004540
Chris Lattnera5937dd2007-08-26 01:18:55 +00004541 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004542 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4543 UsualArithmeticConversions(lex, rex);
4544 else {
4545 UsualUnaryConversions(lex);
4546 UsualUnaryConversions(rex);
4547 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004548 QualType lType = lex->getType();
4549 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004550
Mike Stumpaf199f32009-05-07 18:43:07 +00004551 if (!lType->isFloatingType()
4552 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004553 // For non-floating point types, check for self-comparisons of the form
4554 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4555 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004556 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004557 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004558 Expr *LHSStripped = lex->IgnoreParens();
4559 Expr *RHSStripped = rex->IgnoreParens();
4560 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4561 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004562 if (DRL->getDecl() == DRR->getDecl() &&
4563 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004564 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Chris Lattner55660a72009-03-08 19:39:53 +00004566 if (isa<CastExpr>(LHSStripped))
4567 LHSStripped = LHSStripped->IgnoreParenCasts();
4568 if (isa<CastExpr>(RHSStripped))
4569 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Chris Lattner55660a72009-03-08 19:39:53 +00004571 // Warn about comparisons against a string constant (unless the other
4572 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004573 Expr *literalString = 0;
4574 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004575 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004576 !RHSStripped->isNullPointerConstant(Context,
4577 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004578 literalString = lex;
4579 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004580 } else if ((isa<StringLiteral>(RHSStripped) ||
4581 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004582 !LHSStripped->isNullPointerConstant(Context,
4583 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004584 literalString = rex;
4585 literalStringStripped = RHSStripped;
4586 }
4587
4588 if (literalString) {
4589 std::string resultComparison;
4590 switch (Opc) {
4591 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4592 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4593 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4594 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4595 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4596 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4597 default: assert(false && "Invalid comparison operator");
4598 }
4599 Diag(Loc, diag::warn_stringcompare)
4600 << isa<ObjCEncodeExpr>(literalStringStripped)
4601 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004602 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4603 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4604 "strcmp(")
4605 << CodeModificationHint::CreateInsertion(
4606 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004607 resultComparison);
4608 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004609 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004610
Douglas Gregor447b69e2008-11-19 03:25:36 +00004611 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004612 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004613
Chris Lattnera5937dd2007-08-26 01:18:55 +00004614 if (isRelational) {
4615 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004616 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004617 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004618 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004619 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004620 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004621 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004622 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004623
Chris Lattnera5937dd2007-08-26 01:18:55 +00004624 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004625 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004626 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004627
Douglas Gregorce940492009-09-25 04:25:58 +00004628 bool LHSIsNull = lex->isNullPointerConstant(Context,
4629 Expr::NPC_ValueDependentIsNull);
4630 bool RHSIsNull = rex->isNullPointerConstant(Context,
4631 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004632
Chris Lattnera5937dd2007-08-26 01:18:55 +00004633 // All of the following pointer related warnings are GCC extensions, except
4634 // when handling null pointer constants. One day, we can consider making them
4635 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004636 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004637 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004638 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004639 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004640 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004641
Douglas Gregor0c6db942009-05-04 06:07:12 +00004642 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004643 if (LCanPointeeTy == RCanPointeeTy)
4644 return ResultTy;
4645
Douglas Gregor0c6db942009-05-04 06:07:12 +00004646 // C++ [expr.rel]p2:
4647 // [...] Pointer conversions (4.10) and qualification
4648 // conversions (4.4) are performed on pointer operands (or on
4649 // a pointer operand and a null pointer constant) to bring
4650 // them to their composite pointer type. [...]
4651 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004652 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004653 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004654 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004655 if (T.isNull()) {
4656 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4657 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4658 return QualType();
4659 }
4660
Eli Friedman73c39ab2009-10-20 08:27:19 +00004661 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4662 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004663 return ResultTy;
4664 }
Eli Friedman3075e762009-08-23 00:27:47 +00004665 // C99 6.5.9p2 and C99 6.5.8p2
4666 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4667 RCanPointeeTy.getUnqualifiedType())) {
4668 // Valid unless a relational comparison of function pointers
4669 if (isRelational && LCanPointeeTy->isFunctionType()) {
4670 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4671 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4672 }
4673 } else if (!isRelational &&
4674 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4675 // Valid unless comparison between non-null pointer and function pointer
4676 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4677 && !LHSIsNull && !RHSIsNull) {
4678 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4679 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4680 }
4681 } else {
4682 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004683 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004684 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004685 }
Eli Friedman3075e762009-08-23 00:27:47 +00004686 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004687 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004688 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004689 }
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004691 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004692 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004693 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004694 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004695 (lType->isPointerType() ||
4696 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004697 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004698 return ResultTy;
4699 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004700 if (LHSIsNull &&
4701 (rType->isPointerType() ||
4702 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004703 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004704 return ResultTy;
4705 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004706
4707 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004708 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004709 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4710 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004711 // In addition, pointers to members can be compared, or a pointer to
4712 // member and a null pointer constant. Pointer to member conversions
4713 // (4.11) and qualification conversions (4.4) are performed to bring
4714 // them to a common type. If one operand is a null pointer constant,
4715 // the common type is the type of the other operand. Otherwise, the
4716 // common type is a pointer to member type similar (4.4) to the type
4717 // of one of the operands, with a cv-qualification signature (4.4)
4718 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004719 // types.
4720 QualType T = FindCompositePointerType(lex, rex);
4721 if (T.isNull()) {
4722 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4723 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4724 return QualType();
4725 }
Mike Stump1eb44332009-09-09 15:08:12 +00004726
Eli Friedman73c39ab2009-10-20 08:27:19 +00004727 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4728 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004729 return ResultTy;
4730 }
Mike Stump1eb44332009-09-09 15:08:12 +00004731
Douglas Gregor20b3e992009-08-24 17:42:35 +00004732 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004733 if (lType->isNullPtrType() && rType->isNullPtrType())
4734 return ResultTy;
4735 }
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Steve Naroff1c7d0672008-09-04 15:10:53 +00004737 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004738 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004739 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4740 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004741
Steve Naroff1c7d0672008-09-04 15:10:53 +00004742 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004743 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004744 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004745 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004746 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004747 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004748 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004749 }
Steve Naroff59f53942008-09-28 01:11:11 +00004750 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004751 if (!isRelational
4752 && ((lType->isBlockPointerType() && rType->isPointerType())
4753 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004754 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004755 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004756 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004757 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004758 ->getPointeeType()->isVoidType())))
4759 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4760 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004761 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004762 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004763 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004764 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004765
Steve Naroff14108da2009-07-10 23:34:53 +00004766 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004767 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004768 const PointerType *LPT = lType->getAs<PointerType>();
4769 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004770 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004771 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004772 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004773 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004774
Steve Naroffa8069f12008-11-17 19:49:16 +00004775 if (!LPtrToVoid && !RPtrToVoid &&
4776 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004777 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004778 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004779 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004780 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004781 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004782 }
Steve Naroff14108da2009-07-10 23:34:53 +00004783 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004784 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004785 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4786 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004787 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004788 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004789 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004790 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004791 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004792 unsigned DiagID = 0;
4793 if (RHSIsNull) {
4794 if (isRelational)
4795 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4796 } else if (isRelational)
4797 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4798 else
4799 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004800
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004801 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004802 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004803 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004804 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004805 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004806 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004807 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004808 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004809 unsigned DiagID = 0;
4810 if (LHSIsNull) {
4811 if (isRelational)
4812 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4813 } else if (isRelational)
4814 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4815 else
4816 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004817
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004818 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004819 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004820 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004821 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004822 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004823 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004824 }
Steve Naroff39218df2008-09-04 16:56:14 +00004825 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004826 if (!isRelational && RHSIsNull
4827 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004828 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004829 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004830 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004831 if (!isRelational && LHSIsNull
4832 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004833 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004834 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004835 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004836 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004837}
4838
Nate Begemanbe2341d2008-07-14 18:02:46 +00004839/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004840/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004841/// like a scalar comparison, a vector comparison produces a vector of integer
4842/// types.
4843QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004844 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004845 bool isRelational) {
4846 // Check to make sure we're operating on vectors of the same type and width,
4847 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004848 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004849 if (vType.isNull())
4850 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004851
Nate Begemanbe2341d2008-07-14 18:02:46 +00004852 QualType lType = lex->getType();
4853 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004854
Nate Begemanbe2341d2008-07-14 18:02:46 +00004855 // For non-floating point types, check for self-comparisons of the form
4856 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4857 // often indicate logic errors in the program.
4858 if (!lType->isFloatingType()) {
4859 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4860 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4861 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004862 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004863 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004864
Nate Begemanbe2341d2008-07-14 18:02:46 +00004865 // Check for comparisons of floating point operands using != and ==.
4866 if (!isRelational && lType->isFloatingType()) {
4867 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004868 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004869 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004870
Nate Begemanbe2341d2008-07-14 18:02:46 +00004871 // Return the type for the comparison, which is the same as vector type for
4872 // integer vectors, or an integer type of identical size and number of
4873 // elements for floating point vectors.
4874 if (lType->isIntegerType())
4875 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004876
John McCall183700f2009-09-21 23:43:11 +00004877 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004878 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004879 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004880 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004881 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004882 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4883
Mike Stumpeed9cac2009-02-19 03:04:26 +00004884 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004885 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004886 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4887}
4888
Reid Spencer5f016e22007-07-11 17:01:13 +00004889inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004890 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004891 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004892 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004893
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004894 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004895
Steve Naroffa4332e22007-07-17 00:58:39 +00004896 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004897 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004898 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004899}
4900
4901inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004902 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004903 UsualUnaryConversions(lex);
4904 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004905
Anders Carlsson04905012009-10-16 01:44:21 +00004906 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4907 return InvalidOperands(Loc, lex, rex);
4908
4909 if (Context.getLangOptions().CPlusPlus) {
4910 // C++ [expr.log.and]p2
4911 // C++ [expr.log.or]p2
4912 return Context.BoolTy;
4913 }
4914
4915 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004916}
4917
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004918/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4919/// is a read-only property; return true if so. A readonly property expression
4920/// depends on various declarations and thus must be treated specially.
4921///
Mike Stump1eb44332009-09-09 15:08:12 +00004922static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004923 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4924 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4925 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4926 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004927 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004928 BaseType->getAsObjCInterfacePointerType())
4929 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4930 if (S.isPropertyReadonly(PDecl, IFace))
4931 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004932 }
4933 }
4934 return false;
4935}
4936
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004937/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4938/// emit an error and return true. If so, return false.
4939static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004940 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004941 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004942 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004943 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4944 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004945 if (IsLV == Expr::MLV_Valid)
4946 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004947
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004948 unsigned Diag = 0;
4949 bool NeedType = false;
4950 switch (IsLV) { // C99 6.5.16p2
4951 default: assert(0 && "Unknown result from isModifiableLvalue!");
4952 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004953 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004954 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4955 NeedType = true;
4956 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004957 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004958 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4959 NeedType = true;
4960 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004961 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004962 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4963 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004964 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004965 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4966 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004967 case Expr::MLV_IncompleteType:
4968 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004969 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004970 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4971 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004972 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004973 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4974 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004975 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004976 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4977 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004978 case Expr::MLV_ReadonlyProperty:
4979 Diag = diag::error_readonly_property_assignment;
4980 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004981 case Expr::MLV_NoSetterProperty:
4982 Diag = diag::error_nosetter_property_assignment;
4983 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004984 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004985
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004986 SourceRange Assign;
4987 if (Loc != OrigLoc)
4988 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004989 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004990 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004991 else
Mike Stump1eb44332009-09-09 15:08:12 +00004992 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004993 return true;
4994}
4995
4996
4997
4998// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004999QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5000 SourceLocation Loc,
5001 QualType CompoundType) {
5002 // Verify that LHS is a modifiable lvalue, and emit error if not.
5003 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005004 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005005
5006 QualType LHSType = LHS->getType();
5007 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005008
Chris Lattner5cf216b2008-01-04 18:04:52 +00005009 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005010 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005011 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005012 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005013 // Special case of NSObject attributes on c-style pointer types.
5014 if (ConvTy == IncompatiblePointer &&
5015 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005016 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005017 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005018 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005019 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005020
Chris Lattner2c156472008-08-21 18:04:13 +00005021 // If the RHS is a unary plus or minus, check to see if they = and + are
5022 // right next to each other. If so, the user may have typo'd "x =+ 4"
5023 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005024 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005025 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5026 RHSCheck = ICE->getSubExpr();
5027 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5028 if ((UO->getOpcode() == UnaryOperator::Plus ||
5029 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005030 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005031 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005032 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5033 // And there is a space or other character before the subexpr of the
5034 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005035 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5036 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005037 Diag(Loc, diag::warn_not_compound_assign)
5038 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5039 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005040 }
Chris Lattner2c156472008-08-21 18:04:13 +00005041 }
5042 } else {
5043 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005044 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005045 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005046
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005047 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5048 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005049 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005050
Reid Spencer5f016e22007-07-11 17:01:13 +00005051 // C99 6.5.16p3: The type of an assignment expression is the type of the
5052 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005053 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005054 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5055 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005056 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005057 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005058 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005059}
5060
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005061// C99 6.5.17
5062QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005063 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005064 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005065
5066 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5067 // incomplete in C++).
5068
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005069 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005070}
5071
Steve Naroff49b45262007-07-13 16:58:59 +00005072/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5073/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005074QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5075 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005076 if (Op->isTypeDependent())
5077 return Context.DependentTy;
5078
Chris Lattner3528d352008-11-21 07:05:48 +00005079 QualType ResType = Op->getType();
5080 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005081
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005082 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5083 // Decrement of bool is not allowed.
5084 if (!isInc) {
5085 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5086 return QualType();
5087 }
5088 // Increment of bool sets it to true, but is deprecated.
5089 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5090 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005091 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005092 } else if (ResType->isAnyPointerType()) {
5093 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005094
Chris Lattner3528d352008-11-21 07:05:48 +00005095 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005096 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005097 if (getLangOptions().CPlusPlus) {
5098 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5099 << Op->getSourceRange();
5100 return QualType();
5101 }
5102
5103 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005104 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005105 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005106 if (getLangOptions().CPlusPlus) {
5107 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5108 << Op->getType() << Op->getSourceRange();
5109 return QualType();
5110 }
5111
5112 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005113 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005114 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005115 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005116 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005117 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005118 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005119 // Diagnose bad cases where we step over interface counts.
5120 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5121 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5122 << PointeeTy << Op->getSourceRange();
5123 return QualType();
5124 }
Chris Lattner3528d352008-11-21 07:05:48 +00005125 } else if (ResType->isComplexType()) {
5126 // C99 does not support ++/-- on complex types, we allow as an extension.
5127 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005128 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005129 } else {
5130 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005131 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005132 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005133 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005134 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005135 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005136 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005137 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005138 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005139}
5140
Anders Carlsson369dee42008-02-01 07:15:58 +00005141/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005142/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005143/// where the declaration is needed for type checking. We only need to
5144/// handle cases when the expression references a function designator
5145/// or is an lvalue. Here are some examples:
5146/// - &(x) => x
5147/// - &*****f => f for f a function designator.
5148/// - &s.xx => s
5149/// - &s.zz[1].yy -> s, if zz is an array
5150/// - *(x + 1) -> x, if x is an array
5151/// - &"123"[2] -> 0
5152/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005153static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005154 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005155 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005156 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005157 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005158 // If this is an arrow operator, the address is an offset from
5159 // the base's value, so the object the base refers to is
5160 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005161 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005162 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005163 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005164 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005165 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005166 // FIXME: This code shouldn't be necessary! We should catch the implicit
5167 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005168 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5169 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5170 if (ICE->getSubExpr()->getType()->isArrayType())
5171 return getPrimaryDecl(ICE->getSubExpr());
5172 }
5173 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005174 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005175 case Stmt::UnaryOperatorClass: {
5176 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005177
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005178 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005179 case UnaryOperator::Real:
5180 case UnaryOperator::Imag:
5181 case UnaryOperator::Extension:
5182 return getPrimaryDecl(UO->getSubExpr());
5183 default:
5184 return 0;
5185 }
5186 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005187 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005188 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005189 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005190 // If the result of an implicit cast is an l-value, we care about
5191 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005192 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005193 default:
5194 return 0;
5195 }
5196}
5197
5198/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005199/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005200/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005201/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005202/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005203/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005204/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005205QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005206 // Make sure to ignore parentheses in subsequent checks
5207 op = op->IgnoreParens();
5208
Douglas Gregor9103bb22008-12-17 22:52:20 +00005209 if (op->isTypeDependent())
5210 return Context.DependentTy;
5211
Steve Naroff08f19672008-01-13 17:10:08 +00005212 if (getLangOptions().C99) {
5213 // Implement C99-only parts of addressof rules.
5214 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5215 if (uOp->getOpcode() == UnaryOperator::Deref)
5216 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5217 // (assuming the deref expression is valid).
5218 return uOp->getSubExpr()->getType();
5219 }
5220 // Technically, there should be a check for array subscript
5221 // expressions here, but the result of one is always an lvalue anyway.
5222 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005223 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005224 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005225
Eli Friedman441cf102009-05-16 23:27:50 +00005226 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5227 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005228 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005229 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005230 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005231 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5232 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005233 return QualType();
5234 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005235 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005236 // The operand cannot be a bit-field
5237 Diag(OpLoc, diag::err_typecheck_address_of)
5238 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005239 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005240 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5241 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005242 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005243 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005244 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005245 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005246 } else if (isa<ObjCPropertyRefExpr>(op)) {
5247 // cannot take address of a property expression.
5248 Diag(OpLoc, diag::err_typecheck_address_of)
5249 << "property expression" << op->getSourceRange();
5250 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005251 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5252 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005253 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5254 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005255 } else if (isa<UnresolvedLookupExpr>(op)) {
5256 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005257 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005258 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005259 // with the register storage-class specifier.
5260 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5261 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005262 Diag(OpLoc, diag::err_typecheck_address_of)
5263 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005264 return QualType();
5265 }
John McCallba135432009-11-21 08:51:07 +00005266 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005267 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005268 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005269 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005270 // Could be a pointer to member, though, if there is an explicit
5271 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005272 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005273 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005274 if (Ctx && Ctx->isRecord()) {
5275 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005276 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005277 diag::err_cannot_form_pointer_to_member_of_reference_type)
5278 << FD->getDeclName() << FD->getType();
5279 return QualType();
5280 }
Mike Stump1eb44332009-09-09 15:08:12 +00005281
Sebastian Redlebc07d52009-02-03 20:19:35 +00005282 return Context.getMemberPointerType(op->getType(),
5283 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005284 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005285 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005286 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005287 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005288 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005289 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5290 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005291 return Context.getMemberPointerType(op->getType(),
5292 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5293 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005294 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005295 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005296
Eli Friedman441cf102009-05-16 23:27:50 +00005297 if (lval == Expr::LV_IncompleteVoidType) {
5298 // Taking the address of a void variable is technically illegal, but we
5299 // allow it in cases which are otherwise valid.
5300 // Example: "extern void x; void* y = &x;".
5301 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5302 }
5303
Reid Spencer5f016e22007-07-11 17:01:13 +00005304 // If the operand has type "type", the result has type "pointer to type".
5305 return Context.getPointerType(op->getType());
5306}
5307
Chris Lattner22caddc2008-11-23 09:13:29 +00005308QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005309 if (Op->isTypeDependent())
5310 return Context.DependentTy;
5311
Chris Lattner22caddc2008-11-23 09:13:29 +00005312 UsualUnaryConversions(Op);
5313 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005314
Chris Lattner22caddc2008-11-23 09:13:29 +00005315 // Note that per both C89 and C99, this is always legal, even if ptype is an
5316 // incomplete type or void. It would be possible to warn about dereferencing
5317 // a void pointer, but it's completely well-defined, and such a warning is
5318 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005319 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005320 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005321
John McCall183700f2009-09-21 23:43:11 +00005322 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005323 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005324
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005325 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005326 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005327 return QualType();
5328}
5329
5330static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5331 tok::TokenKind Kind) {
5332 BinaryOperator::Opcode Opc;
5333 switch (Kind) {
5334 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005335 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5336 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005337 case tok::star: Opc = BinaryOperator::Mul; break;
5338 case tok::slash: Opc = BinaryOperator::Div; break;
5339 case tok::percent: Opc = BinaryOperator::Rem; break;
5340 case tok::plus: Opc = BinaryOperator::Add; break;
5341 case tok::minus: Opc = BinaryOperator::Sub; break;
5342 case tok::lessless: Opc = BinaryOperator::Shl; break;
5343 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5344 case tok::lessequal: Opc = BinaryOperator::LE; break;
5345 case tok::less: Opc = BinaryOperator::LT; break;
5346 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5347 case tok::greater: Opc = BinaryOperator::GT; break;
5348 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5349 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5350 case tok::amp: Opc = BinaryOperator::And; break;
5351 case tok::caret: Opc = BinaryOperator::Xor; break;
5352 case tok::pipe: Opc = BinaryOperator::Or; break;
5353 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5354 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5355 case tok::equal: Opc = BinaryOperator::Assign; break;
5356 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5357 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5358 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5359 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5360 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5361 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5362 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5363 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5364 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5365 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5366 case tok::comma: Opc = BinaryOperator::Comma; break;
5367 }
5368 return Opc;
5369}
5370
5371static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5372 tok::TokenKind Kind) {
5373 UnaryOperator::Opcode Opc;
5374 switch (Kind) {
5375 default: assert(0 && "Unknown unary op!");
5376 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5377 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5378 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5379 case tok::star: Opc = UnaryOperator::Deref; break;
5380 case tok::plus: Opc = UnaryOperator::Plus; break;
5381 case tok::minus: Opc = UnaryOperator::Minus; break;
5382 case tok::tilde: Opc = UnaryOperator::Not; break;
5383 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005384 case tok::kw___real: Opc = UnaryOperator::Real; break;
5385 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5386 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5387 }
5388 return Opc;
5389}
5390
Douglas Gregoreaebc752008-11-06 23:29:22 +00005391/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5392/// operator @p Opc at location @c TokLoc. This routine only supports
5393/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005394Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5395 unsigned Op,
5396 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005397 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005398 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005399 // The following two variables are used for compound assignment operators
5400 QualType CompLHSTy; // Type of LHS after promotions for computation
5401 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005402
5403 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005404 case BinaryOperator::Assign:
5405 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5406 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005407 case BinaryOperator::PtrMemD:
5408 case BinaryOperator::PtrMemI:
5409 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5410 Opc == BinaryOperator::PtrMemI);
5411 break;
5412 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005413 case BinaryOperator::Div:
5414 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5415 break;
5416 case BinaryOperator::Rem:
5417 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5418 break;
5419 case BinaryOperator::Add:
5420 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5421 break;
5422 case BinaryOperator::Sub:
5423 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5424 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005425 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005426 case BinaryOperator::Shr:
5427 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5428 break;
5429 case BinaryOperator::LE:
5430 case BinaryOperator::LT:
5431 case BinaryOperator::GE:
5432 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005433 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005434 break;
5435 case BinaryOperator::EQ:
5436 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005437 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005438 break;
5439 case BinaryOperator::And:
5440 case BinaryOperator::Xor:
5441 case BinaryOperator::Or:
5442 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5443 break;
5444 case BinaryOperator::LAnd:
5445 case BinaryOperator::LOr:
5446 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5447 break;
5448 case BinaryOperator::MulAssign:
5449 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005450 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5451 CompLHSTy = CompResultTy;
5452 if (!CompResultTy.isNull())
5453 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005454 break;
5455 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005456 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5457 CompLHSTy = CompResultTy;
5458 if (!CompResultTy.isNull())
5459 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005460 break;
5461 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005462 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5463 if (!CompResultTy.isNull())
5464 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005465 break;
5466 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005467 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5468 if (!CompResultTy.isNull())
5469 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005470 break;
5471 case BinaryOperator::ShlAssign:
5472 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005473 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5474 CompLHSTy = CompResultTy;
5475 if (!CompResultTy.isNull())
5476 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005477 break;
5478 case BinaryOperator::AndAssign:
5479 case BinaryOperator::XorAssign:
5480 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005481 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5482 CompLHSTy = CompResultTy;
5483 if (!CompResultTy.isNull())
5484 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005485 break;
5486 case BinaryOperator::Comma:
5487 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5488 break;
5489 }
5490 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005491 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005492 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005493 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5494 else
5495 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005496 CompLHSTy, CompResultTy,
5497 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005498}
5499
Sebastian Redlaee3c932009-10-27 12:10:02 +00005500/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5501/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005502static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5503 const PartialDiagnostic &PD,
5504 SourceRange ParenRange)
5505{
5506 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5507 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5508 // We can't display the parentheses, so just dig the
5509 // warning/error and return.
5510 Self.Diag(Loc, PD);
5511 return;
5512 }
5513
5514 Self.Diag(Loc, PD)
5515 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5516 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5517}
5518
Sebastian Redlaee3c932009-10-27 12:10:02 +00005519/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5520/// operators are mixed in a way that suggests that the programmer forgot that
5521/// comparison operators have higher precedence. The most typical example of
5522/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005523static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5524 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005525 typedef BinaryOperator BinOp;
5526 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5527 rhsopc = static_cast<BinOp::Opcode>(-1);
5528 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005529 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005530 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005531 rhsopc = BO->getOpcode();
5532
5533 // Subs are not binary operators.
5534 if (lhsopc == -1 && rhsopc == -1)
5535 return;
5536
5537 // Bitwise operations are sometimes used as eager logical ops.
5538 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005539 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5540 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005541 return;
5542
Sebastian Redlaee3c932009-10-27 12:10:02 +00005543 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005544 SuggestParentheses(Self, OpLoc,
5545 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005546 << SourceRange(lhs->getLocStart(), OpLoc)
5547 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5548 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5549 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005550 SuggestParentheses(Self, OpLoc,
5551 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005552 << SourceRange(OpLoc, rhs->getLocEnd())
5553 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5554 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005555}
5556
5557/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5558/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5559/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5560static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5561 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005562 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005563 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5564}
5565
Reid Spencer5f016e22007-07-11 17:01:13 +00005566// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005567Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5568 tok::TokenKind Kind,
5569 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005570 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005571 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005572
Steve Narofff69936d2007-09-16 03:34:24 +00005573 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5574 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005575
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005576 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5577 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5578
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005579 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5580}
5581
5582Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5583 BinaryOperator::Opcode Opc,
5584 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005585 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005586 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005587 rhs->getType()->isOverloadableType())) {
5588 // Find all of the overloaded operators visible from this
5589 // point. We perform both an operator-name lookup from the local
5590 // scope and an argument-dependent lookup based on the types of
5591 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005592 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005593 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5594 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005595 if (S)
5596 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5597 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00005598 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005599 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005600 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005601 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005602 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005603
Douglas Gregor063daf62009-03-13 18:40:31 +00005604 // Build the (potentially-overloaded, potentially-dependent)
5605 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005606 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005607 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005608
Douglas Gregoreaebc752008-11-06 23:29:22 +00005609 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005610 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005611}
5612
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005613Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005614 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005615 ExprArg InputArg) {
5616 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005617
Mike Stump390b4cc2009-05-16 07:39:55 +00005618 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005619 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005620 QualType resultType;
5621 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005622 case UnaryOperator::OffsetOf:
5623 assert(false && "Invalid unary operator");
5624 break;
5625
Reid Spencer5f016e22007-07-11 17:01:13 +00005626 case UnaryOperator::PreInc:
5627 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005628 case UnaryOperator::PostInc:
5629 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005630 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005631 Opc == UnaryOperator::PreInc ||
5632 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005633 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005634 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005635 resultType = CheckAddressOfOperand(Input, OpLoc);
5636 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005637 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005638 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005639 resultType = CheckIndirectionOperand(Input, OpLoc);
5640 break;
5641 case UnaryOperator::Plus:
5642 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005643 UsualUnaryConversions(Input);
5644 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005645 if (resultType->isDependentType())
5646 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005647 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5648 break;
5649 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5650 resultType->isEnumeralType())
5651 break;
5652 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5653 Opc == UnaryOperator::Plus &&
5654 resultType->isPointerType())
5655 break;
5656
Sebastian Redl0eb23302009-01-19 00:08:26 +00005657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5658 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005659 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005660 UsualUnaryConversions(Input);
5661 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005662 if (resultType->isDependentType())
5663 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005664 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5665 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5666 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005667 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005668 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005669 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5671 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005672 break;
5673 case UnaryOperator::LNot: // logical negation
5674 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005675 DefaultFunctionArrayConversion(Input);
5676 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005677 if (resultType->isDependentType())
5678 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005679 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5681 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005682 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005683 // In C++, it's bool. C++ 5.3.1p8
5684 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005685 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005686 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005687 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005688 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005689 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005690 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005691 resultType = Input->getType();
5692 break;
5693 }
5694 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005695 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005696
5697 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005698 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005699}
5700
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005701Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5702 UnaryOperator::Opcode Opc,
5703 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005704 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00005705 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5706 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005707 // Find all of the overloaded operators visible from this
5708 // point. We perform both an operator-name lookup from the local
5709 // scope and an argument-dependent lookup based on the types of
5710 // the arguments.
5711 FunctionSet Functions;
5712 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5713 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005714 if (S)
5715 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5716 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005717 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005718 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005719 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005720 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005721
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005722 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5723 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005724
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005725 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5726}
5727
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005728// Unary Operators. 'Tok' is the token for the operator.
5729Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5730 tok::TokenKind Op, ExprArg input) {
5731 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5732}
5733
Steve Naroff1b273c42007-09-16 14:56:35 +00005734/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005735Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5736 SourceLocation LabLoc,
5737 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005738 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005739 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005740
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005741 // If we haven't seen this label yet, create a forward reference. It
5742 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005743 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005744 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005745
Reid Spencer5f016e22007-07-11 17:01:13 +00005746 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005747 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5748 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005749}
5750
Sebastian Redlf53597f2009-03-15 17:47:39 +00005751Sema::OwningExprResult
5752Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5753 SourceLocation RPLoc) { // "({..})"
5754 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005755 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5756 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5757
Eli Friedmandca2b732009-01-24 23:09:00 +00005758 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005759 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005760 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005761
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005762 // FIXME: there are a variety of strange constraints to enforce here, for
5763 // example, it is not possible to goto into a stmt expression apparently.
5764 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005765
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005766 // If there are sub stmts in the compound stmt, take the type of the last one
5767 // as the type of the stmtexpr.
5768 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005769
Chris Lattner611b2ec2008-07-26 19:51:01 +00005770 if (!Compound->body_empty()) {
5771 Stmt *LastStmt = Compound->body_back();
5772 // If LastStmt is a label, skip down through into the body.
5773 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5774 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005775
Chris Lattner611b2ec2008-07-26 19:51:01 +00005776 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005777 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005778 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005779
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005780 // FIXME: Check that expression type is complete/non-abstract; statement
5781 // expressions are not lvalues.
5782
Sebastian Redlf53597f2009-03-15 17:47:39 +00005783 substmt.release();
5784 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005785}
Steve Naroffd34e9152007-08-01 22:05:33 +00005786
Sebastian Redlf53597f2009-03-15 17:47:39 +00005787Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5788 SourceLocation BuiltinLoc,
5789 SourceLocation TypeLoc,
5790 TypeTy *argty,
5791 OffsetOfComponent *CompPtr,
5792 unsigned NumComponents,
5793 SourceLocation RPLoc) {
5794 // FIXME: This function leaks all expressions in the offset components on
5795 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005796 // FIXME: Preserve type source info.
5797 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005798 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005799
Sebastian Redl28507842009-02-26 14:39:58 +00005800 bool Dependent = ArgTy->isDependentType();
5801
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005802 // We must have at least one component that refers to the type, and the first
5803 // one is known to be a field designator. Verify that the ArgTy represents
5804 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005805 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005806 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005807
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005808 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5809 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005810
Eli Friedman35183ac2009-02-27 06:44:11 +00005811 // Otherwise, create a null pointer as the base, and iteratively process
5812 // the offsetof designators.
5813 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5814 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005815 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005816 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005817
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005818 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5819 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005820 // FIXME: This diagnostic isn't actually visible because the location is in
5821 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005822 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005823 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5824 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005825
Sebastian Redl28507842009-02-26 14:39:58 +00005826 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005827 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005828
John McCalld00f2002009-11-04 03:03:43 +00005829 if (RequireCompleteType(TypeLoc, Res->getType(),
5830 diag::err_offsetof_incomplete_type))
5831 return ExprError();
5832
Sebastian Redl28507842009-02-26 14:39:58 +00005833 // FIXME: Dependent case loses a lot of information here. And probably
5834 // leaks like a sieve.
5835 for (unsigned i = 0; i != NumComponents; ++i) {
5836 const OffsetOfComponent &OC = CompPtr[i];
5837 if (OC.isBrackets) {
5838 // Offset of an array sub-field. TODO: Should we allow vector elements?
5839 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5840 if (!AT) {
5841 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005842 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5843 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005844 }
5845
5846 // FIXME: C++: Verify that operator[] isn't overloaded.
5847
Eli Friedman35183ac2009-02-27 06:44:11 +00005848 // Promote the array so it looks more like a normal array subscript
5849 // expression.
5850 DefaultFunctionArrayConversion(Res);
5851
Sebastian Redl28507842009-02-26 14:39:58 +00005852 // C99 6.5.2.1p1
5853 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005854 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005855 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005856 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005857 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005858 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005859
5860 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5861 OC.LocEnd);
5862 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005863 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005864
Ted Kremenek6217b802009-07-29 21:53:49 +00005865 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005866 if (!RC) {
5867 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005868 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5869 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005870 }
Chris Lattner704fe352007-08-30 17:59:59 +00005871
Sebastian Redl28507842009-02-26 14:39:58 +00005872 // Get the decl corresponding to this.
5873 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005874 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005875 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005876 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5877 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5878 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005879 DidWarnAboutNonPOD = true;
5880 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005881 }
Mike Stump1eb44332009-09-09 15:08:12 +00005882
John McCalla24dc2e2009-11-17 02:14:36 +00005883 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5884 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00005885
Sebastian Redl28507842009-02-26 14:39:58 +00005886 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005887 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005888 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005889 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005890 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5891 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005892
Sebastian Redl28507842009-02-26 14:39:58 +00005893 // FIXME: C++: Verify that MemberDecl isn't a static field.
5894 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005895 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005896 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00005897 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005898 } else {
5899 // MemberDecl->getType() doesn't get the right qualifiers, but it
5900 // doesn't matter here.
5901 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5902 MemberDecl->getType().getNonReferenceType());
5903 }
Sebastian Redl28507842009-02-26 14:39:58 +00005904 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005905 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005906
Sebastian Redlf53597f2009-03-15 17:47:39 +00005907 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5908 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005909}
5910
5911
Sebastian Redlf53597f2009-03-15 17:47:39 +00005912Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5913 TypeTy *arg1,TypeTy *arg2,
5914 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005915 // FIXME: Preserve type source info.
5916 QualType argT1 = GetTypeFromParser(arg1);
5917 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005918
Steve Naroffd34e9152007-08-01 22:05:33 +00005919 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005920
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005921 if (getLangOptions().CPlusPlus) {
5922 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5923 << SourceRange(BuiltinLoc, RPLoc);
5924 return ExprError();
5925 }
5926
Sebastian Redlf53597f2009-03-15 17:47:39 +00005927 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5928 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005929}
5930
Sebastian Redlf53597f2009-03-15 17:47:39 +00005931Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5932 ExprArg cond,
5933 ExprArg expr1, ExprArg expr2,
5934 SourceLocation RPLoc) {
5935 Expr *CondExpr = static_cast<Expr*>(cond.get());
5936 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5937 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005938
Steve Naroffd04fdd52007-08-03 21:21:27 +00005939 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5940
Sebastian Redl28507842009-02-26 14:39:58 +00005941 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005942 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005943 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005944 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005945 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005946 } else {
5947 // The conditional expression is required to be a constant expression.
5948 llvm::APSInt condEval(32);
5949 SourceLocation ExpLoc;
5950 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005951 return ExprError(Diag(ExpLoc,
5952 diag::err_typecheck_choose_expr_requires_constant)
5953 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005954
Sebastian Redl28507842009-02-26 14:39:58 +00005955 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5956 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00005957 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5958 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00005959 }
5960
Sebastian Redlf53597f2009-03-15 17:47:39 +00005961 cond.release(); expr1.release(); expr2.release();
5962 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00005963 resType, RPLoc,
5964 resType->isDependentType(),
5965 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005966}
5967
Steve Naroff4eb206b2008-09-03 18:15:37 +00005968//===----------------------------------------------------------------------===//
5969// Clang Extensions.
5970//===----------------------------------------------------------------------===//
5971
5972/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005973void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005974 // Analyze block parameters.
5975 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005976
Steve Naroff4eb206b2008-09-03 18:15:37 +00005977 // Add BSI to CurBlock.
5978 BSI->PrevBlockInfo = CurBlock;
5979 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005980
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005981 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005982 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005983 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00005984 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005985 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5986 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005987
Steve Naroff090276f2008-10-10 01:28:17 +00005988 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005989 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005990}
5991
Mike Stump98eb8a72009-02-04 22:31:32 +00005992void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005993 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005994
5995 if (ParamInfo.getNumTypeObjects() == 0
5996 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005997 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005998 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5999
Mike Stump4eeab842009-04-28 01:10:27 +00006000 if (T->isArrayType()) {
6001 Diag(ParamInfo.getSourceRange().getBegin(),
6002 diag::err_block_returns_array);
6003 return;
6004 }
6005
Mike Stump98eb8a72009-02-04 22:31:32 +00006006 // The parameter list is optional, if there was none, assume ().
6007 if (!T->isFunctionType())
6008 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6009
6010 CurBlock->hasPrototype = true;
6011 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006012 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006013 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006014 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006015 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006016 // FIXME: remove the attribute.
6017 }
John McCall183700f2009-09-21 23:43:11 +00006018 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006019
Chris Lattner9097af12009-04-11 19:27:54 +00006020 // Do not allow returning a objc interface by-value.
6021 if (RetTy->isObjCInterfaceType()) {
6022 Diag(ParamInfo.getSourceRange().getBegin(),
6023 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6024 return;
6025 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006026 return;
6027 }
6028
Steve Naroff4eb206b2008-09-03 18:15:37 +00006029 // Analyze arguments to block.
6030 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6031 "Not a function declarator!");
6032 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006033
Steve Naroff090276f2008-10-10 01:28:17 +00006034 CurBlock->hasPrototype = FTI.hasPrototype;
6035 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006036
Steve Naroff4eb206b2008-09-03 18:15:37 +00006037 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6038 // no arguments, not a function that takes a single void argument.
6039 if (FTI.hasPrototype &&
6040 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006041 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6042 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006043 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006044 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006045 } else if (FTI.hasPrototype) {
6046 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006047 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006048 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006049 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006050 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006051 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006052 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006053 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006054 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6055 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6056 // If this has an identifier, add it to the scope stack.
6057 if ((*AI)->getIdentifier())
6058 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006059
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006060 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006061 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006062 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006063 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006064 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006065 // FIXME: remove the attribute.
6066 }
Mike Stump1eb44332009-09-09 15:08:12 +00006067
Chris Lattner9097af12009-04-11 19:27:54 +00006068 // Analyze the return type.
6069 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006070 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006071
Chris Lattner9097af12009-04-11 19:27:54 +00006072 // Do not allow returning a objc interface by-value.
6073 if (RetTy->isObjCInterfaceType()) {
6074 Diag(ParamInfo.getSourceRange().getBegin(),
6075 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6076 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006077 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006078}
6079
6080/// ActOnBlockError - If there is an error parsing a block, this callback
6081/// is invoked to pop the information about the block from the action impl.
6082void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6083 // Ensure that CurBlock is deleted.
6084 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006085
Chris Lattner17a78302009-04-19 05:28:12 +00006086 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6087
Steve Naroff4eb206b2008-09-03 18:15:37 +00006088 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006089 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006090 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006091 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006092}
6093
6094/// ActOnBlockStmtExpr - This is called when the body of a block statement
6095/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006096Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6097 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006098 // If blocks are disabled, emit an error.
6099 if (!LangOpts.Blocks)
6100 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006101
Steve Naroff4eb206b2008-09-03 18:15:37 +00006102 // Ensure that CurBlock is deleted.
6103 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006104
Steve Naroff090276f2008-10-10 01:28:17 +00006105 PopDeclContext();
6106
Steve Naroff4eb206b2008-09-03 18:15:37 +00006107 // Pop off CurBlock, handle nested blocks.
6108 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006109
Steve Naroff4eb206b2008-09-03 18:15:37 +00006110 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006111 if (!BSI->ReturnType.isNull())
6112 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006113
Steve Naroff4eb206b2008-09-03 18:15:37 +00006114 llvm::SmallVector<QualType, 8> ArgTypes;
6115 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6116 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006117
Mike Stump56925862009-07-28 22:04:01 +00006118 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006119 QualType BlockTy;
6120 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006121 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6122 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006123 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006124 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006125 BSI->isVariadic, 0, false, false, 0, 0,
6126 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006127
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006128 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006129 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006130 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006131
Chris Lattner17a78302009-04-19 05:28:12 +00006132 // If needed, diagnose invalid gotos and switches in the block.
6133 if (CurFunctionNeedsScopeChecking)
6134 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6135 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006136
Anders Carlssone9146f22009-05-01 19:49:17 +00006137 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006138 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006139 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6140 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006141}
6142
Sebastian Redlf53597f2009-03-15 17:47:39 +00006143Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6144 ExprArg expr, TypeTy *type,
6145 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006146 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006147 Expr *E = static_cast<Expr*>(expr.get());
6148 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006149
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006150 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006151
6152 // Get the va_list type
6153 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006154 if (VaListType->isArrayType()) {
6155 // Deal with implicit array decay; for example, on x86-64,
6156 // va_list is an array, but it's supposed to decay to
6157 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006158 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006159 // Make sure the input expression also decays appropriately.
6160 UsualUnaryConversions(E);
6161 } else {
6162 // Otherwise, the va_list argument must be an l-value because
6163 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006164 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006165 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006166 return ExprError();
6167 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006168
Douglas Gregordd027302009-05-19 23:10:31 +00006169 if (!E->isTypeDependent() &&
6170 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006171 return ExprError(Diag(E->getLocStart(),
6172 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006173 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006174 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006175
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006176 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006177 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006178
Sebastian Redlf53597f2009-03-15 17:47:39 +00006179 expr.release();
6180 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6181 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006182}
6183
Sebastian Redlf53597f2009-03-15 17:47:39 +00006184Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006185 // The type of __null will be int or long, depending on the size of
6186 // pointers on the target.
6187 QualType Ty;
6188 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6189 Ty = Context.IntTy;
6190 else
6191 Ty = Context.LongTy;
6192
Sebastian Redlf53597f2009-03-15 17:47:39 +00006193 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006194}
6195
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006196static void
6197MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6198 QualType DstType,
6199 Expr *SrcExpr,
6200 CodeModificationHint &Hint) {
6201 if (!SemaRef.getLangOptions().ObjC1)
6202 return;
6203
6204 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6205 if (!PT)
6206 return;
6207
6208 // Check if the destination is of type 'id'.
6209 if (!PT->isObjCIdType()) {
6210 // Check if the destination is the 'NSString' interface.
6211 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6212 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6213 return;
6214 }
6215
6216 // Strip off any parens and casts.
6217 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6218 if (!SL || SL->isWide())
6219 return;
6220
6221 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6222}
6223
Chris Lattner5cf216b2008-01-04 18:04:52 +00006224bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6225 SourceLocation Loc,
6226 QualType DstType, QualType SrcType,
6227 Expr *SrcExpr, const char *Flavor) {
6228 // Decode the result (notice that AST's are still created for extensions).
6229 bool isInvalid = false;
6230 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006231 CodeModificationHint Hint;
6232
Chris Lattner5cf216b2008-01-04 18:04:52 +00006233 switch (ConvTy) {
6234 default: assert(0 && "Unknown conversion type");
6235 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006236 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006237 DiagKind = diag::ext_typecheck_convert_pointer_int;
6238 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006239 case IntToPointer:
6240 DiagKind = diag::ext_typecheck_convert_int_pointer;
6241 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006242 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006243 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006244 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6245 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006246 case IncompatiblePointerSign:
6247 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6248 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006249 case FunctionVoidPointer:
6250 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6251 break;
6252 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006253 // If the qualifiers lost were because we were applying the
6254 // (deprecated) C++ conversion from a string literal to a char*
6255 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6256 // Ideally, this check would be performed in
6257 // CheckPointerTypesForAssignment. However, that would require a
6258 // bit of refactoring (so that the second argument is an
6259 // expression, rather than a type), which should be done as part
6260 // of a larger effort to fix CheckPointerTypesForAssignment for
6261 // C++ semantics.
6262 if (getLangOptions().CPlusPlus &&
6263 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6264 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006265 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6266 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006267 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006268 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006269 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006270 case IntToBlockPointer:
6271 DiagKind = diag::err_int_to_block_pointer;
6272 break;
6273 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006274 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006275 break;
Steve Naroff39579072008-10-14 22:18:38 +00006276 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006277 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006278 // it can give a more specific diagnostic.
6279 DiagKind = diag::warn_incompatible_qualified_id;
6280 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006281 case IncompatibleVectors:
6282 DiagKind = diag::warn_incompatible_vectors;
6283 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006284 case Incompatible:
6285 DiagKind = diag::err_typecheck_convert_incompatible;
6286 isInvalid = true;
6287 break;
6288 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006289
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006290 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006291 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006292 return isInvalid;
6293}
Anders Carlssone21555e2008-11-30 19:50:32 +00006294
Chris Lattner3bf68932009-04-25 21:59:05 +00006295bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006296 llvm::APSInt ICEResult;
6297 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6298 if (Result)
6299 *Result = ICEResult;
6300 return false;
6301 }
6302
Anders Carlssone21555e2008-11-30 19:50:32 +00006303 Expr::EvalResult EvalResult;
6304
Mike Stumpeed9cac2009-02-19 03:04:26 +00006305 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006306 EvalResult.HasSideEffects) {
6307 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6308
6309 if (EvalResult.Diag) {
6310 // We only show the note if it's not the usual "invalid subexpression"
6311 // or if it's actually in a subexpression.
6312 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6313 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6314 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6315 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006316
Anders Carlssone21555e2008-11-30 19:50:32 +00006317 return true;
6318 }
6319
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006320 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6321 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006322
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006323 if (EvalResult.Diag &&
6324 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6325 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006326
Anders Carlssone21555e2008-11-30 19:50:32 +00006327 if (Result)
6328 *Result = EvalResult.Val.getInt();
6329 return false;
6330}
Douglas Gregore0762c92009-06-19 23:52:42 +00006331
Mike Stump1eb44332009-09-09 15:08:12 +00006332Sema::ExpressionEvaluationContext
6333Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006334 // Introduce a new set of potentially referenced declarations to the stack.
6335 if (NewContext == PotentiallyPotentiallyEvaluated)
6336 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump1eb44332009-09-09 15:08:12 +00006337
Douglas Gregorac7610d2009-06-22 20:57:11 +00006338 std::swap(ExprEvalContext, NewContext);
6339 return NewContext;
6340}
6341
Mike Stump1eb44332009-09-09 15:08:12 +00006342void
Douglas Gregorac7610d2009-06-22 20:57:11 +00006343Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6344 ExpressionEvaluationContext NewContext) {
6345 ExprEvalContext = NewContext;
6346
6347 if (OldContext == PotentiallyPotentiallyEvaluated) {
6348 // Mark any remaining declarations in the current position of the stack
6349 // as "referenced". If they were not meant to be referenced, semantic
6350 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6351 PotentiallyReferencedDecls RemainingDecls;
6352 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6353 PotentiallyReferencedDeclStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00006354
Douglas Gregorac7610d2009-06-22 20:57:11 +00006355 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6356 IEnd = RemainingDecls.end();
6357 I != IEnd; ++I)
6358 MarkDeclarationReferenced(I->first, I->second);
6359 }
6360}
Douglas Gregore0762c92009-06-19 23:52:42 +00006361
6362/// \brief Note that the given declaration was referenced in the source code.
6363///
6364/// This routine should be invoke whenever a given declaration is referenced
6365/// in the source code, and where that reference occurred. If this declaration
6366/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6367/// C99 6.9p3), then the declaration will be marked as used.
6368///
6369/// \param Loc the location where the declaration was referenced.
6370///
6371/// \param D the declaration that has been referenced by the source code.
6372void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6373 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006374
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006375 if (D->isUsed())
6376 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006377
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006378 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6379 // template or not. The reason for this is that unevaluated expressions
6380 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6381 // -Wunused-parameters)
6382 if (isa<ParmVarDecl>(D) ||
6383 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006384 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Douglas Gregore0762c92009-06-19 23:52:42 +00006386 // Do not mark anything as "used" within a dependent context; wait for
6387 // an instantiation.
6388 if (CurContext->isDependentContext())
6389 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006390
Douglas Gregorac7610d2009-06-22 20:57:11 +00006391 switch (ExprEvalContext) {
6392 case Unevaluated:
6393 // We are in an expression that is not potentially evaluated; do nothing.
6394 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006395
Douglas Gregorac7610d2009-06-22 20:57:11 +00006396 case PotentiallyEvaluated:
6397 // We are in a potentially-evaluated expression, so this declaration is
6398 // "used"; handle this below.
6399 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006400
Douglas Gregorac7610d2009-06-22 20:57:11 +00006401 case PotentiallyPotentiallyEvaluated:
6402 // We are in an expression that may be potentially evaluated; queue this
6403 // declaration reference until we know whether the expression is
6404 // potentially evaluated.
6405 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6406 return;
6407 }
Mike Stump1eb44332009-09-09 15:08:12 +00006408
Douglas Gregore0762c92009-06-19 23:52:42 +00006409 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006410 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006411 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006412 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6413 if (!Constructor->isUsed())
6414 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006415 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006416 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006417 if (!Constructor->isUsed())
6418 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6419 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006420 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6421 if (Destructor->isImplicit() && !Destructor->isUsed())
6422 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006423
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006424 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6425 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6426 MethodDecl->getOverloadedOperator() == OO_Equal) {
6427 if (!MethodDecl->isUsed())
6428 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6429 }
6430 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006431 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006432 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006433 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006434 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006435 bool AlreadyInstantiated = false;
6436 if (FunctionTemplateSpecializationInfo *SpecInfo
6437 = Function->getTemplateSpecializationInfo()) {
6438 if (SpecInfo->getPointOfInstantiation().isInvalid())
6439 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006440 else if (SpecInfo->getTemplateSpecializationKind()
6441 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006442 AlreadyInstantiated = true;
6443 } else if (MemberSpecializationInfo *MSInfo
6444 = Function->getMemberSpecializationInfo()) {
6445 if (MSInfo->getPointOfInstantiation().isInvalid())
6446 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006447 else if (MSInfo->getTemplateSpecializationKind()
6448 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006449 AlreadyInstantiated = true;
6450 }
6451
6452 if (!AlreadyInstantiated)
6453 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6454 }
6455
Douglas Gregore0762c92009-06-19 23:52:42 +00006456 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006457 Function->setUsed(true);
6458 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006459 }
Mike Stump1eb44332009-09-09 15:08:12 +00006460
Douglas Gregore0762c92009-06-19 23:52:42 +00006461 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006462 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006463 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006464 Var->getInstantiatedFromStaticDataMember()) {
6465 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6466 assert(MSInfo && "Missing member specialization information?");
6467 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6468 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6469 MSInfo->setPointOfInstantiation(Loc);
6470 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6471 }
6472 }
Mike Stump1eb44332009-09-09 15:08:12 +00006473
Douglas Gregore0762c92009-06-19 23:52:42 +00006474 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006475
Douglas Gregore0762c92009-06-19 23:52:42 +00006476 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006477 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006478 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006479}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006480
6481bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6482 CallExpr *CE, FunctionDecl *FD) {
6483 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6484 return false;
6485
6486 PartialDiagnostic Note =
6487 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6488 << FD->getDeclName() : PDiag();
6489 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6490
6491 if (RequireCompleteType(Loc, ReturnType,
6492 FD ?
6493 PDiag(diag::err_call_function_incomplete_return)
6494 << CE->getSourceRange() << FD->getDeclName() :
6495 PDiag(diag::err_call_incomplete_return)
6496 << CE->getSourceRange(),
6497 std::make_pair(NoteLoc, Note)))
6498 return true;
6499
6500 return false;
6501}
6502
John McCall5a881bb2009-10-12 21:59:07 +00006503// Diagnose the common s/=/==/ typo. Note that adding parentheses
6504// will prevent this condition from triggering, which is what we want.
6505void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6506 SourceLocation Loc;
6507
John McCalla52ef082009-11-11 02:41:58 +00006508 unsigned diagnostic = diag::warn_condition_is_assignment;
6509
John McCall5a881bb2009-10-12 21:59:07 +00006510 if (isa<BinaryOperator>(E)) {
6511 BinaryOperator *Op = cast<BinaryOperator>(E);
6512 if (Op->getOpcode() != BinaryOperator::Assign)
6513 return;
6514
John McCallc8d8ac52009-11-12 00:06:05 +00006515 // Greylist some idioms by putting them into a warning subcategory.
6516 if (ObjCMessageExpr *ME
6517 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6518 Selector Sel = ME->getSelector();
6519
John McCallc8d8ac52009-11-12 00:06:05 +00006520 // self = [<foo> init...]
6521 if (isSelfExpr(Op->getLHS())
6522 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6523 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6524
6525 // <foo> = [<bar> nextObject]
6526 else if (Sel.isUnarySelector() &&
6527 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6528 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6529 }
John McCalla52ef082009-11-11 02:41:58 +00006530
John McCall5a881bb2009-10-12 21:59:07 +00006531 Loc = Op->getOperatorLoc();
6532 } else if (isa<CXXOperatorCallExpr>(E)) {
6533 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6534 if (Op->getOperator() != OO_Equal)
6535 return;
6536
6537 Loc = Op->getOperatorLoc();
6538 } else {
6539 // Not an assignment.
6540 return;
6541 }
6542
John McCall5a881bb2009-10-12 21:59:07 +00006543 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006544 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006545
John McCalla52ef082009-11-11 02:41:58 +00006546 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00006547 << E->getSourceRange()
6548 << CodeModificationHint::CreateInsertion(Open, "(")
6549 << CodeModificationHint::CreateInsertion(Close, ")");
6550}
6551
6552bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6553 DiagnoseAssignmentAsCondition(E);
6554
6555 if (!E->isTypeDependent()) {
6556 DefaultFunctionArrayConversion(E);
6557
6558 QualType T = E->getType();
6559
6560 if (getLangOptions().CPlusPlus) {
6561 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6562 return true;
6563 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6564 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6565 << T << E->getSourceRange();
6566 return true;
6567 }
6568 }
6569
6570 return false;
6571}