blob: bf9d099e560f5bf017a8cd02a90373d0a2139d26 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000020#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000023#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000027#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000028#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000029#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000030#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031using namespace clang;
32
David Chisnall9f57c292009-08-17 16:35:33 +000033
Douglas Gregor171c45a2009-02-18 21:56:37 +000034/// \brief Determine whether the use of this declaration is valid, and
35/// emit any corresponding diagnostics.
36///
37/// This routine diagnoses various problems with referencing
38/// declarations that can occur when using a declaration. For example,
39/// it might warn if a deprecated or unavailable declaration is being
40/// used, or produce an error (and return true) if a C++0x deleted
41/// function is being used.
42///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000043/// If IgnoreDeprecated is set to true, this should not want about deprecated
44/// decls.
45///
Douglas Gregor171c45a2009-02-18 21:56:37 +000046/// \returns true if there was an error (this declaration cannot be
47/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000048///
John McCall28a6aea2009-11-04 02:18:39 +000049bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000050 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000051 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000052 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000053 }
54
Chris Lattnera27dd592009-10-25 17:21:40 +000055 // See if the decl is unavailable
56 if (D->getAttr<UnavailableAttr>()) {
57 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
58 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
59 }
60
Douglas Gregor171c45a2009-02-18 21:56:37 +000061 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000063 if (FD->isDeleted()) {
64 Diag(Loc, diag::err_deleted_function_use);
65 Diag(D->getLocation(), diag::note_unavailable_here) << true;
66 return true;
67 }
Douglas Gregorde681d42009-02-24 04:26:15 +000068 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000069
Douglas Gregor171c45a2009-02-18 21:56:37 +000070 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000071}
72
Fariborz Jahanian027b8862009-05-13 18:09:35 +000073/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000074/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000075/// attribute. It warns if call does not have the sentinel argument.
76///
77void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000078 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000079 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000080 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000081 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000082 int sentinelPos = attr->getSentinel();
83 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000084
Mike Stump87c57ac2009-05-16 07:39:55 +000085 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
86 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000087 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000088 bool warnNotEnoughArgs = false;
89 int isMethod = 0;
90 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
91 // skip over named parameters.
92 ObjCMethodDecl::param_iterator P, E = MD->param_end();
93 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
94 if (nullPos)
95 --nullPos;
96 else
97 ++i;
98 }
99 warnNotEnoughArgs = (P != E || i >= NumArgs);
100 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000101 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000102 // skip over named parameters.
103 ObjCMethodDecl::param_iterator P, E = FD->param_end();
104 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
105 if (nullPos)
106 --nullPos;
107 else
108 ++i;
109 }
110 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000111 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000112 // block or function pointer call.
113 QualType Ty = V->getType();
114 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000115 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000116 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
117 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000118 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
119 unsigned NumArgsInProto = Proto->getNumArgs();
120 unsigned k;
121 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
122 if (nullPos)
123 --nullPos;
124 else
125 ++i;
126 }
127 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
128 }
129 if (Ty->isBlockPointerType())
130 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000131 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000132 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000133 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000134 return;
135
136 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000137 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000138 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000139 return;
140 }
141 int sentinel = i;
142 while (sentinelPos > 0 && i < NumArgs-1) {
143 --sentinelPos;
144 ++i;
145 }
146 if (sentinelPos > 0) {
147 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000148 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000149 return;
150 }
151 while (i < NumArgs-1) {
152 ++i;
153 ++sentinel;
154 }
155 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000156 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
157 (!sentinelExpr->getType()->isPointerType() ||
158 !sentinelExpr->isNullPointerConstant(Context,
159 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000160 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 }
163 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000164}
165
Douglas Gregor87f95b02009-02-26 21:00:50 +0000166SourceRange Sema::getExprRange(ExprTy *E) const {
167 Expr *Ex = (Expr *)E;
168 return Ex? Ex->getSourceRange() : SourceRange();
169}
170
Chris Lattner513165e2008-07-25 21:10:04 +0000171//===----------------------------------------------------------------------===//
172// Standard Promotions and Conversions
173//===----------------------------------------------------------------------===//
174
Chris Lattner513165e2008-07-25 21:10:04 +0000175/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
176void Sema::DefaultFunctionArrayConversion(Expr *&E) {
177 QualType Ty = E->getType();
178 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
179
Chris Lattner513165e2008-07-25 21:10:04 +0000180 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000181 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000182 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000183 else if (Ty->isArrayType()) {
184 // In C90 mode, arrays only promote to pointers if the array expression is
185 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
186 // type 'array of type' is converted to an expression that has type 'pointer
187 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
188 // that has type 'array of type' ...". The relevant change is "an lvalue"
189 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000190 //
191 // C++ 4.2p1:
192 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
193 // T" can be converted to an rvalue of type "pointer to T".
194 //
195 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
196 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000197 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
198 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000199 }
Chris Lattner513165e2008-07-25 21:10:04 +0000200}
201
202/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000203/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000204/// sometimes surpressed. For example, the array->pointer conversion doesn't
205/// apply if the array is an argument to the sizeof or address (&) operators.
206/// In these instances, this routine should *not* be called.
207Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
208 QualType Ty = Expr->getType();
209 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000210
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000211 // C99 6.3.1.1p2:
212 //
213 // The following may be used in an expression wherever an int or
214 // unsigned int may be used:
215 // - an object or expression with an integer type whose integer
216 // conversion rank is less than or equal to the rank of int
217 // and unsigned int.
218 // - A bit-field of type _Bool, int, signed int, or unsigned int.
219 //
220 // If an int can represent all values of the original type, the
221 // value is converted to an int; otherwise, it is converted to an
222 // unsigned int. These are called the integer promotions. All
223 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000224 QualType PTy = Context.isPromotableBitField(Expr);
225 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000226 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000227 return Expr;
228 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000229 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000230 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000231 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000232 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000233 }
234
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000235 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000236 return Expr;
237}
238
Chris Lattner2ce500f2008-07-25 22:25:12 +0000239/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000240/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000241/// double. All other argument types are converted by UsualUnaryConversions().
242void Sema::DefaultArgumentPromotion(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000245
Chris Lattner2ce500f2008-07-25 22:25:12 +0000246 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000247 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000248 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000249 return ImpCastExprToType(Expr, Context.DoubleTy,
250 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000251
Chris Lattner2ce500f2008-07-25 22:25:12 +0000252 UsualUnaryConversions(Expr);
253}
254
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000255/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
256/// will warn if the resulting type is not a POD type, and rejects ObjC
257/// interfaces passed by value. This returns true if the argument type is
258/// completely illegal.
259bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000260 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000262 if (Expr->getType()->isObjCInterfaceType() &&
263 DiagRuntimeBehavior(Expr->getLocStart(),
264 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
265 << Expr->getType() << CT))
266 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000267
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000268 if (!Expr->getType()->isPODType() &&
269 DiagRuntimeBehavior(Expr->getLocStart(),
270 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
271 << Expr->getType() << CT))
272 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000273
274 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000275}
276
277
Chris Lattner513165e2008-07-25 21:10:04 +0000278/// UsualArithmeticConversions - Performs various conversions that are common to
279/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000280/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000281/// responsible for emitting appropriate error diagnostics.
282/// FIXME: verify the conversion rules for "complex int" are consistent with
283/// GCC.
284QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
285 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000286 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000287 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000288
289 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000290
Mike Stump11289f42009-09-09 15:08:12 +0000291 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000292 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000293 QualType lhs =
294 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000295 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000296 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000297
298 // If both types are identical, no conversion is needed.
299 if (lhs == rhs)
300 return lhs;
301
302 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
303 // The caller can deal with this (e.g. pointer + int).
304 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
305 return lhs;
306
Douglas Gregord2c2d172009-05-02 00:36:19 +0000307 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000308 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000309 if (!LHSBitfieldPromoteTy.isNull())
310 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000311 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000312 if (!RHSBitfieldPromoteTy.isNull())
313 rhs = RHSBitfieldPromoteTy;
314
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000315 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000316 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000317 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
318 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000319 return destType;
320}
321
Chris Lattner513165e2008-07-25 21:10:04 +0000322//===----------------------------------------------------------------------===//
323// Semantic Analysis for various Expression Types
324//===----------------------------------------------------------------------===//
325
326
Steve Naroff83895f72007-09-16 03:34:24 +0000327/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000328/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
329/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
330/// multiple tokens. However, the common case is that StringToks points to one
331/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000332///
333Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000334Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000335 assert(NumStringToks && "Must have at least one string!");
336
Chris Lattner8a24e582009-01-16 18:51:42 +0000337 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000338 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000339 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000340
Chris Lattner23b7eb62007-06-15 23:05:46 +0000341 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000342 for (unsigned i = 0; i != NumStringToks; ++i)
343 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000344
Chris Lattner36fc8792008-02-11 00:02:17 +0000345 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000346 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000347 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000348
349 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
350 if (getLangOptions().CPlusPlus)
351 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000352
Chris Lattner36fc8792008-02-11 00:02:17 +0000353 // Get an array type for the string, according to C99 6.4.5. This includes
354 // the nul terminator character as well as the string length for pascal
355 // strings.
356 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000357 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000358 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattner5b183d82006-11-10 05:03:26 +0000360 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000361 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000362 Literal.GetStringLength(),
363 Literal.AnyWide, StrTy,
364 &StringTokLocs[0],
365 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000366}
367
Chris Lattner2a9d9892008-10-20 05:16:36 +0000368/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
369/// CurBlock to VD should cause it to be snapshotted (as we do for auto
370/// variables defined outside the block) or false if this is not needed (e.g.
371/// for values inside the block or for globals).
372///
Chris Lattner497d7b02009-04-21 22:26:47 +0000373/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
374/// up-to-date.
375///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000376static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
377 ValueDecl *VD) {
378 // If the value is defined inside the block, we couldn't snapshot it even if
379 // we wanted to.
380 if (CurBlock->TheDecl == VD->getDeclContext())
381 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattner2a9d9892008-10-20 05:16:36 +0000383 // If this is an enum constant or function, it is constant, don't snapshot.
384 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
385 return false;
386
387 // If this is a reference to an extern, static, or global variable, no need to
388 // snapshot it.
389 // FIXME: What about 'const' variables in C++?
390 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000391 if (!Var->hasLocalStorage())
392 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattner497d7b02009-04-21 22:26:47 +0000394 // Blocks that have these can't be constant.
395 CurBlock->hasBlockDeclRefExprs = true;
396
397 // If we have nested blocks, the decl may be declared in an outer block (in
398 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
399 // be defined outside all of the current blocks (in which case the blocks do
400 // all get the bit). Walk the nesting chain.
401 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
402 NextBlock = NextBlock->PrevBlockInfo) {
403 // If we found the defining block for the variable, don't mark the block as
404 // having a reference outside it.
405 if (NextBlock->TheDecl == VD->getDeclContext())
406 break;
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattner497d7b02009-04-21 22:26:47 +0000408 // Otherwise, the DeclRef from the inner block causes the outer one to need
409 // a snapshot as well.
410 NextBlock->hasBlockDeclRefExprs = true;
411 }
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner2a9d9892008-10-20 05:16:36 +0000413 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000414}
415
Chris Lattner2a9d9892008-10-20 05:16:36 +0000416
417
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000418/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000419Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000420Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000421 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
423 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000424 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000425 << D->getDeclName();
426 return ExprError();
427 }
Mike Stump11289f42009-09-09 15:08:12 +0000428
Anders Carlsson946b86d2009-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 Stump11289f42009-09-09 15:08:12 +0000433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000434 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000435 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000436 << D->getIdentifier();
437 return ExprError();
438 }
439 }
440 }
441 }
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000443 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000445 return Owned(DeclRefExpr::Create(Context,
446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
447 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000448 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000449}
450
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000451/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
452/// variable corresponding to the anonymous union or struct whose type
453/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000454static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
455 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000456 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000457 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000458
Mike Stump87c57ac2009-05-16 07:39:55 +0000459 // FIXME: Once Decls are directly linked together, this will be an O(1)
460 // operation rather than a slow walk through DeclContext's vector (which
461 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000462 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000463 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000464 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000465 D != DEnd; ++D) {
466 if (*D == Record) {
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
469 ++D;
470 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000472 return *D;
473 }
474 }
475
476 assert(false && "Missing object for anonymous record");
477 return 0;
478}
479
Douglas Gregord5846a12009-04-15 06:41:24 +0000480/// \brief Given a field that represents a member of an anonymous
481/// struct/union, build the path from that field's context to the
482/// actual member.
483///
484/// Construct the sequence of field member references we'll have to
485/// perform to get to the field in the anonymous union/struct. The
486/// list of members is built from the field outward, so traverse it
487/// backwards to go from an object in the current context to the field
488/// we found.
489///
490/// \returns The variable from which the field access should begin,
491/// for an anonymous struct/union that is not a member of another
492/// class. Otherwise, returns NULL.
493VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
494 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000495 assert(Field->getDeclContext()->isRecord() &&
496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
497 && "Field must be stored inside an anonymous struct or union");
498
Douglas Gregord5846a12009-04-15 06:41:24 +0000499 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000500 VarDecl *BaseObject = 0;
501 DeclContext *Ctx = Field->getDeclContext();
502 do {
503 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000506 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000507 else {
508 BaseObject = cast<VarDecl>(AnonObject);
509 break;
510 }
511 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000512 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000514
515 return BaseObject;
516}
517
518Sema::OwningExprResult
519Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
520 FieldDecl *Field,
521 Expr *BaseObjectExpr,
522 SourceLocation OpLoc) {
523 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000525 AnonFields);
526
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000527 // Build the expression that refers to the base object, from
528 // which we will build a sequence of member references to each
529 // of the anonymous union objects and, eventually, the field we
530 // found via name lookup.
531 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000532 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000533 if (BaseObject) {
534 // BaseObject is an anonymous struct/union variable (and is,
535 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000537 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000539 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000540 BaseQuals
541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
John McCall8ccfcb52009-09-24 19:53:00 +0000551 BaseQuals
552 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000553 } else {
554 // We've found a member of an anonymous struct/union that is
555 // inside a non-anonymous struct/union, so in a well-formed
556 // program our base object expression is "this".
557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
558 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000559 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000560 = Context.getTagDeclType(
561 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
562 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000563 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000564 == Context.getCanonicalType(ThisType)) ||
565 IsDerivedFrom(ThisType, AnonFieldType)) {
566 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000567 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000568 MD->getThisType(Context),
569 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000570 BaseObjectIsPointer = true;
571 }
572 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000573 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
574 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000575 }
John McCall8ccfcb52009-09-24 19:53:00 +0000576 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000577 }
578
Mike Stump11289f42009-09-09 15:08:12 +0000579 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000580 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
581 << Field->getDeclName());
Douglas Gregor9ac7a072009-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 McCall8ccfcb52009-09-24 19:53:00 +0000587 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-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 McCall8ccfcb52009-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 Gregorc9c02ed2009-06-19 23:52:42 +0000610 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000611 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000612 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000613 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
614 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000615 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000616 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000617 }
618
Sebastian Redlffbcf962009-01-18 18:53:16 +0000619 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000620}
621
John McCall10eae182009-11-30 22:42:35 +0000622/// Decomposes the given name into a DeclarationName, its location, and
623/// possibly a list of template arguments.
624///
625/// If this produces template arguments, it is permitted to call
626/// DecomposeTemplateName.
627///
628/// This actually loses a lot of source location information for
629/// non-standard name kinds; we should consider preserving that in
630/// some way.
631static void DecomposeUnqualifiedId(Sema &SemaRef,
632 const UnqualifiedId &Id,
633 TemplateArgumentListInfo &Buffer,
634 DeclarationName &Name,
635 SourceLocation &NameLoc,
636 const TemplateArgumentListInfo *&TemplateArgs) {
637 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
638 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
639 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
640
641 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
642 Id.TemplateId->getTemplateArgs(),
643 Id.TemplateId->NumArgs);
644 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
645 TemplateArgsPtr.release();
646
647 TemplateName TName =
648 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
649
650 Name = SemaRef.Context.getNameForTemplate(TName);
651 NameLoc = Id.TemplateId->TemplateNameLoc;
652 TemplateArgs = &Buffer;
653 } else {
654 Name = SemaRef.GetNameFromUnqualifiedId(Id);
655 NameLoc = Id.StartLocation;
656 TemplateArgs = 0;
657 }
658}
659
660/// Decompose the given template name into a list of lookup results.
661///
662/// The unqualified ID must name a non-dependent template, which can
663/// be more easily tested by checking whether DecomposeUnqualifiedId
664/// found template arguments.
665static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
666 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
667 TemplateName TName =
668 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
669
John McCalle66edc12009-11-24 19:00:30 +0000670 if (TemplateDecl *TD = TName.getAsTemplateDecl())
671 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000672 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
673 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
674 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000675 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000676
John McCalle66edc12009-11-24 19:00:30 +0000677 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000678}
679
John McCall10eae182009-11-30 22:42:35 +0000680static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
681 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
682 E = Record->bases_end(); I != E; ++I) {
683 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
684 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
685 if (!BaseRT) return false;
686
687 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
688 if (!BaseRecord->isDefinition() ||
689 !IsFullyFormedScope(SemaRef, BaseRecord))
690 return false;
691 }
692
693 return true;
694}
695
John McCallf786fb12009-11-30 23:50:49 +0000696/// Determines whether we can lookup this id-expression now or whether
697/// we have to wait until template instantiation is complete.
698static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000699 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000700
John McCallf786fb12009-11-30 23:50:49 +0000701 // If the qualifier scope isn't computable, it's definitely dependent.
702 if (!DC) return true;
703
704 // If the qualifier scope doesn't name a record, we can always look into it.
705 if (!isa<CXXRecordDecl>(DC)) return false;
706
707 // We can't look into record types unless they're fully-formed.
708 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
709
John McCall2d74de92009-12-01 22:10:20 +0000710 return false;
711}
John McCallf786fb12009-11-30 23:50:49 +0000712
John McCall2d74de92009-12-01 22:10:20 +0000713/// Determines if the given class is provably not derived from all of
714/// the prospective base classes.
715static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
716 CXXRecordDecl *Record,
717 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000718 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000719 return false;
720
John McCalla6d407c2009-12-01 22:28:41 +0000721 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
722 if (!RD) return false;
723 Record = cast<CXXRecordDecl>(RD);
724
John McCall2d74de92009-12-01 22:10:20 +0000725 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
726 E = Record->bases_end(); I != E; ++I) {
727 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
728 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
729 if (!BaseRT) return false;
730
731 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000732 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
733 return false;
734 }
735
736 return true;
737}
738
John McCall5af04502009-12-02 20:26:00 +0000739/// Determines if this is an instance member of a class.
740static bool IsInstanceMember(NamedDecl *D) {
John McCall57500772009-12-16 12:17:52 +0000741 assert(D->isCXXClassMember() &&
John McCall2d74de92009-12-01 22:10:20 +0000742 "checking whether non-member is instance member");
743
744 if (isa<FieldDecl>(D)) return true;
745
746 if (isa<CXXMethodDecl>(D))
747 return !cast<CXXMethodDecl>(D)->isStatic();
748
749 if (isa<FunctionTemplateDecl>(D)) {
750 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
751 return !cast<CXXMethodDecl>(D)->isStatic();
752 }
753
754 return false;
755}
756
757enum IMAKind {
758 /// The reference is definitely not an instance member access.
759 IMA_Static,
760
761 /// The reference may be an implicit instance member access.
762 IMA_Mixed,
763
764 /// The reference may be to an instance member, but it is invalid if
765 /// so, because the context is not an instance method.
766 IMA_Mixed_StaticContext,
767
768 /// The reference may be to an instance member, but it is invalid if
769 /// so, because the context is from an unrelated class.
770 IMA_Mixed_Unrelated,
771
772 /// The reference is definitely an implicit instance member access.
773 IMA_Instance,
774
775 /// The reference may be to an unresolved using declaration.
776 IMA_Unresolved,
777
778 /// The reference may be to an unresolved using declaration and the
779 /// context is not an instance method.
780 IMA_Unresolved_StaticContext,
781
782 /// The reference is to a member of an anonymous structure in a
783 /// non-class context.
784 IMA_AnonymousMember,
785
786 /// All possible referrents are instance members and the current
787 /// context is not an instance method.
788 IMA_Error_StaticContext,
789
790 /// All possible referrents are instance members of an unrelated
791 /// class.
792 IMA_Error_Unrelated
793};
794
795/// The given lookup names class member(s) and is not being used for
796/// an address-of-member expression. Classify the type of access
797/// according to whether it's possible that this reference names an
798/// instance member. This is best-effort; it is okay to
799/// conservatively answer "yes", in which case some errors will simply
800/// not be caught until template-instantiation.
801static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
802 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000803 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000804
805 bool isStaticContext =
806 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
807 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
808
809 if (R.isUnresolvableResult())
810 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
811
812 // Collect all the declaring classes of instance members we find.
813 bool hasNonInstance = false;
814 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
815 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
816 NamedDecl *D = (*I)->getUnderlyingDecl();
817 if (IsInstanceMember(D)) {
818 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
819
820 // If this is a member of an anonymous record, move out to the
821 // innermost non-anonymous struct or union. If there isn't one,
822 // that's a special case.
823 while (R->isAnonymousStructOrUnion()) {
824 R = dyn_cast<CXXRecordDecl>(R->getParent());
825 if (!R) return IMA_AnonymousMember;
826 }
827 Classes.insert(R->getCanonicalDecl());
828 }
829 else
830 hasNonInstance = true;
831 }
832
833 // If we didn't find any instance members, it can't be an implicit
834 // member reference.
835 if (Classes.empty())
836 return IMA_Static;
837
838 // If the current context is not an instance method, it can't be
839 // an implicit member reference.
840 if (isStaticContext)
841 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
842
843 // If we can prove that the current context is unrelated to all the
844 // declaring classes, it can't be an implicit member reference (in
845 // which case it's an error if any of those members are selected).
846 if (IsProvablyNotDerivedFrom(SemaRef,
847 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
848 Classes))
849 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
850
851 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
852}
853
854/// Diagnose a reference to a field with no object available.
855static void DiagnoseInstanceReference(Sema &SemaRef,
856 const CXXScopeSpec &SS,
857 const LookupResult &R) {
858 SourceLocation Loc = R.getNameLoc();
859 SourceRange Range(Loc);
860 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
861
862 if (R.getAsSingle<FieldDecl>()) {
863 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
864 if (MD->isStatic()) {
865 // "invalid use of member 'x' in static member function"
866 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
867 << Range << R.getLookupName();
868 return;
869 }
870 }
871
872 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
873 << R.getLookupName() << Range;
874 return;
875 }
876
877 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000878}
879
John McCalld681c392009-12-16 08:11:27 +0000880/// Diagnose an empty lookup.
881///
882/// \return false if new lookup candidates were found
Douglas Gregor598b08f2009-12-31 05:20:13 +0000883bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCalld681c392009-12-16 08:11:27 +0000884 LookupResult &R) {
885 DeclarationName Name = R.getLookupName();
886
John McCalld681c392009-12-16 08:11:27 +0000887 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000888 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000889 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
890 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000891 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000892 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000893 diagnostic_suggest = diag::err_undeclared_use_suggest;
894 }
John McCalld681c392009-12-16 08:11:27 +0000895
Douglas Gregor598b08f2009-12-31 05:20:13 +0000896 // If the original lookup was an unqualified lookup, fake an
897 // unqualified lookup. This is useful when (for example) the
898 // original lookup would not have found something because it was a
899 // dependent name.
900 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
901 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000902 if (isa<CXXRecordDecl>(DC)) {
903 LookupQualifiedName(R, DC);
904
905 if (!R.empty()) {
906 // Don't give errors about ambiguities in this lookup.
907 R.suppressDiagnostics();
908
909 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
910 bool isInstance = CurMethod &&
911 CurMethod->isInstance() &&
912 DC == CurMethod->getParent();
913
914 // Give a code modification hint to insert 'this->'.
915 // TODO: fixit for inserting 'Base<T>::' in the other cases.
916 // Actually quite difficult!
917 if (isInstance)
918 Diag(R.getNameLoc(), diagnostic) << Name
919 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
920 "this->");
921 else
922 Diag(R.getNameLoc(), diagnostic) << Name;
923
924 // Do we really want to note all of these?
925 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
926 Diag((*I)->getLocation(), diag::note_dependent_var_use);
927
928 // Tell the callee to try to recover.
929 return false;
930 }
931 }
932 }
933
Douglas Gregor598b08f2009-12-31 05:20:13 +0000934 // We didn't find anything, so try to correct for a typo.
Douglas Gregor25363982010-01-01 00:15:04 +0000935 if (S && CorrectTypo(R, S, &SS)) {
936 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
937 if (SS.isEmpty())
938 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
939 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000940 R.getLookupName().getAsString());
Douglas Gregor25363982010-01-01 00:15:04 +0000941 else
942 Diag(R.getNameLoc(), diag::err_no_member_suggest)
943 << Name << computeDeclContext(SS, false) << R.getLookupName()
944 << SS.getRange()
945 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000946 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000947 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
948 Diag(ND->getLocation(), diag::note_previous_decl)
949 << ND->getDeclName();
950
Douglas Gregor25363982010-01-01 00:15:04 +0000951 // Tell the callee to try to recover.
952 return false;
953 }
954
955 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
956 // FIXME: If we ended up with a typo for a type name or
957 // Objective-C class name, we're in trouble because the parser
958 // is in the wrong place to recover. Suggest the typo
959 // correction, but don't make it a fix-it since we're not going
960 // to recover well anyway.
961 if (SS.isEmpty())
962 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
963 else
964 Diag(R.getNameLoc(), diag::err_no_member_suggest)
965 << Name << computeDeclContext(SS, false) << R.getLookupName()
966 << SS.getRange();
967
968 // Don't try to recover; it won't work.
969 return true;
970 }
971
972 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +0000973 }
974
975 // Emit a special diagnostic for failed member lookups.
976 // FIXME: computing the declaration context might fail here (?)
977 if (!SS.isEmpty()) {
978 Diag(R.getNameLoc(), diag::err_no_member)
979 << Name << computeDeclContext(SS, false)
980 << SS.getRange();
981 return true;
982 }
983
John McCalld681c392009-12-16 08:11:27 +0000984 // Give up, we can't recover.
985 Diag(R.getNameLoc(), diagnostic) << Name;
986 return true;
987}
988
John McCalle66edc12009-11-24 19:00:30 +0000989Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
990 const CXXScopeSpec &SS,
991 UnqualifiedId &Id,
992 bool HasTrailingLParen,
993 bool isAddressOfOperand) {
994 assert(!(isAddressOfOperand && HasTrailingLParen) &&
995 "cannot be direct & operand and have a trailing lparen");
996
997 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000998 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000999
John McCall10eae182009-11-30 22:42:35 +00001000 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001001
1002 // Decompose the UnqualifiedId into the following data.
1003 DeclarationName Name;
1004 SourceLocation NameLoc;
1005 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00001006 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1007 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001008
Douglas Gregor4ea80432008-11-18 15:03:34 +00001009 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +00001010
John McCalle66edc12009-11-24 19:00:30 +00001011 // C++ [temp.dep.expr]p3:
1012 // An id-expression is type-dependent if it contains:
1013 // -- a nested-name-specifier that contains a class-name that
1014 // names a dependent type.
1015 // Determine whether this is a member of an unknown specialization;
1016 // we need to handle these differently.
John McCallf786fb12009-11-30 23:50:49 +00001017 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCalle66edc12009-11-24 19:00:30 +00001018 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001019 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001020 TemplateArgs);
1021 }
John McCalld14a8642009-11-21 08:51:07 +00001022
John McCalle66edc12009-11-24 19:00:30 +00001023 // Perform the required lookup.
1024 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1025 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001026 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001027 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001028 } else {
1029 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +00001030
John McCalle66edc12009-11-24 19:00:30 +00001031 // If this reference is in an Objective-C method, then we need to do
1032 // some special Objective-C lookup, too.
1033 if (!SS.isSet() && II && getCurMethodDecl()) {
1034 OwningExprResult E(LookupInObjCMethod(R, S, II));
1035 if (E.isInvalid())
1036 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001037
John McCalle66edc12009-11-24 19:00:30 +00001038 Expr *Ex = E.takeAs<Expr>();
1039 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001040 }
Chris Lattner59a25942008-03-31 00:36:02 +00001041 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001042
John McCalle66edc12009-11-24 19:00:30 +00001043 if (R.isAmbiguous())
1044 return ExprError();
1045
Douglas Gregor171c45a2009-02-18 21:56:37 +00001046 // Determine whether this name might be a candidate for
1047 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001048 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001049
John McCalle66edc12009-11-24 19:00:30 +00001050 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001051 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001052 // in C90, extension in C99, forbidden in C++).
1053 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1054 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1055 if (D) R.addDecl(D);
1056 }
1057
1058 // If this name wasn't predeclared and if this is not a function
1059 // call, diagnose the problem.
1060 if (R.empty()) {
Douglas Gregor598b08f2009-12-31 05:20:13 +00001061 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001062 return ExprError();
1063
1064 assert(!R.empty() &&
1065 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001066
1067 // If we found an Objective-C instance variable, let
1068 // LookupInObjCMethod build the appropriate expression to
1069 // reference the ivar.
1070 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1071 R.clear();
1072 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1073 assert(E.isInvalid() || E.get());
1074 return move(E);
1075 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001076 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078
John McCalle66edc12009-11-24 19:00:30 +00001079 // This is guaranteed from this point on.
1080 assert(!R.empty() || ADL);
1081
1082 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001083 // Warn about constructs like:
1084 // if (void *X = foo()) { ... } else { X }.
1085 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001086
Douglas Gregor3256d042009-06-30 15:47:41 +00001087 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1088 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001089 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001090 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001091 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001092 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001093 << Var->getDeclName()
1094 << (Var->getType()->isPointerType()? 2 :
1095 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001096 break;
1097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
Douglas Gregor13a2c032009-11-05 17:49:26 +00001099 // Move to the parent of this scope.
1100 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001101 }
1102 }
John McCalle66edc12009-11-24 19:00:30 +00001103 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001104 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1105 // C99 DR 316 says that, if a function type comes from a
1106 // function definition (without a prototype), that type is only
1107 // used for checking compatibility. Therefore, when referencing
1108 // the function, we pretend that we don't have the full function
1109 // type.
John McCalle66edc12009-11-24 19:00:30 +00001110 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001111 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001112
Douglas Gregor3256d042009-06-30 15:47:41 +00001113 QualType T = Func->getType();
1114 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001115 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001116 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001117 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001118 }
1119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
John McCall2d74de92009-12-01 22:10:20 +00001121 // Check whether this might be a C++ implicit instance member access.
1122 // C++ [expr.prim.general]p6:
1123 // Within the definition of a non-static member function, an
1124 // identifier that names a non-static member is transformed to a
1125 // class member access expression.
1126 // But note that &SomeClass::foo is grammatically distinct, even
1127 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001128 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001129 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001130 if (!isAbstractMemberPointer)
1131 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001132 }
1133
John McCalle66edc12009-11-24 19:00:30 +00001134 if (TemplateArgs)
1135 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001136
John McCalle66edc12009-11-24 19:00:30 +00001137 return BuildDeclarationNameExpr(SS, R, ADL);
1138}
1139
John McCall57500772009-12-16 12:17:52 +00001140/// Builds an expression which might be an implicit member expression.
1141Sema::OwningExprResult
1142Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1143 LookupResult &R,
1144 const TemplateArgumentListInfo *TemplateArgs) {
1145 switch (ClassifyImplicitMemberAccess(*this, R)) {
1146 case IMA_Instance:
1147 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1148
1149 case IMA_AnonymousMember:
1150 assert(R.isSingleResult());
1151 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1152 R.getAsSingle<FieldDecl>());
1153
1154 case IMA_Mixed:
1155 case IMA_Mixed_Unrelated:
1156 case IMA_Unresolved:
1157 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1158
1159 case IMA_Static:
1160 case IMA_Mixed_StaticContext:
1161 case IMA_Unresolved_StaticContext:
1162 if (TemplateArgs)
1163 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1164 return BuildDeclarationNameExpr(SS, R, false);
1165
1166 case IMA_Error_StaticContext:
1167 case IMA_Error_Unrelated:
1168 DiagnoseInstanceReference(*this, SS, R);
1169 return ExprError();
1170 }
1171
1172 llvm_unreachable("unexpected instance member access kind");
1173 return ExprError();
1174}
1175
John McCall10eae182009-11-30 22:42:35 +00001176/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1177/// declaration name, generally during template instantiation.
1178/// There's a large number of things which don't need to be done along
1179/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001180Sema::OwningExprResult
1181Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1182 DeclarationName Name,
1183 SourceLocation NameLoc) {
1184 DeclContext *DC;
1185 if (!(DC = computeDeclContext(SS, false)) ||
1186 DC->isDependentContext() ||
1187 RequireCompleteDeclContext(SS))
1188 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1189
1190 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1191 LookupQualifiedName(R, DC);
1192
1193 if (R.isAmbiguous())
1194 return ExprError();
1195
1196 if (R.empty()) {
1197 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1198 return ExprError();
1199 }
1200
1201 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1202}
1203
1204/// LookupInObjCMethod - The parser has read a name in, and Sema has
1205/// detected that we're currently inside an ObjC method. Perform some
1206/// additional lookup.
1207///
1208/// Ideally, most of this would be done by lookup, but there's
1209/// actually quite a lot of extra work involved.
1210///
1211/// Returns a null sentinel to indicate trivial success.
1212Sema::OwningExprResult
1213Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1214 IdentifierInfo *II) {
1215 SourceLocation Loc = Lookup.getNameLoc();
1216
1217 // There are two cases to handle here. 1) scoped lookup could have failed,
1218 // in which case we should look for an ivar. 2) scoped lookup could have
1219 // found a decl, but that decl is outside the current instance method (i.e.
1220 // a global variable). In these two cases, we do a lookup for an ivar with
1221 // this name, if the lookup sucedes, we replace it our current decl.
1222
1223 // If we're in a class method, we don't normally want to look for
1224 // ivars. But if we don't find anything else, and there's an
1225 // ivar, that's an error.
1226 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1227
1228 bool LookForIvars;
1229 if (Lookup.empty())
1230 LookForIvars = true;
1231 else if (IsClassMethod)
1232 LookForIvars = false;
1233 else
1234 LookForIvars = (Lookup.isSingleResult() &&
1235 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1236
1237 if (LookForIvars) {
1238 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1239 ObjCInterfaceDecl *ClassDeclared;
1240 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1241 // Diagnose using an ivar in a class method.
1242 if (IsClassMethod)
1243 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1244 << IV->getDeclName());
1245
1246 // If we're referencing an invalid decl, just return this as a silent
1247 // error node. The error diagnostic was already emitted on the decl.
1248 if (IV->isInvalidDecl())
1249 return ExprError();
1250
1251 // Check if referencing a field with __attribute__((deprecated)).
1252 if (DiagnoseUseOfDecl(IV, Loc))
1253 return ExprError();
1254
1255 // Diagnose the use of an ivar outside of the declaring class.
1256 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1257 ClassDeclared != IFace)
1258 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1259
1260 // FIXME: This should use a new expr for a direct reference, don't
1261 // turn this into Self->ivar, just return a BareIVarExpr or something.
1262 IdentifierInfo &II = Context.Idents.get("self");
1263 UnqualifiedId SelfName;
1264 SelfName.setIdentifier(&II, SourceLocation());
1265 CXXScopeSpec SelfScopeSpec;
1266 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1267 SelfName, false, false);
1268 MarkDeclarationReferenced(Loc, IV);
1269 return Owned(new (Context)
1270 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1271 SelfExpr.takeAs<Expr>(), true, true));
1272 }
1273 } else if (getCurMethodDecl()->isInstanceMethod()) {
1274 // We should warn if a local variable hides an ivar.
1275 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1276 ObjCInterfaceDecl *ClassDeclared;
1277 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1278 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1279 IFace == ClassDeclared)
1280 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1281 }
1282 }
1283
1284 // Needed to implement property "super.method" notation.
1285 if (Lookup.empty() && II->isStr("super")) {
1286 QualType T;
1287
1288 if (getCurMethodDecl()->isInstanceMethod())
1289 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1290 getCurMethodDecl()->getClassInterface()));
1291 else
1292 T = Context.getObjCClassType();
1293 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1294 }
1295
1296 // Sentinel value saying that we didn't do anything special.
1297 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001298}
John McCalld14a8642009-11-21 08:51:07 +00001299
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001300/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001301bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001302Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1303 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001304 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001305 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001306 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001307 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001308 if (DestType->isDependentType() || From->getType()->isDependentType())
1309 return false;
1310 QualType FromRecordType = From->getType();
1311 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001312 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001313 DestType = Context.getPointerType(DestType);
1314 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001315 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001316 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1317 CheckDerivedToBaseConversion(FromRecordType,
1318 DestRecordType,
1319 From->getSourceRange().getBegin(),
1320 From->getSourceRange()))
1321 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001322 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1323 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001324 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001325 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001326}
Douglas Gregor3256d042009-06-30 15:47:41 +00001327
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001328/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001329static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001330 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001331 SourceLocation Loc, QualType Ty,
1332 const TemplateArgumentListInfo *TemplateArgs = 0) {
1333 NestedNameSpecifier *Qualifier = 0;
1334 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001335 if (SS.isSet()) {
1336 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1337 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001338 }
Mike Stump11289f42009-09-09 15:08:12 +00001339
John McCalle66edc12009-11-24 19:00:30 +00001340 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1341 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001342}
1343
John McCall2d74de92009-12-01 22:10:20 +00001344/// Builds an implicit member access expression. The current context
1345/// is known to be an instance method, and the given unqualified lookup
1346/// set is known to contain only instance members, at least one of which
1347/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001348Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001349Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1350 LookupResult &R,
1351 const TemplateArgumentListInfo *TemplateArgs,
1352 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001353 assert(!R.empty() && !R.isAmbiguous());
1354
John McCalld14a8642009-11-21 08:51:07 +00001355 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001356
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001357 // We may have found a field within an anonymous union or struct
1358 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001359 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001360 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001361 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001362 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001363 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001364
John McCall2d74de92009-12-01 22:10:20 +00001365 // If this is known to be an instance access, go ahead and build a
1366 // 'this' expression now.
1367 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1368 Expr *This = 0; // null signifies implicit access
1369 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001370 SourceLocation Loc = R.getNameLoc();
1371 if (SS.getRange().isValid())
1372 Loc = SS.getRange().getBegin();
1373 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001374 }
1375
John McCall2d74de92009-12-01 22:10:20 +00001376 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1377 /*OpLoc*/ SourceLocation(),
1378 /*IsArrow*/ true,
1379 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001380}
1381
John McCalle66edc12009-11-24 19:00:30 +00001382bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001383 const LookupResult &R,
1384 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001385 // Only when used directly as the postfix-expression of a call.
1386 if (!HasTrailingLParen)
1387 return false;
1388
1389 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001390 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001391 return false;
1392
1393 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001394 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001395 return false;
1396
1397 // Turn off ADL when we find certain kinds of declarations during
1398 // normal lookup:
1399 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1400 NamedDecl *D = *I;
1401
1402 // C++0x [basic.lookup.argdep]p3:
1403 // -- a declaration of a class member
1404 // Since using decls preserve this property, we check this on the
1405 // original decl.
John McCall57500772009-12-16 12:17:52 +00001406 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001407 return false;
1408
1409 // C++0x [basic.lookup.argdep]p3:
1410 // -- a block-scope function declaration that is not a
1411 // using-declaration
1412 // NOTE: we also trigger this for function templates (in fact, we
1413 // don't check the decl type at all, since all other decl types
1414 // turn off ADL anyway).
1415 if (isa<UsingShadowDecl>(D))
1416 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1417 else if (D->getDeclContext()->isFunctionOrMethod())
1418 return false;
1419
1420 // C++0x [basic.lookup.argdep]p3:
1421 // -- a declaration that is neither a function or a function
1422 // template
1423 // And also for builtin functions.
1424 if (isa<FunctionDecl>(D)) {
1425 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1426
1427 // But also builtin functions.
1428 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1429 return false;
1430 } else if (!isa<FunctionTemplateDecl>(D))
1431 return false;
1432 }
1433
1434 return true;
1435}
1436
1437
John McCalld14a8642009-11-21 08:51:07 +00001438/// Diagnoses obvious problems with the use of the given declaration
1439/// as an expression. This is only actually called for lookups that
1440/// were not overloaded, and it doesn't promise that the declaration
1441/// will in fact be used.
1442static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1443 if (isa<TypedefDecl>(D)) {
1444 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1445 return true;
1446 }
1447
1448 if (isa<ObjCInterfaceDecl>(D)) {
1449 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1450 return true;
1451 }
1452
1453 if (isa<NamespaceDecl>(D)) {
1454 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1455 return true;
1456 }
1457
1458 return false;
1459}
1460
1461Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001462Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001463 LookupResult &R,
1464 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001465 // If this is a single, fully-resolved result and we don't need ADL,
1466 // just build an ordinary singleton decl ref.
1467 if (!NeedsADL && R.isSingleResult())
John McCallb53bbd42009-11-22 01:44:31 +00001468 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001469
1470 // We only need to check the declaration if there's exactly one
1471 // result, because in the overloaded case the results can only be
1472 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001473 if (R.isSingleResult() &&
1474 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001475 return ExprError();
1476
John McCalle66edc12009-11-24 19:00:30 +00001477 bool Dependent
1478 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001479 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001480 = UnresolvedLookupExpr::Create(Context, Dependent,
1481 (NestedNameSpecifier*) SS.getScopeRep(),
1482 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001483 R.getLookupName(), R.getNameLoc(),
1484 NeedsADL, R.isOverloadedResult());
1485 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1486 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001487
1488 return Owned(ULE);
1489}
1490
1491
1492/// \brief Complete semantic analysis for a reference to the given declaration.
1493Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001494Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001495 SourceLocation Loc, NamedDecl *D) {
1496 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001497 assert(!isa<FunctionTemplateDecl>(D) &&
1498 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001499
1500 if (CheckDeclInExpr(*this, Loc, D))
1501 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001502
Douglas Gregore7488b92009-12-01 16:58:18 +00001503 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1504 // Specifically diagnose references to class templates that are missing
1505 // a template argument list.
1506 Diag(Loc, diag::err_template_decl_ref)
1507 << Template << SS.getRange();
1508 Diag(Template->getLocation(), diag::note_template_decl_here);
1509 return ExprError();
1510 }
1511
1512 // Make sure that we're referring to a value.
1513 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1514 if (!VD) {
1515 Diag(Loc, diag::err_ref_non_value)
1516 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001517 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001518 return ExprError();
1519 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001520
Douglas Gregor171c45a2009-02-18 21:56:37 +00001521 // Check whether this declaration can be used. Note that we suppress
1522 // this check when we're going to perform argument-dependent lookup
1523 // on this function name, because this might not be the function
1524 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001525 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001526 return ExprError();
1527
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001528 // Only create DeclRefExpr's for valid Decl's.
1529 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001530 return ExprError();
1531
Chris Lattner2a9d9892008-10-20 05:16:36 +00001532 // If the identifier reference is inside a block, and it refers to a value
1533 // that is outside the block, create a BlockDeclRefExpr instead of a
1534 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1535 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001536 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001537 // We do not do this for things like enum constants, global variables, etc,
1538 // as they do not get snapshotted.
1539 //
1540 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001541 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1542 Diag(Loc, diag::err_ref_vm_type);
1543 Diag(D->getLocation(), diag::note_declared_at);
1544 return ExprError();
1545 }
1546
Mike Stump8971a862010-01-05 03:10:36 +00001547 if (VD->getType()->isArrayType()) {
1548 Diag(Loc, diag::err_ref_array_type);
1549 Diag(D->getLocation(), diag::note_declared_at);
1550 return ExprError();
1551 }
1552
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001553 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001554 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001555 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001556 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001557 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001558 // This is to record that a 'const' was actually synthesize and added.
1559 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001560 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001561
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001562 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001563 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001564 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001565 }
1566 // If this reference is not in a block or if the referenced variable is
1567 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001568
John McCalle66edc12009-11-24 19:00:30 +00001569 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001570}
Chris Lattnere168f762006-11-10 05:29:30 +00001571
Sebastian Redlffbcf962009-01-18 18:53:16 +00001572Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1573 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001574 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001575
Chris Lattnere168f762006-11-10 05:29:30 +00001576 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001577 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001578 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1579 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1580 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001581 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001582
Chris Lattnera81a0272008-01-12 08:14:25 +00001583 // Pre-defined identifiers are of type char[x], where x is the length of the
1584 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001585
Anders Carlsson2fb08242009-09-08 18:24:21 +00001586 Decl *currentDecl = getCurFunctionOrMethodDecl();
1587 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001588 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001589 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001590 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001591
Anders Carlsson0b209a82009-09-11 01:22:35 +00001592 QualType ResTy;
1593 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1594 ResTy = Context.DependentTy;
1595 } else {
1596 unsigned Length =
1597 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001598
Anders Carlsson0b209a82009-09-11 01:22:35 +00001599 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001600 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001601 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1602 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001603 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001604}
1605
Sebastian Redlffbcf962009-01-18 18:53:16 +00001606Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001607 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001608 CharBuffer.resize(Tok.getLength());
1609 const char *ThisTokBegin = &CharBuffer[0];
1610 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001611
Steve Naroffae4143e2007-04-26 20:39:23 +00001612 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1613 Tok.getLocation(), PP);
1614 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001615 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001616
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001617 QualType Ty;
1618 if (!getLangOptions().CPlusPlus)
1619 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1620 else if (Literal.isWide())
1621 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1622 else
1623 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001624
Sebastian Redl20614a72009-01-20 22:23:13 +00001625 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1626 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001627 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001628}
1629
Sebastian Redlffbcf962009-01-18 18:53:16 +00001630Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1631 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001632 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1633 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001634 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001635 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001636 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001637 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001638 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001639
Chris Lattner23b7eb62007-06-15 23:05:46 +00001640 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001641 // Add padding so that NumericLiteralParser can overread by one character.
1642 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001643 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001644
Chris Lattner67ca9252007-05-21 01:08:44 +00001645 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001646 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001647
Mike Stump11289f42009-09-09 15:08:12 +00001648 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001649 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001650 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001651 return ExprError();
1652
Chris Lattner1c20a172007-08-26 03:42:43 +00001653 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001654
Chris Lattner1c20a172007-08-26 03:42:43 +00001655 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001656 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001657 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001658 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001659 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001660 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001661 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001662 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001663
1664 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1665
John McCall53b93a02009-12-24 09:08:04 +00001666 using llvm::APFloat;
1667 APFloat Val(Format);
1668
1669 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001670
1671 // Overflow is always an error, but underflow is only an error if
1672 // we underflowed to zero (APFloat reports denormals as underflow).
1673 if ((result & APFloat::opOverflow) ||
1674 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001675 unsigned diagnostic;
1676 llvm::SmallVector<char, 20> buffer;
1677 if (result & APFloat::opOverflow) {
1678 diagnostic = diag::err_float_overflow;
1679 APFloat::getLargest(Format).toString(buffer);
1680 } else {
1681 diagnostic = diag::err_float_underflow;
1682 APFloat::getSmallest(Format).toString(buffer);
1683 }
1684
1685 Diag(Tok.getLocation(), diagnostic)
1686 << Ty
1687 << llvm::StringRef(buffer.data(), buffer.size());
1688 }
1689
1690 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001691 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001692
Chris Lattner1c20a172007-08-26 03:42:43 +00001693 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001694 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001695 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001696 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001697
Neil Boothac582c52007-08-29 22:00:19 +00001698 // long long is a C99 feature.
1699 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001700 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001701 Diag(Tok.getLocation(), diag::ext_longlong);
1702
Chris Lattner67ca9252007-05-21 01:08:44 +00001703 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001704 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001705
Chris Lattner67ca9252007-05-21 01:08:44 +00001706 if (Literal.GetIntegerValue(ResultVal)) {
1707 // If this value didn't fit into uintmax_t, warn and force to ull.
1708 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001709 Ty = Context.UnsignedLongLongTy;
1710 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001711 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001712 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001713 // If this value fits into a ULL, try to figure out what else it fits into
1714 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001715
Chris Lattner67ca9252007-05-21 01:08:44 +00001716 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1717 // be an unsigned int.
1718 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1719
1720 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001721 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001722 if (!Literal.isLong && !Literal.isLongLong) {
1723 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001724 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001725
Chris Lattner67ca9252007-05-21 01:08:44 +00001726 // Does it fit in a unsigned int?
1727 if (ResultVal.isIntN(IntSize)) {
1728 // Does it fit in a signed int?
1729 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001730 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001731 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001732 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001733 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001734 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001735 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001736
Chris Lattner67ca9252007-05-21 01:08:44 +00001737 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001738 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001739 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001740
Chris Lattner67ca9252007-05-21 01:08:44 +00001741 // Does it fit in a unsigned long?
1742 if (ResultVal.isIntN(LongSize)) {
1743 // Does it fit in a signed long?
1744 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001745 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001746 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001747 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001748 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001749 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001750 }
1751
Chris Lattner67ca9252007-05-21 01:08:44 +00001752 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001753 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001754 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001755
Chris Lattner67ca9252007-05-21 01:08:44 +00001756 // Does it fit in a unsigned long long?
1757 if (ResultVal.isIntN(LongLongSize)) {
1758 // Does it fit in a signed long long?
1759 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001760 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001761 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001762 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001763 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001764 }
1765 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001766
Chris Lattner67ca9252007-05-21 01:08:44 +00001767 // If we still couldn't decide a type, we probably have something that
1768 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001769 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001770 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001771 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001772 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001773 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001774
Chris Lattner55258cf2008-05-09 05:59:00 +00001775 if (ResultVal.getBitWidth() != Width)
1776 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001777 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001778 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001779 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001780
Chris Lattner1c20a172007-08-26 03:42:43 +00001781 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1782 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001783 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001784 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001785
1786 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001787}
1788
Sebastian Redlffbcf962009-01-18 18:53:16 +00001789Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1790 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001791 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001792 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001793 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001794}
1795
Steve Naroff71b59a92007-06-04 22:22:31 +00001796/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001797/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001798bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001799 SourceLocation OpLoc,
1800 const SourceRange &ExprRange,
1801 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001802 if (exprType->isDependentType())
1803 return false;
1804
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001805 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1806 // the result is the size of the referenced type."
1807 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1808 // result shall be the alignment of the referenced type."
1809 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1810 exprType = Ref->getPointeeType();
1811
Steve Naroff043d45d2007-05-15 02:32:35 +00001812 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001813 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001814 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001815 if (isSizeof)
1816 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1817 return false;
1818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
Chris Lattner62975a72009-04-24 00:30:45 +00001820 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001821 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001822 Diag(OpLoc, diag::ext_sizeof_void_type)
1823 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001824 return false;
1825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Chris Lattner62975a72009-04-24 00:30:45 +00001827 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001828 PDiag(diag::err_sizeof_alignof_incomplete_type)
1829 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001830 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001831
Chris Lattner62975a72009-04-24 00:30:45 +00001832 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001833 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001834 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001835 << exprType << isSizeof << ExprRange;
1836 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001837 }
Mike Stump11289f42009-09-09 15:08:12 +00001838
Chris Lattner62975a72009-04-24 00:30:45 +00001839 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001840}
1841
Chris Lattner8dff0172009-01-24 20:17:12 +00001842bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1843 const SourceRange &ExprRange) {
1844 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001845
Mike Stump11289f42009-09-09 15:08:12 +00001846 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001847 if (isa<DeclRefExpr>(E))
1848 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001849
1850 // Cannot know anything else if the expression is dependent.
1851 if (E->isTypeDependent())
1852 return false;
1853
Douglas Gregor71235ec2009-05-02 02:18:30 +00001854 if (E->getBitField()) {
1855 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1856 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001857 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001858
1859 // Alignment of a field access is always okay, so long as it isn't a
1860 // bit-field.
1861 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001862 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001863 return false;
1864
Chris Lattner8dff0172009-01-24 20:17:12 +00001865 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1866}
1867
Douglas Gregor0950e412009-03-13 21:01:28 +00001868/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001869Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001870Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001871 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001872 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001873 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001874 return ExprError();
1875
John McCallbcd03502009-12-07 02:54:59 +00001876 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001877
Douglas Gregor0950e412009-03-13 21:01:28 +00001878 if (!T->isDependentType() &&
1879 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1880 return ExprError();
1881
1882 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001883 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001884 Context.getSizeType(), OpLoc,
1885 R.getEnd()));
1886}
1887
1888/// \brief Build a sizeof or alignof expression given an expression
1889/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001890Action::OwningExprResult
1891Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001892 bool isSizeOf, SourceRange R) {
1893 // Verify that the operand is valid.
1894 bool isInvalid = false;
1895 if (E->isTypeDependent()) {
1896 // Delay type-checking for type-dependent expressions.
1897 } else if (!isSizeOf) {
1898 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001899 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001900 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1901 isInvalid = true;
1902 } else {
1903 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1904 }
1905
1906 if (isInvalid)
1907 return ExprError();
1908
1909 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1910 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1911 Context.getSizeType(), OpLoc,
1912 R.getEnd()));
1913}
1914
Sebastian Redl6f282892008-11-11 17:56:53 +00001915/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1916/// the same for @c alignof and @c __alignof
1917/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001918Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001919Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1920 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001921 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001922 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001923
Sebastian Redl6f282892008-11-11 17:56:53 +00001924 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001925 TypeSourceInfo *TInfo;
1926 (void) GetTypeFromParser(TyOrEx, &TInfo);
1927 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001928 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001929
Douglas Gregor0950e412009-03-13 21:01:28 +00001930 Expr *ArgEx = (Expr *)TyOrEx;
1931 Action::OwningExprResult Result
1932 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1933
1934 if (Result.isInvalid())
1935 DeleteExpr(ArgEx);
1936
1937 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001938}
1939
Chris Lattner709322b2009-02-17 08:12:06 +00001940QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001941 if (V->isTypeDependent())
1942 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001943
Chris Lattnere267f5d2007-08-26 05:39:26 +00001944 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001945 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001946 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001947
Chris Lattnere267f5d2007-08-26 05:39:26 +00001948 // Otherwise they pass through real integer and floating point types here.
1949 if (V->getType()->isArithmeticType())
1950 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattnere267f5d2007-08-26 05:39:26 +00001952 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001953 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1954 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001955 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001956}
1957
1958
Chris Lattnere168f762006-11-10 05:29:30 +00001959
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001960Action::OwningExprResult
1961Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1962 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001963 UnaryOperator::Opcode Opc;
1964 switch (Kind) {
1965 default: assert(0 && "Unknown unary op!");
1966 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1967 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1968 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001969
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001970 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001971}
1972
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001973Action::OwningExprResult
1974Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1975 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001976 // Since this might be a postfix expression, get rid of ParenListExprs.
1977 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1978
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001979 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1980 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001981
Douglas Gregor40412ac2008-11-19 17:17:41 +00001982 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001983 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1984 Base.release();
1985 Idx.release();
1986 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1987 Context.DependentTy, RLoc));
1988 }
1989
Mike Stump11289f42009-09-09 15:08:12 +00001990 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001991 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001992 LHSExp->getType()->isEnumeralType() ||
1993 RHSExp->getType()->isRecordType() ||
1994 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001995 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001996 }
1997
Sebastian Redladba46e2009-10-29 20:17:01 +00001998 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1999}
2000
2001
2002Action::OwningExprResult
2003Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2004 ExprArg Idx, SourceLocation RLoc) {
2005 Expr *LHSExp = static_cast<Expr*>(Base.get());
2006 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2007
Chris Lattner36d572b2007-07-16 00:14:47 +00002008 // Perform default conversions.
2009 DefaultFunctionArrayConversion(LHSExp);
2010 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002011
Chris Lattner36d572b2007-07-16 00:14:47 +00002012 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002013
Steve Naroffc1aadb12007-03-28 21:49:40 +00002014 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002015 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002016 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002017 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002018 Expr *BaseExpr, *IndexExpr;
2019 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002020 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2021 BaseExpr = LHSExp;
2022 IndexExpr = RHSExp;
2023 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002025 BaseExpr = LHSExp;
2026 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002027 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002028 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002029 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002030 BaseExpr = RHSExp;
2031 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002032 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002033 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002034 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002035 BaseExpr = LHSExp;
2036 IndexExpr = RHSExp;
2037 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002038 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002039 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002040 // Handle the uncommon case of "123[Ptr]".
2041 BaseExpr = RHSExp;
2042 IndexExpr = LHSExp;
2043 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002044 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002045 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002046 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002047
Chris Lattner36d572b2007-07-16 00:14:47 +00002048 // FIXME: need to deal with const...
2049 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002050 } else if (LHSTy->isArrayType()) {
2051 // If we see an array that wasn't promoted by
2052 // DefaultFunctionArrayConversion, it must be an array that
2053 // wasn't promoted because of the C90 rule that doesn't
2054 // allow promoting non-lvalue arrays. Warn, then
2055 // force the promotion here.
2056 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2057 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002058 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2059 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002060 LHSTy = LHSExp->getType();
2061
2062 BaseExpr = LHSExp;
2063 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002064 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002065 } else if (RHSTy->isArrayType()) {
2066 // Same as previous, except for 123[f().a] case
2067 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2068 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002069 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2070 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002071 RHSTy = RHSExp->getType();
2072
2073 BaseExpr = RHSExp;
2074 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002075 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002076 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002077 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2078 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002079 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002080 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002081 if (!(IndexExpr->getType()->isIntegerType() &&
2082 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002083 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2084 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002085
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002086 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002087 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2088 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002089 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2090
Douglas Gregorac1fb652009-03-24 19:52:54 +00002091 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002092 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2093 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002094 // incomplete types are not object types.
2095 if (ResultType->isFunctionType()) {
2096 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2097 << ResultType << BaseExpr->getSourceRange();
2098 return ExprError();
2099 }
Mike Stump11289f42009-09-09 15:08:12 +00002100
Douglas Gregorac1fb652009-03-24 19:52:54 +00002101 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002102 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002103 PDiag(diag::err_subscript_incomplete_type)
2104 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002105 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattner62975a72009-04-24 00:30:45 +00002107 // Diagnose bad cases where we step over interface counts.
2108 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2109 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2110 << ResultType << BaseExpr->getSourceRange();
2111 return ExprError();
2112 }
Mike Stump11289f42009-09-09 15:08:12 +00002113
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002114 Base.release();
2115 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002116 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002117 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002118}
2119
Steve Narofff8fd09e2007-07-27 22:15:19 +00002120QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002121CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002122 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002123 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002124 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2125 // see FIXME there.
2126 //
2127 // FIXME: This logic can be greatly simplified by splitting it along
2128 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002129 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002130
Steve Narofff8fd09e2007-07-27 22:15:19 +00002131 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002132 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002133
Mike Stump4e1f26a2009-02-19 03:04:26 +00002134 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002135 // special names that indicate a subset of exactly half the elements are
2136 // to be selected.
2137 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002138
Nate Begemanbb70bf62009-01-18 01:47:54 +00002139 // This flag determines whether or not CompName has an 's' char prefix,
2140 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002141 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002142
2143 // Check that we've found one of the special components, or that the component
2144 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002145 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002146 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2147 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002148 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002149 do
2150 compStr++;
2151 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002152 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002153 do
2154 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002155 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002156 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002157
Mike Stump4e1f26a2009-02-19 03:04:26 +00002158 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002159 // We didn't get to the end of the string. This means the component names
2160 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002161 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2162 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002163 return QualType();
2164 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002165
Nate Begemanbb70bf62009-01-18 01:47:54 +00002166 // Ensure no component accessor exceeds the width of the vector type it
2167 // operates on.
2168 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002169 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002170
2171 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002172 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002173
2174 while (*compStr) {
2175 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2176 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2177 << baseType << SourceRange(CompLoc);
2178 return QualType();
2179 }
2180 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002181 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002182
Steve Narofff8fd09e2007-07-27 22:15:19 +00002183 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002184 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002185 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002186 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002187 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002188 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002189 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002190 if (HexSwizzle)
2191 CompSize--;
2192
Steve Narofff8fd09e2007-07-27 22:15:19 +00002193 if (CompSize == 1)
2194 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002195
Nate Begemance4d7fc2008-04-18 23:10:10 +00002196 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002197 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002198 // diagostics look bad. We want extended vector types to appear built-in.
2199 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2200 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2201 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002202 }
2203 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002204}
2205
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002206static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002207 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002208 const Selector &Sel,
2209 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002210
Anders Carlssonf571c112009-08-26 18:25:21 +00002211 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002212 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002213 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002214 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002215
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002216 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2217 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002218 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002219 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002220 return D;
2221 }
2222 return 0;
2223}
2224
Steve Narofffb4330f2009-06-17 22:40:22 +00002225static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002226 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002227 const Selector &Sel,
2228 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002229 // Check protocols on qualified interfaces.
2230 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002231 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002232 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002233 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002234 GDecl = PD;
2235 break;
2236 }
2237 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002238 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002239 GDecl = OMD;
2240 break;
2241 }
2242 }
2243 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002244 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002245 E = QIdTy->qual_end(); I != E; ++I) {
2246 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002247 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002248 if (GDecl)
2249 return GDecl;
2250 }
2251 }
2252 return GDecl;
2253}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002254
John McCall10eae182009-11-30 22:42:35 +00002255Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002256Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2257 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002258 const CXXScopeSpec &SS,
2259 NamedDecl *FirstQualifierInScope,
2260 DeclarationName Name, SourceLocation NameLoc,
2261 const TemplateArgumentListInfo *TemplateArgs) {
2262 Expr *BaseExpr = Base.takeAs<Expr>();
2263
2264 // Even in dependent contexts, try to diagnose base expressions with
2265 // obviously wrong types, e.g.:
2266 //
2267 // T* t;
2268 // t.f;
2269 //
2270 // In Obj-C++, however, the above expression is valid, since it could be
2271 // accessing the 'f' property if T is an Obj-C interface. The extra check
2272 // allows this, while still reporting an error if T is a struct pointer.
2273 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002274 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002275 if (PT && (!getLangOptions().ObjC1 ||
2276 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002277 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002278 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002279 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002280 return ExprError();
2281 }
2282 }
2283
John McCall2d74de92009-12-01 22:10:20 +00002284 assert(BaseType->isDependentType());
John McCall10eae182009-11-30 22:42:35 +00002285
2286 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2287 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002288 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002289 IsArrow, OpLoc,
2290 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2291 SS.getRange(),
2292 FirstQualifierInScope,
2293 Name, NameLoc,
2294 TemplateArgs));
2295}
2296
2297/// We know that the given qualified member reference points only to
2298/// declarations which do not belong to the static type of the base
2299/// expression. Diagnose the problem.
2300static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2301 Expr *BaseExpr,
2302 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002303 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002304 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002305 // If this is an implicit member access, use a different set of
2306 // diagnostics.
2307 if (!BaseExpr)
2308 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002309
2310 // FIXME: this is an exceedingly lame diagnostic for some of the more
2311 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002312 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002313 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002314 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002315}
2316
2317// Check whether the declarations we found through a nested-name
2318// specifier in a member expression are actually members of the base
2319// type. The restriction here is:
2320//
2321// C++ [expr.ref]p2:
2322// ... In these cases, the id-expression shall name a
2323// member of the class or of one of its base classes.
2324//
2325// So it's perfectly legitimate for the nested-name specifier to name
2326// an unrelated class, and for us to find an overload set including
2327// decls from classes which are not superclasses, as long as the decl
2328// we actually pick through overload resolution is from a superclass.
2329bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2330 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002331 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002332 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002333 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2334 if (!BaseRT) {
2335 // We can't check this yet because the base type is still
2336 // dependent.
2337 assert(BaseType->isDependentType());
2338 return false;
2339 }
2340 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002341
2342 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002343 // If this is an implicit member reference and we find a
2344 // non-instance member, it's not an error.
2345 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2346 return false;
John McCall10eae182009-11-30 22:42:35 +00002347
John McCall2d74de92009-12-01 22:10:20 +00002348 // Note that we use the DC of the decl, not the underlying decl.
2349 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2350 while (RecordD->isAnonymousStructOrUnion())
2351 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2352
2353 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2354 MemberRecord.insert(RecordD->getCanonicalDecl());
2355
2356 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2357 return false;
2358 }
2359
John McCallcd4b4772009-12-02 03:53:29 +00002360 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002361 return true;
2362}
2363
2364static bool
2365LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2366 SourceRange BaseRange, const RecordType *RTy,
2367 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2368 RecordDecl *RDecl = RTy->getDecl();
2369 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2370 PDiag(diag::err_typecheck_incomplete_tag)
2371 << BaseRange))
2372 return true;
2373
2374 DeclContext *DC = RDecl;
2375 if (SS.isSet()) {
2376 // If the member name was a qualified-id, look into the
2377 // nested-name-specifier.
2378 DC = SemaRef.computeDeclContext(SS, false);
2379
John McCallcd4b4772009-12-02 03:53:29 +00002380 if (SemaRef.RequireCompleteDeclContext(SS)) {
2381 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2382 << SS.getRange() << DC;
2383 return true;
2384 }
2385
John McCall2d74de92009-12-01 22:10:20 +00002386 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2387
2388 if (!isa<TypeDecl>(DC)) {
2389 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2390 << DC << SS.getRange();
2391 return true;
John McCall10eae182009-11-30 22:42:35 +00002392 }
2393 }
2394
John McCall2d74de92009-12-01 22:10:20 +00002395 // The record definition is complete, now look up the member.
2396 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002397
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002398 if (!R.empty())
2399 return false;
2400
2401 // We didn't find anything with the given name, so try to correct
2402 // for typos.
2403 DeclarationName Name = R.getLookupName();
2404 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2405 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2406 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2407 << Name << DC << R.getLookupName() << SS.getRange()
2408 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2409 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002410 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2411 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2412 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002413 return false;
2414 } else {
2415 R.clear();
2416 }
2417
John McCall10eae182009-11-30 22:42:35 +00002418 return false;
2419}
2420
2421Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002422Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002423 SourceLocation OpLoc, bool IsArrow,
2424 const CXXScopeSpec &SS,
2425 NamedDecl *FirstQualifierInScope,
2426 DeclarationName Name, SourceLocation NameLoc,
2427 const TemplateArgumentListInfo *TemplateArgs) {
2428 Expr *Base = BaseArg.takeAs<Expr>();
2429
John McCallcd4b4772009-12-02 03:53:29 +00002430 if (BaseType->isDependentType() ||
2431 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002432 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002433 IsArrow, OpLoc,
2434 SS, FirstQualifierInScope,
2435 Name, NameLoc,
2436 TemplateArgs);
2437
2438 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002439
John McCall2d74de92009-12-01 22:10:20 +00002440 // Implicit member accesses.
2441 if (!Base) {
2442 QualType RecordTy = BaseType;
2443 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2444 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2445 RecordTy->getAs<RecordType>(),
2446 OpLoc, SS))
2447 return ExprError();
2448
2449 // Explicit member accesses.
2450 } else {
2451 OwningExprResult Result =
2452 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2453 SS, FirstQualifierInScope,
2454 /*ObjCImpDecl*/ DeclPtrTy());
2455
2456 if (Result.isInvalid()) {
2457 Owned(Base);
2458 return ExprError();
2459 }
2460
2461 if (Result.get())
2462 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002463 }
2464
John McCall2d74de92009-12-01 22:10:20 +00002465 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2466 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002467}
2468
2469Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002470Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2471 SourceLocation OpLoc, bool IsArrow,
2472 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002473 LookupResult &R,
2474 const TemplateArgumentListInfo *TemplateArgs) {
2475 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002476 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002477 if (IsArrow) {
2478 assert(BaseType->isPointerType());
2479 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2480 }
2481
2482 NestedNameSpecifier *Qualifier =
2483 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2484 DeclarationName MemberName = R.getLookupName();
2485 SourceLocation MemberLoc = R.getNameLoc();
2486
2487 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002488 return ExprError();
2489
John McCall10eae182009-11-30 22:42:35 +00002490 if (R.empty()) {
2491 // Rederive where we looked up.
2492 DeclContext *DC = (SS.isSet()
2493 ? computeDeclContext(SS, false)
2494 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002495
John McCall10eae182009-11-30 22:42:35 +00002496 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002497 << MemberName << DC
2498 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002499 return ExprError();
2500 }
2501
John McCallcd4b4772009-12-02 03:53:29 +00002502 // Diagnose qualified lookups that find only declarations from a
2503 // non-base type. Note that it's okay for lookup to find
2504 // declarations from a non-base type as long as those aren't the
2505 // ones picked by overload resolution.
2506 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002507 return ExprError();
2508
2509 // Construct an unresolved result if we in fact got an unresolved
2510 // result.
2511 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002512 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002513 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002514 R.isUnresolvableResult() ||
2515 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002516
2517 UnresolvedMemberExpr *MemExpr
2518 = UnresolvedMemberExpr::Create(Context, Dependent,
2519 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002520 BaseExpr, BaseExprType,
2521 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002522 Qualifier, SS.getRange(),
2523 MemberName, MemberLoc,
2524 TemplateArgs);
2525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2526 MemExpr->addDecl(*I);
2527
2528 return Owned(MemExpr);
2529 }
2530
2531 assert(R.isSingleResult());
2532 NamedDecl *MemberDecl = R.getFoundDecl();
2533
2534 // FIXME: diagnose the presence of template arguments now.
2535
2536 // If the decl being referenced had an error, return an error for this
2537 // sub-expr without emitting another error, in order to avoid cascading
2538 // error cases.
2539 if (MemberDecl->isInvalidDecl())
2540 return ExprError();
2541
John McCall2d74de92009-12-01 22:10:20 +00002542 // Handle the implicit-member-access case.
2543 if (!BaseExpr) {
2544 // If this is not an instance member, convert to a non-member access.
2545 if (!IsInstanceMember(MemberDecl))
2546 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2547
Douglas Gregorb15af892010-01-07 23:12:05 +00002548 SourceLocation Loc = R.getNameLoc();
2549 if (SS.getRange().isValid())
2550 Loc = SS.getRange().getBegin();
2551 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002552 }
2553
John McCall10eae182009-11-30 22:42:35 +00002554 bool ShouldCheckUse = true;
2555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2556 // Don't diagnose the use of a virtual member function unless it's
2557 // explicitly qualified.
2558 if (MD->isVirtual() && !SS.isSet())
2559 ShouldCheckUse = false;
2560 }
2561
2562 // Check the use of this member.
2563 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2564 Owned(BaseExpr);
2565 return ExprError();
2566 }
2567
2568 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2569 // We may have found a field within an anonymous union or struct
2570 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002571 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2572 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002573 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2574 BaseExpr, OpLoc);
2575
2576 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2577 QualType MemberType = FD->getType();
2578 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2579 MemberType = Ref->getPointeeType();
2580 else {
2581 Qualifiers BaseQuals = BaseType.getQualifiers();
2582 BaseQuals.removeObjCGCAttr();
2583 if (FD->isMutable()) BaseQuals.removeConst();
2584
2585 Qualifiers MemberQuals
2586 = Context.getCanonicalType(MemberType).getQualifiers();
2587
2588 Qualifiers Combined = BaseQuals + MemberQuals;
2589 if (Combined != MemberQuals)
2590 MemberType = Context.getQualifiedType(MemberType, Combined);
2591 }
2592
2593 MarkDeclarationReferenced(MemberLoc, FD);
2594 if (PerformObjectMemberConversion(BaseExpr, FD))
2595 return ExprError();
2596 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2597 FD, MemberLoc, MemberType));
2598 }
2599
2600 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2601 MarkDeclarationReferenced(MemberLoc, Var);
2602 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2603 Var, MemberLoc,
2604 Var->getType().getNonReferenceType()));
2605 }
2606
2607 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2608 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2609 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2610 MemberFn, MemberLoc,
2611 MemberFn->getType()));
2612 }
2613
2614 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2615 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2616 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2617 Enum, MemberLoc, Enum->getType()));
2618 }
2619
2620 Owned(BaseExpr);
2621
2622 if (isa<TypeDecl>(MemberDecl))
2623 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2624 << MemberName << int(IsArrow));
2625
2626 // We found a declaration kind that we didn't expect. This is a
2627 // generic error message that tells the user that she can't refer
2628 // to this member with '.' or '->'.
2629 return ExprError(Diag(MemberLoc,
2630 diag::err_typecheck_member_reference_unknown)
2631 << MemberName << int(IsArrow));
2632}
2633
2634/// Look up the given member of the given non-type-dependent
2635/// expression. This can return in one of two ways:
2636/// * If it returns a sentinel null-but-valid result, the caller will
2637/// assume that lookup was performed and the results written into
2638/// the provided structure. It will take over from there.
2639/// * Otherwise, the returned expression will be produced in place of
2640/// an ordinary member expression.
2641///
2642/// The ObjCImpDecl bit is a gross hack that will need to be properly
2643/// fixed for ObjC++.
2644Sema::OwningExprResult
2645Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002646 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002647 const CXXScopeSpec &SS,
2648 NamedDecl *FirstQualifierInScope,
2649 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002650 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002651
Steve Naroffeaaae462007-12-16 21:42:28 +00002652 // Perform default conversions.
2653 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002654
Steve Naroff185616f2007-07-26 03:11:44 +00002655 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002656 assert(!BaseType->isDependentType());
2657
2658 DeclarationName MemberName = R.getLookupName();
2659 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002660
2661 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002662 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002663 // function. Suggest the addition of those parentheses, build the
2664 // call, and continue on.
2665 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2666 if (const FunctionProtoType *Fun
2667 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2668 QualType ResultTy = Fun->getResultType();
2669 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002670 ((!IsArrow && ResultTy->isRecordType()) ||
2671 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002672 ResultTy->getAs<PointerType>()->getPointeeType()
2673 ->isRecordType()))) {
2674 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2675 Diag(Loc, diag::err_member_reference_needs_call)
2676 << QualType(Fun, 0)
2677 << CodeModificationHint::CreateInsertion(Loc, "()");
2678
2679 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002680 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002681 MultiExprArg(*this, 0, 0), 0, Loc);
2682 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002683 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002684
2685 BaseExpr = NewBase.takeAs<Expr>();
2686 DefaultFunctionArrayConversion(BaseExpr);
2687 BaseType = BaseExpr->getType();
2688 }
2689 }
2690 }
2691
David Chisnall9f57c292009-08-17 16:35:33 +00002692 // If this is an Objective-C pseudo-builtin and a definition is provided then
2693 // use that.
2694 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002695 if (IsArrow) {
2696 // Handle the following exceptional case PObj->isa.
2697 if (const ObjCObjectPointerType *OPT =
2698 BaseType->getAs<ObjCObjectPointerType>()) {
2699 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2700 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002701 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2702 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002703 }
2704 }
David Chisnall9f57c292009-08-17 16:35:33 +00002705 // We have an 'id' type. Rather than fall through, we check if this
2706 // is a reference to 'isa'.
2707 if (BaseType != Context.ObjCIdRedefinitionType) {
2708 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002709 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002710 }
David Chisnall9f57c292009-08-17 16:35:33 +00002711 }
John McCall10eae182009-11-30 22:42:35 +00002712
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002713 // If this is an Objective-C pseudo-builtin and a definition is provided then
2714 // use that.
2715 if (Context.isObjCSelType(BaseType)) {
2716 // We have an 'SEL' type. Rather than fall through, we check if this
2717 // is a reference to 'sel_id'.
2718 if (BaseType != Context.ObjCSelRedefinitionType) {
2719 BaseType = Context.ObjCSelRedefinitionType;
2720 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2721 }
2722 }
John McCall10eae182009-11-30 22:42:35 +00002723
Steve Naroff185616f2007-07-26 03:11:44 +00002724 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002725
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002726 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002727 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002728 // Also must look for a getter name which uses property syntax.
2729 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2730 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2731 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2732 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2733 ObjCMethodDecl *Getter;
2734 // FIXME: need to also look locally in the implementation.
2735 if ((Getter = IFace->lookupClassMethod(Sel))) {
2736 // Check the use of this method.
2737 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2738 return ExprError();
2739 }
2740 // If we found a getter then this may be a valid dot-reference, we
2741 // will look for the matching setter, in case it is needed.
2742 Selector SetterSel =
2743 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2744 PP.getSelectorTable(), Member);
2745 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2746 if (!Setter) {
2747 // If this reference is in an @implementation, also check for 'private'
2748 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002749 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002750 }
2751 // Look through local category implementations associated with the class.
2752 if (!Setter)
2753 Setter = IFace->getCategoryClassMethod(SetterSel);
2754
2755 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2756 return ExprError();
2757
2758 if (Getter || Setter) {
2759 QualType PType;
2760
2761 if (Getter)
2762 PType = Getter->getResultType();
2763 else
2764 // Get the expression type from Setter's incoming parameter.
2765 PType = (*(Setter->param_end() -1))->getType();
2766 // FIXME: we must check that the setter has property type.
2767 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2768 PType,
2769 Setter, MemberLoc, BaseExpr));
2770 }
2771 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2772 << MemberName << BaseType);
2773 }
2774 }
2775
2776 if (BaseType->isObjCClassType() &&
2777 BaseType != Context.ObjCClassRedefinitionType) {
2778 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002779 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
John McCall10eae182009-11-30 22:42:35 +00002782 if (IsArrow) {
2783 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002784 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002785 else if (BaseType->isObjCObjectPointerType())
2786 ;
John McCalla928c652009-12-07 22:46:59 +00002787 else if (BaseType->isRecordType()) {
2788 // Recover from arrow accesses to records, e.g.:
2789 // struct MyRecord foo;
2790 // foo->bar
2791 // This is actually well-formed in C++ if MyRecord has an
2792 // overloaded operator->, but that should have been dealt with
2793 // by now.
2794 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2795 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2796 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2797 IsArrow = false;
2798 } else {
John McCall10eae182009-11-30 22:42:35 +00002799 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2800 << BaseType << BaseExpr->getSourceRange();
2801 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002802 }
John McCalla928c652009-12-07 22:46:59 +00002803 } else {
2804 // Recover from dot accesses to pointers, e.g.:
2805 // type *foo;
2806 // foo.bar
2807 // This is actually well-formed in two cases:
2808 // - 'type' is an Objective C type
2809 // - 'bar' is a pseudo-destructor name which happens to refer to
2810 // the appropriate pointer type
2811 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2812 const PointerType *PT = BaseType->getAs<PointerType>();
2813 if (PT && PT->getPointeeType()->isRecordType()) {
2814 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2815 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2816 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2817 BaseType = PT->getPointeeType();
2818 IsArrow = true;
2819 }
2820 }
John McCall10eae182009-11-30 22:42:35 +00002821 }
John McCalla928c652009-12-07 22:46:59 +00002822
John McCall10eae182009-11-30 22:42:35 +00002823 // Handle field access to simple records. This also handles access
2824 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002825 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002826 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2827 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002828 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002829 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002830 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002831
Douglas Gregorad8a3362009-09-04 17:36:40 +00002832 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2833 // into a record type was handled above, any destructor we see here is a
2834 // pseudo-destructor.
2835 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2836 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002837 // The left hand side of the dot operator shall be of scalar type. The
2838 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002839 // type.
2840 if (!BaseType->isScalarType())
2841 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2842 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002843
Douglas Gregorad8a3362009-09-04 17:36:40 +00002844 // [...] The type designated by the pseudo-destructor-name shall be the
2845 // same as the object type.
2846 if (!MemberName.getCXXNameType()->isDependentType() &&
2847 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2848 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2849 << BaseType << MemberName.getCXXNameType()
2850 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002851
2852 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002853 // the form
2854 //
Mike Stump11289f42009-09-09 15:08:12 +00002855 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2856 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002857 // shall designate the same scalar type.
2858 //
2859 // FIXME: DPG can't see any way to trigger this particular clause, so it
2860 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002861
Douglas Gregorad8a3362009-09-04 17:36:40 +00002862 // FIXME: We've lost the precise spelling of the type by going through
2863 // DeclarationName. Can we do better?
2864 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002865 IsArrow, OpLoc,
2866 (NestedNameSpecifier *) SS.getScopeRep(),
2867 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002868 MemberName.getCXXNameType(),
2869 MemberLoc));
2870 }
Mike Stump11289f42009-09-09 15:08:12 +00002871
Chris Lattnerdc420f42008-07-21 04:59:05 +00002872 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2873 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002874 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2875 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002876 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002877 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002878 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002879 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002880 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2881
Steve Naroffa057ba92009-07-16 00:25:06 +00002882 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2883 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002884 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002886 if (!IV) {
2887 // Attempt to correct for typos in ivar names.
2888 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2889 LookupMemberName);
2890 if (CorrectTypo(Res, 0, 0, IDecl) &&
2891 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2892 Diag(R.getNameLoc(),
2893 diag::err_typecheck_member_reference_ivar_suggest)
2894 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2895 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2896 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002897 Diag(IV->getLocation(), diag::note_previous_decl)
2898 << IV->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002899 }
2900 }
2901
Steve Naroffa057ba92009-07-16 00:25:06 +00002902 if (IV) {
2903 // If the decl being referenced had an error, return an error for this
2904 // sub-expr without emitting another error, in order to avoid cascading
2905 // error cases.
2906 if (IV->isInvalidDecl())
2907 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002908
Steve Naroffa057ba92009-07-16 00:25:06 +00002909 // Check whether we can reference this field.
2910 if (DiagnoseUseOfDecl(IV, MemberLoc))
2911 return ExprError();
2912 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2913 IV->getAccessControl() != ObjCIvarDecl::Package) {
2914 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2915 if (ObjCMethodDecl *MD = getCurMethodDecl())
2916 ClassOfMethodDecl = MD->getClassInterface();
2917 else if (ObjCImpDecl && getCurFunctionDecl()) {
2918 // Case of a c-function declared inside an objc implementation.
2919 // FIXME: For a c-style function nested inside an objc implementation
2920 // class, there is no implementation context available, so we pass
2921 // down the context as argument to this routine. Ideally, this context
2922 // need be passed down in the AST node and somehow calculated from the
2923 // AST for a function decl.
2924 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002925 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002926 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2927 ClassOfMethodDecl = IMPD->getClassInterface();
2928 else if (ObjCCategoryImplDecl* CatImplClass =
2929 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2930 ClassOfMethodDecl = CatImplClass->getClassInterface();
2931 }
Mike Stump11289f42009-09-09 15:08:12 +00002932
2933 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2934 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002935 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002936 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002937 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002938 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2939 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002940 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002941 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002942 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002943
2944 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2945 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002946 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002947 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002948 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002949 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002950 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002951 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002952 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002953 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002954 if (!IsArrow && (BaseType->isObjCIdType() ||
2955 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002956 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002957 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002958
Steve Naroff7cae42b2009-07-10 23:34:53 +00002959 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002960 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002961 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2962 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2963 // Check the use of this declaration
2964 if (DiagnoseUseOfDecl(PD, MemberLoc))
2965 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002966
Steve Naroff7cae42b2009-07-10 23:34:53 +00002967 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2968 MemberLoc, BaseExpr));
2969 }
2970 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2971 // Check the use of this method.
2972 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2973 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002974
Steve Naroff7cae42b2009-07-10 23:34:53 +00002975 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002976 OMD->getResultType(),
2977 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002978 NULL, 0));
2979 }
2980 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002981
Steve Naroff7cae42b2009-07-10 23:34:53 +00002982 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002983 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002984 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002985 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2986 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002987 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002988 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002989 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2990 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002991 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002992
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002993 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002994 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002995 // Check whether we can reference this property.
2996 if (DiagnoseUseOfDecl(PD, MemberLoc))
2997 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002998 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002999 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003000 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00003001 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3002 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003003 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00003004 MemberLoc, BaseExpr));
3005 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003006 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00003007 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3008 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00003009 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003010 // Check whether we can reference this property.
3011 if (DiagnoseUseOfDecl(PD, MemberLoc))
3012 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00003013
Steve Narofff6009ed2009-01-21 00:14:39 +00003014 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00003015 MemberLoc, BaseExpr));
3016 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003017 // If that failed, look for an "implicit" property by seeing if the nullary
3018 // selector is implemented.
3019
3020 // FIXME: The logic for looking up nullary and unary selectors should be
3021 // shared with the code in ActOnInstanceMessage.
3022
Anders Carlssonf571c112009-08-26 18:25:21 +00003023 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003024 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003025
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003026 // If this reference is in an @implementation, check for 'private' methods.
3027 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00003028 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003029
Steve Naroff1df62692008-10-22 19:16:27 +00003030 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003031 if (!Getter)
3032 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003033 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003034 // Check if we can reference this property.
3035 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3036 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003037 }
3038 // If we found a getter then this may be a valid dot-reference, we
3039 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00003040 Selector SetterSel =
3041 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00003042 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003043 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003044 if (!Setter) {
3045 // If this reference is in an @implementation, also check for 'private'
3046 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003047 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003048 }
3049 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003050 if (!Setter)
3051 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003052
Steve Naroff1d984fe2009-03-11 13:48:17 +00003053 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3054 return ExprError();
3055
3056 if (Getter || Setter) {
3057 QualType PType;
3058
3059 if (Getter)
3060 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00003061 else
3062 // Get the expression type from Setter's incoming parameter.
3063 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003064 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00003065 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00003066 Setter, MemberLoc, BaseExpr));
3067 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003068
3069 // Attempt to correct for typos in property names.
3070 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3071 LookupOrdinaryName);
3072 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3073 Res.getAsSingle<ObjCPropertyDecl>()) {
3074 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3075 << MemberName << BaseType << Res.getLookupName()
3076 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3077 Res.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003078 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3079 Diag(Property->getLocation(), diag::note_previous_decl)
3080 << Property->getDeclName();
3081
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003082 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
3083 FirstQualifierInScope, ObjCImpDecl);
3084 }
3085
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003086 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003087 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00003088 }
Mike Stump11289f42009-09-09 15:08:12 +00003089
Steve Naroffe87026a2009-07-24 17:54:45 +00003090 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003091 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00003092 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003093 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003094 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003095 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003096
Chris Lattnerb63a7452008-07-21 04:28:12 +00003097 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003098 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003099 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003100 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3101 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003102 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003103 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003104 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003105 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003106
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003107 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3108 << BaseType << BaseExpr->getSourceRange();
3109
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003110 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003111}
3112
John McCall10eae182009-11-30 22:42:35 +00003113static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3114 SourceLocation NameLoc,
3115 Sema::ExprArg MemExpr) {
3116 Expr *E = (Expr *) MemExpr.get();
3117 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3118 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00003119 << isa<CXXPseudoDestructorExpr>(E)
3120 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3121
John McCall10eae182009-11-30 22:42:35 +00003122 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3123 move(MemExpr),
3124 /*LPLoc*/ ExpectedLParenLoc,
3125 Sema::MultiExprArg(SemaRef, 0, 0),
3126 /*CommaLocs*/ 0,
3127 /*RPLoc*/ ExpectedLParenLoc);
3128}
3129
3130/// The main callback when the parser finds something like
3131/// expression . [nested-name-specifier] identifier
3132/// expression -> [nested-name-specifier] identifier
3133/// where 'identifier' encompasses a fairly broad spectrum of
3134/// possibilities, including destructor and operator references.
3135///
3136/// \param OpKind either tok::arrow or tok::period
3137/// \param HasTrailingLParen whether the next token is '(', which
3138/// is used to diagnose mis-uses of special members that can
3139/// only be called
3140/// \param ObjCImpDecl the current ObjC @implementation decl;
3141/// this is an ugly hack around the fact that ObjC @implementations
3142/// aren't properly put in the context chain
3143Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3144 SourceLocation OpLoc,
3145 tok::TokenKind OpKind,
3146 const CXXScopeSpec &SS,
3147 UnqualifiedId &Id,
3148 DeclPtrTy ObjCImpDecl,
3149 bool HasTrailingLParen) {
3150 if (SS.isSet() && SS.isInvalid())
3151 return ExprError();
3152
3153 TemplateArgumentListInfo TemplateArgsBuffer;
3154
3155 // Decompose the name into its component parts.
3156 DeclarationName Name;
3157 SourceLocation NameLoc;
3158 const TemplateArgumentListInfo *TemplateArgs;
3159 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3160 Name, NameLoc, TemplateArgs);
3161
3162 bool IsArrow = (OpKind == tok::arrow);
3163
3164 NamedDecl *FirstQualifierInScope
3165 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3166 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3167
3168 // This is a postfix expression, so get rid of ParenListExprs.
3169 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3170
3171 Expr *Base = BaseArg.takeAs<Expr>();
3172 OwningExprResult Result(*this);
3173 if (Base->getType()->isDependentType()) {
John McCall2d74de92009-12-01 22:10:20 +00003174 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003175 IsArrow, OpLoc,
3176 SS, FirstQualifierInScope,
3177 Name, NameLoc,
3178 TemplateArgs);
3179 } else {
3180 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3181 if (TemplateArgs) {
3182 // Re-use the lookup done for the template name.
3183 DecomposeTemplateName(R, Id);
3184 } else {
3185 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3186 SS, FirstQualifierInScope,
3187 ObjCImpDecl);
3188
3189 if (Result.isInvalid()) {
3190 Owned(Base);
3191 return ExprError();
3192 }
3193
3194 if (Result.get()) {
3195 // The only way a reference to a destructor can be used is to
3196 // immediately call it, which falls into this case. If the
3197 // next token is not a '(', produce a diagnostic and build the
3198 // call now.
3199 if (!HasTrailingLParen &&
3200 Id.getKind() == UnqualifiedId::IK_DestructorName)
3201 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3202
3203 return move(Result);
3204 }
3205 }
3206
John McCall2d74de92009-12-01 22:10:20 +00003207 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3208 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003209 }
3210
3211 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003212}
3213
Anders Carlsson355933d2009-08-25 03:49:14 +00003214Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3215 FunctionDecl *FD,
3216 ParmVarDecl *Param) {
3217 if (Param->hasUnparsedDefaultArg()) {
3218 Diag (CallLoc,
3219 diag::err_use_of_default_argument_to_function_declared_later) <<
3220 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003221 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003222 diag::note_default_argument_declared_here);
3223 } else {
3224 if (Param->hasUninstantiatedDefaultArg()) {
3225 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3226
3227 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003228 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003229
Mike Stump11289f42009-09-09 15:08:12 +00003230 InstantiatingTemplate Inst(*this, CallLoc, Param,
3231 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003232 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003233
John McCall76d824f2009-08-25 22:02:44 +00003234 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003235 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003236 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003237
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003238 // Check the expression as an initializer for the parameter.
3239 InitializedEntity Entity
3240 = InitializedEntity::InitializeParameter(Param);
3241 InitializationKind Kind
3242 = InitializationKind::CreateCopy(Param->getLocation(),
3243 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3244 Expr *ResultE = Result.takeAs<Expr>();
3245
3246 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3247 Result = InitSeq.Perform(*this, Entity, Kind,
3248 MultiExprArg(*this, (void**)&ResultE, 1));
3249 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003250 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003251
3252 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003253 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003254 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003255 }
Mike Stump11289f42009-09-09 15:08:12 +00003256
Anders Carlsson355933d2009-08-25 03:49:14 +00003257 // If the default expression creates temporaries, we need to
3258 // push them to the current stack of expression temporaries so they'll
3259 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003260 // FIXME: We should really be rebuilding the default argument with new
3261 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003262 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3263 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003264 }
3265
3266 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003267 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003268}
3269
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003270/// ConvertArgumentsForCall - Converts the arguments specified in
3271/// Args/NumArgs to the parameter types of the function FDecl with
3272/// function prototype Proto. Call is the call expression itself, and
3273/// Fn is the function expression. For a C++ member function, this
3274/// routine does not attempt to convert the object argument. Returns
3275/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003276bool
3277Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003278 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003279 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003280 Expr **Args, unsigned NumArgs,
3281 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003282 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003283 // assignment, to the types of the corresponding parameter, ...
3284 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003285 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003286
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003287 // If too few arguments are available (and we don't have default
3288 // arguments for the remaining parameters), don't make the call.
3289 if (NumArgs < NumArgsInProto) {
3290 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3291 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3292 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003293 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003294 }
3295
3296 // If too many are passed and not variadic, error on the extras and drop
3297 // them.
3298 if (NumArgs > NumArgsInProto) {
3299 if (!Proto->isVariadic()) {
3300 Diag(Args[NumArgsInProto]->getLocStart(),
3301 diag::err_typecheck_call_too_many_args)
3302 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3303 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3304 Args[NumArgs-1]->getLocEnd());
3305 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003306 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003307 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003308 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003309 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003310 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003311 VariadicCallType CallType =
3312 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3313 if (Fn->getType()->isBlockPointerType())
3314 CallType = VariadicBlock; // Block
3315 else if (isa<MemberExpr>(Fn))
3316 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003317 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003318 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003319 if (Invalid)
3320 return true;
3321 unsigned TotalNumArgs = AllArgs.size();
3322 for (unsigned i = 0; i < TotalNumArgs; ++i)
3323 Call->setArg(i, AllArgs[i]);
3324
3325 return false;
3326}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003327
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003328bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3329 FunctionDecl *FDecl,
3330 const FunctionProtoType *Proto,
3331 unsigned FirstProtoArg,
3332 Expr **Args, unsigned NumArgs,
3333 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003334 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003335 unsigned NumArgsInProto = Proto->getNumArgs();
3336 unsigned NumArgsToCheck = NumArgs;
3337 bool Invalid = false;
3338 if (NumArgs != NumArgsInProto)
3339 // Use default arguments for missing arguments
3340 NumArgsToCheck = NumArgsInProto;
3341 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003342 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003343 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003344 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003345
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003346 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003347 if (ArgIx < NumArgs) {
3348 Arg = Args[ArgIx++];
3349
Eli Friedman3164fb12009-03-22 22:00:50 +00003350 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3351 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003352 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003353 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003354 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003355
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003356 // Pass the argument
3357 ParmVarDecl *Param = 0;
3358 if (FDecl && i < FDecl->getNumParams())
3359 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003360
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003361
3362 InitializedEntity Entity =
3363 Param? InitializedEntity::InitializeParameter(Param)
3364 : InitializedEntity::InitializeParameter(ProtoArgType);
3365 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3366 SourceLocation(),
3367 Owned(Arg));
3368 if (ArgE.isInvalid())
3369 return true;
3370
3371 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003372 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003373 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003374
Mike Stump11289f42009-09-09 15:08:12 +00003375 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003376 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003377 if (ArgExpr.isInvalid())
3378 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003379
Anders Carlsson355933d2009-08-25 03:49:14 +00003380 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003381 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003382 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003383 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003384
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003385 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003386 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003387 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003388 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003389 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003390 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003391 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003392 }
3393 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003394 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003395}
3396
Steve Naroff83895f72007-09-16 03:34:24 +00003397/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003398/// This provides the location of the left/right parens and a list of comma
3399/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003400Action::OwningExprResult
3401Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3402 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003403 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003404 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003405
3406 // Since this might be a postfix expression, get rid of ParenListExprs.
3407 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003408
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003409 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003410 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003411 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003412
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003413 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003414 // If this is a pseudo-destructor expression, build the call immediately.
3415 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3416 if (NumArgs > 0) {
3417 // Pseudo-destructor calls should not have any arguments.
3418 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3419 << CodeModificationHint::CreateRemoval(
3420 SourceRange(Args[0]->getLocStart(),
3421 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003422
Douglas Gregorad8a3362009-09-04 17:36:40 +00003423 for (unsigned I = 0; I != NumArgs; ++I)
3424 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003425
Douglas Gregorad8a3362009-09-04 17:36:40 +00003426 NumArgs = 0;
3427 }
Mike Stump11289f42009-09-09 15:08:12 +00003428
Douglas Gregorad8a3362009-09-04 17:36:40 +00003429 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3430 RParenLoc));
3431 }
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003433 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003434 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003435 // FIXME: Will need to cache the results of name lookup (including ADL) in
3436 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003437 bool Dependent = false;
3438 if (Fn->isTypeDependent())
3439 Dependent = true;
3440 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3441 Dependent = true;
3442
3443 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003444 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003445 Context.DependentTy, RParenLoc));
3446
3447 // Determine whether this is a call to an object (C++ [over.call.object]).
3448 if (Fn->getType()->isRecordType())
3449 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3450 CommaLocs, RParenLoc));
3451
John McCall10eae182009-11-30 22:42:35 +00003452 Expr *NakedFn = Fn->IgnoreParens();
3453
3454 // Determine whether this is a call to an unresolved member function.
3455 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3456 // If lookup was unresolved but not dependent (i.e. didn't find
3457 // an unresolved using declaration), it has to be an overloaded
3458 // function set, which means it must contain either multiple
3459 // declarations (all methods or method templates) or a single
3460 // method template.
3461 assert((MemE->getNumDecls() > 1) ||
3462 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003463 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003464
John McCall2d74de92009-12-01 22:10:20 +00003465 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3466 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003467 }
3468
Douglas Gregore254f902009-02-04 00:32:51 +00003469 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003470 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003471 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003472 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003473 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3474 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003475 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003476
3477 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003478 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003479 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3480 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003481 if (const FunctionProtoType *FPT =
3482 dyn_cast<FunctionProtoType>(BO->getType())) {
3483 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003484
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003485 ExprOwningPtr<CXXMemberCallExpr>
3486 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3487 NumArgs, ResultTy,
3488 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003489
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003490 if (CheckCallReturnType(FPT->getResultType(),
3491 BO->getRHS()->getSourceRange().getBegin(),
3492 TheCall.get(), 0))
3493 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003494
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003495 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3496 RParenLoc))
3497 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003498
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003499 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3500 }
3501 return ExprError(Diag(Fn->getLocStart(),
3502 diag::err_typecheck_call_not_function)
3503 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003504 }
3505 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003506 }
3507
Douglas Gregore254f902009-02-04 00:32:51 +00003508 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003509 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003510 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003511
Eli Friedmane14b1992009-12-26 03:35:45 +00003512 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003513 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3514 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3515 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3516 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003517 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003518
John McCall57500772009-12-16 12:17:52 +00003519 NamedDecl *NDecl = 0;
3520 if (isa<DeclRefExpr>(NakedFn))
3521 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3522
John McCall2d74de92009-12-01 22:10:20 +00003523 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3524}
3525
John McCall57500772009-12-16 12:17:52 +00003526/// BuildResolvedCallExpr - Build a call to a resolved expression,
3527/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003528/// unary-convert to an expression of function-pointer or
3529/// block-pointer type.
3530///
3531/// \param NDecl the declaration being called, if available
3532Sema::OwningExprResult
3533Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3534 SourceLocation LParenLoc,
3535 Expr **Args, unsigned NumArgs,
3536 SourceLocation RParenLoc) {
3537 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3538
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003539 // Promote the function operand.
3540 UsualUnaryConversions(Fn);
3541
Chris Lattner08464942007-12-28 05:29:59 +00003542 // Make the call expr early, before semantic checks. This guarantees cleanup
3543 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003544 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3545 Args, NumArgs,
3546 Context.BoolTy,
3547 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003548
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003549 const FunctionType *FuncT;
3550 if (!Fn->getType()->isBlockPointerType()) {
3551 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3552 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003553 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003554 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003555 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3556 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003557 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003558 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003559 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003560 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003561 }
Chris Lattner08464942007-12-28 05:29:59 +00003562 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003563 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3564 << Fn->getType() << Fn->getSourceRange());
3565
Eli Friedman3164fb12009-03-22 22:00:50 +00003566 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003567 if (CheckCallReturnType(FuncT->getResultType(),
3568 Fn->getSourceRange().getBegin(), TheCall.get(),
3569 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003570 return ExprError();
3571
Chris Lattner08464942007-12-28 05:29:59 +00003572 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003573 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003574
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003575 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003576 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003577 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003578 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003579 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003580 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003581
Douglas Gregord8e97de2009-04-02 15:37:10 +00003582 if (FDecl) {
3583 // Check if we have too few/too many template arguments, based
3584 // on our knowledge of the function definition.
3585 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003586 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003587 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003588 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003589 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3590 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3591 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3592 }
3593 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003594 }
3595
Steve Naroff0b661582007-08-28 23:30:39 +00003596 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003597 for (unsigned i = 0; i != NumArgs; i++) {
3598 Expr *Arg = Args[i];
3599 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003600 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3601 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003602 PDiag(diag::err_call_incomplete_argument)
3603 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003604 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003605 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003606 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003607 }
Chris Lattner08464942007-12-28 05:29:59 +00003608
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003609 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3610 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003611 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3612 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003613
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003614 // Check for sentinels
3615 if (NDecl)
3616 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003617
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003618 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003619 if (FDecl) {
3620 if (CheckFunctionCall(FDecl, TheCall.get()))
3621 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003622
Douglas Gregor15fc9562009-09-12 00:22:50 +00003623 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003624 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3625 } else if (NDecl) {
3626 if (CheckBlockCall(NDecl, TheCall.get()))
3627 return ExprError();
3628 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003629
Anders Carlssonf8984012009-08-16 03:06:32 +00003630 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003631}
3632
Sebastian Redlb5d49352009-01-19 22:31:54 +00003633Action::OwningExprResult
3634Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3635 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003636 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003637
Douglas Gregor1b303932009-12-22 15:35:07 +00003638 QualType literalType = GetTypeFromParser(Ty);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003639
Steve Naroff57eb2c52007-07-19 21:32:11 +00003640 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003641 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003642 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003643
Eli Friedman37a186d2008-05-20 05:22:08 +00003644 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003645 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003646 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3647 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003648 } else if (!literalType->isDependentType() &&
3649 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003650 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003651 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003652 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003653 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003654
Douglas Gregor85dabae2009-12-16 01:38:02 +00003655 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003656 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003657 InitializationKind Kind
3658 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3659 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003660 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3661 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3662 MultiExprArg(*this, (void**)&literalExpr, 1),
3663 &literalType);
3664 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003665 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003666 InitExpr.release();
3667 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003668
Chris Lattner79413952008-12-04 23:50:19 +00003669 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003670 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003671 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003672 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003673 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003674
3675 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003676
3677 // FIXME: Store the TInfo to preserve type information better.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003678 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003679 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003680}
3681
Sebastian Redlb5d49352009-01-19 22:31:54 +00003682Action::OwningExprResult
3683Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003684 SourceLocation RBraceLoc) {
3685 unsigned NumInit = initlist.size();
3686 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003687
Steve Naroff30d242c2007-09-15 18:49:24 +00003688 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003689 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003690
Mike Stump4e1f26a2009-02-19 03:04:26 +00003691 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003692 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003693 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003694 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003695}
3696
Anders Carlsson094c4592009-10-18 18:12:03 +00003697static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3698 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003699 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003700 return CastExpr::CK_NoOp;
3701
3702 if (SrcTy->hasPointerRepresentation()) {
3703 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003704 return DestTy->isObjCObjectPointerType() ?
3705 CastExpr::CK_AnyPointerToObjCPointerCast :
3706 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003707 if (DestTy->isIntegerType())
3708 return CastExpr::CK_PointerToIntegral;
3709 }
3710
3711 if (SrcTy->isIntegerType()) {
3712 if (DestTy->isIntegerType())
3713 return CastExpr::CK_IntegralCast;
3714 if (DestTy->hasPointerRepresentation())
3715 return CastExpr::CK_IntegralToPointer;
3716 if (DestTy->isRealFloatingType())
3717 return CastExpr::CK_IntegralToFloating;
3718 }
3719
3720 if (SrcTy->isRealFloatingType()) {
3721 if (DestTy->isRealFloatingType())
3722 return CastExpr::CK_FloatingCast;
3723 if (DestTy->isIntegerType())
3724 return CastExpr::CK_FloatingToIntegral;
3725 }
3726
3727 // FIXME: Assert here.
3728 // assert(false && "Unhandled cast combination!");
3729 return CastExpr::CK_Unknown;
3730}
3731
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003732/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003733bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003734 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003735 CXXMethodDecl *& ConversionDecl,
3736 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003737 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003738 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3739 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003740
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003741 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003742
3743 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3744 // type needs to be scalar.
3745 if (castType->isVoidType()) {
3746 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003747 Kind = CastExpr::CK_ToVoid;
3748 return false;
3749 }
3750
3751 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003752 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003753 (castType->isStructureType() || castType->isUnionType())) {
3754 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003755 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003756 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3757 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003758 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003759 return false;
3760 }
3761
3762 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003763 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003764 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003765 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003766 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003767 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003768 if (Context.hasSameUnqualifiedType(Field->getType(),
3769 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003770 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3771 << castExpr->getSourceRange();
3772 break;
3773 }
3774 }
3775 if (Field == FieldEnd)
3776 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3777 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003778 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003779 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003780 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003781
3782 // Reject any other conversions to non-scalar types.
3783 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3784 << castType << castExpr->getSourceRange();
3785 }
3786
3787 if (!castExpr->getType()->isScalarType() &&
3788 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003789 return Diag(castExpr->getLocStart(),
3790 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003791 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003792 }
3793
Anders Carlsson43d70f82009-10-16 05:23:41 +00003794 if (castType->isExtVectorType())
3795 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3796
Anders Carlsson525b76b2009-10-16 02:48:28 +00003797 if (castType->isVectorType())
3798 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3799 if (castExpr->getType()->isVectorType())
3800 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3801
3802 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003803 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003804
Anders Carlsson43d70f82009-10-16 05:23:41 +00003805 if (isa<ObjCSelectorExpr>(castExpr))
3806 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3807
Anders Carlsson525b76b2009-10-16 02:48:28 +00003808 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003809 QualType castExprType = castExpr->getType();
3810 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3811 return Diag(castExpr->getLocStart(),
3812 diag::err_cast_pointer_from_non_pointer_int)
3813 << castExprType << castExpr->getSourceRange();
3814 } else if (!castExpr->getType()->isArithmeticType()) {
3815 if (!castType->isIntegralType() && castType->isArithmeticType())
3816 return Diag(castExpr->getLocStart(),
3817 diag::err_cast_pointer_to_non_pointer_int)
3818 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003819 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003820
3821 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003822 return false;
3823}
3824
Anders Carlsson525b76b2009-10-16 02:48:28 +00003825bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3826 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003827 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003828
Anders Carlssonde71adf2007-11-27 05:51:55 +00003829 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003830 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003831 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003832 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003833 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003834 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003835 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003836 } else
3837 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003838 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003839 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003840
Anders Carlsson525b76b2009-10-16 02:48:28 +00003841 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003842 return false;
3843}
3844
Anders Carlsson43d70f82009-10-16 05:23:41 +00003845bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3846 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003847 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003848
3849 QualType SrcTy = CastExpr->getType();
3850
Nate Begemanc8961a42009-06-27 22:05:55 +00003851 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3852 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003853 if (SrcTy->isVectorType()) {
3854 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3855 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3856 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003857 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003858 return false;
3859 }
3860
Nate Begemanbd956c42009-06-28 02:36:38 +00003861 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003862 // conversion will take place first from scalar to elt type, and then
3863 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003864 if (SrcTy->isPointerType())
3865 return Diag(R.getBegin(),
3866 diag::err_invalid_conversion_between_vector_and_scalar)
3867 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003868
3869 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3870 ImpCastExprToType(CastExpr, DestElemTy,
3871 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003872
3873 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003874 return false;
3875}
3876
Sebastian Redlb5d49352009-01-19 22:31:54 +00003877Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003878Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003879 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003880 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003881
Sebastian Redlb5d49352009-01-19 22:31:54 +00003882 assert((Ty != 0) && (Op.get() != 0) &&
3883 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003884
Nate Begeman5ec4b312009-08-10 23:49:36 +00003885 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003886 //FIXME: Preserve type source info.
3887 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003888
Nate Begeman5ec4b312009-08-10 23:49:36 +00003889 // If the Expr being casted is a ParenListExpr, handle it specially.
3890 if (isa<ParenListExpr>(castExpr))
3891 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003892 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003893 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003894 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003895 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003896
3897 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003898 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003899 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003900
Anders Carlssone9766d52009-09-09 21:33:21 +00003901 if (CastArg.isInvalid())
3902 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003903
Anders Carlssone9766d52009-09-09 21:33:21 +00003904 castExpr = CastArg.takeAs<Expr>();
3905 } else {
3906 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003907 }
Mike Stump11289f42009-09-09 15:08:12 +00003908
Sebastian Redl9f831db2009-07-25 15:41:38 +00003909 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003910 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003911 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003912}
3913
Nate Begeman5ec4b312009-08-10 23:49:36 +00003914/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3915/// of comma binary operators.
3916Action::OwningExprResult
3917Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3918 Expr *expr = EA.takeAs<Expr>();
3919 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3920 if (!E)
3921 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003922
Nate Begeman5ec4b312009-08-10 23:49:36 +00003923 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003924
Nate Begeman5ec4b312009-08-10 23:49:36 +00003925 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3926 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3927 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003928
Nate Begeman5ec4b312009-08-10 23:49:36 +00003929 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3930}
3931
3932Action::OwningExprResult
3933Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3934 SourceLocation RParenLoc, ExprArg Op,
3935 QualType Ty) {
3936 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003937
3938 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003939 // then handle it as such.
3940 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3941 if (PE->getNumExprs() == 0) {
3942 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3943 return ExprError();
3944 }
3945
3946 llvm::SmallVector<Expr *, 8> initExprs;
3947 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3948 initExprs.push_back(PE->getExpr(i));
3949
3950 // FIXME: This means that pretty-printing the final AST will produce curly
3951 // braces instead of the original commas.
3952 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003953 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003954 initExprs.size(), RParenLoc);
3955 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003956 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003957 Owned(E));
3958 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003959 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003960 // sequence of BinOp comma operators.
3961 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3962 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3963 }
3964}
3965
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003966Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003967 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003968 MultiExprArg Val,
3969 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003970 unsigned nexprs = Val.size();
3971 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003972 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3973 Expr *expr;
3974 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3975 expr = new (Context) ParenExpr(L, R, exprs[0]);
3976 else
3977 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003978 return Owned(expr);
3979}
3980
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003981/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3982/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003983/// C99 6.5.15
3984QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3985 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003986 // C++ is sufficiently different to merit its own checker.
3987 if (getLangOptions().CPlusPlus)
3988 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3989
John McCall1fa36b72009-11-05 09:23:39 +00003990 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3991
Chris Lattner432cff52009-02-18 04:28:32 +00003992 UsualUnaryConversions(Cond);
3993 UsualUnaryConversions(LHS);
3994 UsualUnaryConversions(RHS);
3995 QualType CondTy = Cond->getType();
3996 QualType LHSTy = LHS->getType();
3997 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003998
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003999 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004000 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4001 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4002 << CondTy;
4003 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004004 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004005
Chris Lattnere2949f42008-01-06 22:42:25 +00004006 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004007 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4008 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004009
Chris Lattnere2949f42008-01-06 22:42:25 +00004010 // If both operands have arithmetic type, do the usual arithmetic conversions
4011 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004012 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4013 UsualArithmeticConversions(LHS, RHS);
4014 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004015 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004016
Chris Lattnere2949f42008-01-06 22:42:25 +00004017 // If both operands are the same structure or union type, the result is that
4018 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004019 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4020 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004021 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004022 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004023 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004024 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004025 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004026 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004027
Chris Lattnere2949f42008-01-06 22:42:25 +00004028 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004029 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004030 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4031 if (!LHSTy->isVoidType())
4032 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4033 << RHS->getSourceRange();
4034 if (!RHSTy->isVoidType())
4035 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4036 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004037 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4038 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004039 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004040 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004041 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4042 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004043 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004044 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004045 // promote the null to a pointer.
4046 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004047 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004048 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004049 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004050 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004051 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004052 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004053 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004054
4055 // All objective-c pointer type analysis is done here.
4056 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4057 QuestionLoc);
4058 if (!compositeType.isNull())
4059 return compositeType;
4060
4061
Steve Naroff05efa972009-07-01 14:36:47 +00004062 // Handle block pointer types.
4063 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4064 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4065 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4066 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004067 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4068 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004069 return destType;
4070 }
4071 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004072 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004073 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004074 }
Steve Naroff05efa972009-07-01 14:36:47 +00004075 // We have 2 block pointer types.
4076 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4077 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004078 return LHSTy;
4079 }
Steve Naroff05efa972009-07-01 14:36:47 +00004080 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004081 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4082 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004083
Steve Naroff05efa972009-07-01 14:36:47 +00004084 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4085 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004086 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004087 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004088 // In this situation, we assume void* type. No especially good
4089 // reason, but this is what gcc does, and we do have to pick
4090 // to get a consistent AST.
4091 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004092 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4093 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004094 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004095 }
Steve Naroff05efa972009-07-01 14:36:47 +00004096 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004097 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4098 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004099 return LHSTy;
4100 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004101
Steve Naroff05efa972009-07-01 14:36:47 +00004102 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4103 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4104 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4106 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004107
4108 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4109 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4110 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004111 QualType destPointee
4112 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004113 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004114 // Add qualifiers if necessary.
4115 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4116 // Promote to void*.
4117 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004118 return destType;
4119 }
4120 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004121 QualType destPointee
4122 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004123 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004124 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004125 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004126 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004127 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004128 return destType;
4129 }
4130
4131 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4132 // Two identical pointer types are always compatible.
4133 return LHSTy;
4134 }
4135 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4136 rhptee.getUnqualifiedType())) {
4137 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4138 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4139 // In this situation, we assume void* type. No especially good
4140 // reason, but this is what gcc does, and we do have to pick
4141 // to get a consistent AST.
4142 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004143 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4144 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004145 return incompatTy;
4146 }
4147 // The pointer types are compatible.
4148 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4149 // differently qualified versions of compatible types, the result type is
4150 // a pointer to an appropriately qualified version of the *composite*
4151 // type.
4152 // FIXME: Need to calculate the composite type.
4153 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004154 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4155 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004156 return LHSTy;
4157 }
Mike Stump11289f42009-09-09 15:08:12 +00004158
Steve Naroff05efa972009-07-01 14:36:47 +00004159 // GCC compatibility: soften pointer/integer mismatch.
4160 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4161 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4162 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004163 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004164 return RHSTy;
4165 }
4166 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4167 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4168 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004169 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004170 return LHSTy;
4171 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004172
Chris Lattnere2949f42008-01-06 22:42:25 +00004173 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004174 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4175 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004176 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004177}
4178
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004179/// FindCompositeObjCPointerType - Helper method to find composite type of
4180/// two objective-c pointer types of the two input expressions.
4181QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4182 SourceLocation QuestionLoc) {
4183 QualType LHSTy = LHS->getType();
4184 QualType RHSTy = RHS->getType();
4185
4186 // Handle things like Class and struct objc_class*. Here we case the result
4187 // to the pseudo-builtin, because that will be implicitly cast back to the
4188 // redefinition type if an attempt is made to access its fields.
4189 if (LHSTy->isObjCClassType() &&
4190 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4191 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4192 return LHSTy;
4193 }
4194 if (RHSTy->isObjCClassType() &&
4195 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4196 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4197 return RHSTy;
4198 }
4199 // And the same for struct objc_object* / id
4200 if (LHSTy->isObjCIdType() &&
4201 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4202 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4203 return LHSTy;
4204 }
4205 if (RHSTy->isObjCIdType() &&
4206 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4207 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4208 return RHSTy;
4209 }
4210 // And the same for struct objc_selector* / SEL
4211 if (Context.isObjCSelType(LHSTy) &&
4212 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4213 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4214 return LHSTy;
4215 }
4216 if (Context.isObjCSelType(RHSTy) &&
4217 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4218 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4219 return RHSTy;
4220 }
4221 // Check constraints for Objective-C object pointers types.
4222 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4223
4224 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4225 // Two identical object pointer types are always compatible.
4226 return LHSTy;
4227 }
4228 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4229 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4230 QualType compositeType = LHSTy;
4231
4232 // If both operands are interfaces and either operand can be
4233 // assigned to the other, use that type as the composite
4234 // type. This allows
4235 // xxx ? (A*) a : (B*) b
4236 // where B is a subclass of A.
4237 //
4238 // Additionally, as for assignment, if either type is 'id'
4239 // allow silent coercion. Finally, if the types are
4240 // incompatible then make sure to use 'id' as the composite
4241 // type so the result is acceptable for sending messages to.
4242
4243 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4244 // It could return the composite type.
4245 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4246 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4247 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4248 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4249 } else if ((LHSTy->isObjCQualifiedIdType() ||
4250 RHSTy->isObjCQualifiedIdType()) &&
4251 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4252 // Need to handle "id<xx>" explicitly.
4253 // GCC allows qualified id and any Objective-C type to devolve to
4254 // id. Currently localizing to here until clear this should be
4255 // part of ObjCQualifiedIdTypesAreCompatible.
4256 compositeType = Context.getObjCIdType();
4257 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4258 compositeType = Context.getObjCIdType();
4259 } else if (!(compositeType =
4260 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4261 ;
4262 else {
4263 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4264 << LHSTy << RHSTy
4265 << LHS->getSourceRange() << RHS->getSourceRange();
4266 QualType incompatTy = Context.getObjCIdType();
4267 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4268 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4269 return incompatTy;
4270 }
4271 // The object pointer types are compatible.
4272 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4273 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4274 return compositeType;
4275 }
4276 // Check Objective-C object pointer types and 'void *'
4277 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4278 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4279 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4280 QualType destPointee
4281 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4282 QualType destType = Context.getPointerType(destPointee);
4283 // Add qualifiers if necessary.
4284 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4285 // Promote to void*.
4286 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4287 return destType;
4288 }
4289 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4290 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4291 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4292 QualType destPointee
4293 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4294 QualType destType = Context.getPointerType(destPointee);
4295 // Add qualifiers if necessary.
4296 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4297 // Promote to void*.
4298 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4299 return destType;
4300 }
4301 return QualType();
4302}
4303
Steve Naroff83895f72007-09-16 03:34:24 +00004304/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004305/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004306Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4307 SourceLocation ColonLoc,
4308 ExprArg Cond, ExprArg LHS,
4309 ExprArg RHS) {
4310 Expr *CondExpr = (Expr *) Cond.get();
4311 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004312
4313 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4314 // was the condition.
4315 bool isLHSNull = LHSExpr == 0;
4316 if (isLHSNull)
4317 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004318
4319 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004320 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004321 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004322 return ExprError();
4323
4324 Cond.release();
4325 LHS.release();
4326 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004327 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004328 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004329 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004330}
4331
Steve Naroff3f597292007-05-11 22:18:03 +00004332// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004333// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004334// routine is it effectively iqnores the qualifiers on the top level pointee.
4335// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4336// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004337Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004338Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004339 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004340
David Chisnall9f57c292009-08-17 16:35:33 +00004341 if ((lhsType->isObjCClassType() &&
4342 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4343 (rhsType->isObjCClassType() &&
4344 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4345 return Compatible;
4346 }
4347
Steve Naroff1f4d7272007-05-11 04:00:31 +00004348 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004349 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4350 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004351
Steve Naroff1f4d7272007-05-11 04:00:31 +00004352 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004353 lhptee = Context.getCanonicalType(lhptee);
4354 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004355
Chris Lattner9bad62c2008-01-04 18:04:52 +00004356 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004357
4358 // C99 6.5.16.1p1: This following citation is common to constraints
4359 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4360 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004361 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004362 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004363 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004364
Mike Stump4e1f26a2009-02-19 03:04:26 +00004365 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4366 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004367 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004368 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004369 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004370 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004371
Chris Lattner0a788432008-01-03 22:56:36 +00004372 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004373 assert(rhptee->isFunctionType());
4374 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004375 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004376
Chris Lattner0a788432008-01-03 22:56:36 +00004377 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004378 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004379 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004380
4381 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004382 assert(lhptee->isFunctionType());
4383 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004384 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004385 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004386 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004387 lhptee = lhptee.getUnqualifiedType();
4388 rhptee = rhptee.getUnqualifiedType();
4389 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4390 // Check if the pointee types are compatible ignoring the sign.
4391 // We explicitly check for char so that we catch "char" vs
4392 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004393 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004394 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004395 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004396 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004397
4398 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004399 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004400 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004401 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004402
Eli Friedman80160bd2009-03-22 23:59:44 +00004403 if (lhptee == rhptee) {
4404 // Types are compatible ignoring the sign. Qualifier incompatibility
4405 // takes priority over sign incompatibility because the sign
4406 // warning can be disabled.
4407 if (ConvTy != Compatible)
4408 return ConvTy;
4409 return IncompatiblePointerSign;
4410 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004411
4412 // If we are a multi-level pointer, it's possible that our issue is simply
4413 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4414 // the eventual target type is the same and the pointers have the same
4415 // level of indirection, this must be the issue.
4416 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4417 do {
4418 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4419 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4420
4421 lhptee = Context.getCanonicalType(lhptee);
4422 rhptee = Context.getCanonicalType(rhptee);
4423 } while (lhptee->isPointerType() && rhptee->isPointerType());
4424
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004425 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004426 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004427 }
4428
Eli Friedman80160bd2009-03-22 23:59:44 +00004429 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004430 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004431 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004432 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004433}
4434
Steve Naroff081c7422008-09-04 15:10:53 +00004435/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4436/// block pointer types are compatible or whether a block and normal pointer
4437/// are compatible. It is more restrict than comparing two function pointer
4438// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004439Sema::AssignConvertType
4440Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004441 QualType rhsType) {
4442 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004443
Steve Naroff081c7422008-09-04 15:10:53 +00004444 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004445 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4446 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004447
Steve Naroff081c7422008-09-04 15:10:53 +00004448 // make sure we operate on the canonical type
4449 lhptee = Context.getCanonicalType(lhptee);
4450 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004451
Steve Naroff081c7422008-09-04 15:10:53 +00004452 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004453
Steve Naroff081c7422008-09-04 15:10:53 +00004454 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004455 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004456 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004457
Eli Friedmana6638ca2009-06-08 05:08:54 +00004458 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004459 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004460 return ConvTy;
4461}
4462
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004463/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4464/// for assignment compatibility.
4465Sema::AssignConvertType
4466Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4467 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4468 return Compatible;
4469 QualType lhptee =
4470 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4471 QualType rhptee =
4472 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4473 // make sure we operate on the canonical type
4474 lhptee = Context.getCanonicalType(lhptee);
4475 rhptee = Context.getCanonicalType(rhptee);
4476 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4477 return CompatiblePointerDiscardsQualifiers;
4478
4479 if (Context.typesAreCompatible(lhsType, rhsType))
4480 return Compatible;
4481 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4482 return IncompatibleObjCQualifiedId;
4483 return IncompatiblePointer;
4484}
4485
Mike Stump4e1f26a2009-02-19 03:04:26 +00004486/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4487/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004488/// pointers. Here are some objectionable examples that GCC considers warnings:
4489///
4490/// int a, *pint;
4491/// short *pshort;
4492/// struct foo *pfoo;
4493///
4494/// pint = pshort; // warning: assignment from incompatible pointer type
4495/// a = pint; // warning: assignment makes integer from pointer without a cast
4496/// pint = a; // warning: assignment makes pointer from integer without a cast
4497/// pint = pfoo; // warning: assignment from incompatible pointer type
4498///
4499/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004500/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004501///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004502Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004503Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004504 // Get canonical types. We're not formatting these types, just comparing
4505 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004506 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4507 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004508
4509 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004510 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004511
David Chisnall9f57c292009-08-17 16:35:33 +00004512 if ((lhsType->isObjCClassType() &&
4513 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4514 (rhsType->isObjCClassType() &&
4515 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4516 return Compatible;
4517 }
4518
Douglas Gregor6b754842008-10-28 00:22:11 +00004519 // If the left-hand side is a reference type, then we are in a
4520 // (rare!) case where we've allowed the use of references in C,
4521 // e.g., as a parameter type in a built-in function. In this case,
4522 // just make sure that the type referenced is compatible with the
4523 // right-hand side type. The caller is responsible for adjusting
4524 // lhsType so that the resulting expression does not have reference
4525 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004526 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004527 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004528 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004529 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004530 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004531 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4532 // to the same ExtVector type.
4533 if (lhsType->isExtVectorType()) {
4534 if (rhsType->isExtVectorType())
4535 return lhsType == rhsType ? Compatible : Incompatible;
4536 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4537 return Compatible;
4538 }
Mike Stump11289f42009-09-09 15:08:12 +00004539
Nate Begeman191a6b12008-07-14 18:02:46 +00004540 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004541 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004542 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004543 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004544 if (getLangOptions().LaxVectorConversions &&
4545 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004546 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004547 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004548 }
4549 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004550 }
Eli Friedman3360d892008-05-30 18:07:22 +00004551
Chris Lattner881a2122008-01-04 23:32:24 +00004552 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004553 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004554
Chris Lattnerec646832008-04-07 06:49:41 +00004555 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004556 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004557 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004558
Chris Lattnerec646832008-04-07 06:49:41 +00004559 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004560 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004561
Steve Naroffaccc4882009-07-20 17:56:53 +00004562 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004563 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004564 if (lhsType->isVoidPointerType()) // an exception to the rule.
4565 return Compatible;
4566 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004567 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004568 if (rhsType->getAs<BlockPointerType>()) {
4569 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004570 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004571
4572 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004573 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004574 return Compatible;
4575 }
Steve Naroff081c7422008-09-04 15:10:53 +00004576 return Incompatible;
4577 }
4578
4579 if (isa<BlockPointerType>(lhsType)) {
4580 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004581 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004582
Steve Naroff32d072c2008-09-29 18:10:17 +00004583 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004584 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004585 return Compatible;
4586
Steve Naroff081c7422008-09-04 15:10:53 +00004587 if (rhsType->isBlockPointerType())
4588 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004589
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004590 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004591 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004592 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004593 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004594 return Incompatible;
4595 }
4596
Steve Naroff7cae42b2009-07-10 23:34:53 +00004597 if (isa<ObjCObjectPointerType>(lhsType)) {
4598 if (rhsType->isIntegerType())
4599 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004600
Steve Naroffaccc4882009-07-20 17:56:53 +00004601 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004602 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004603 if (rhsType->isVoidPointerType()) // an exception to the rule.
4604 return Compatible;
4605 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004606 }
4607 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004608 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004609 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004610 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004611 if (RHSPT->getPointeeType()->isVoidType())
4612 return Compatible;
4613 }
4614 // Treat block pointers as objects.
4615 if (rhsType->isBlockPointerType())
4616 return Compatible;
4617 return Incompatible;
4618 }
Chris Lattnerec646832008-04-07 06:49:41 +00004619 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004620 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004621 if (lhsType == Context.BoolTy)
4622 return Compatible;
4623
4624 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004625 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004626
Mike Stump4e1f26a2009-02-19 03:04:26 +00004627 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004628 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004629
4630 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004631 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004632 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004633 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004634 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004635 if (isa<ObjCObjectPointerType>(rhsType)) {
4636 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4637 if (lhsType == Context.BoolTy)
4638 return Compatible;
4639
4640 if (lhsType->isIntegerType())
4641 return PointerToInt;
4642
Steve Naroffaccc4882009-07-20 17:56:53 +00004643 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004644 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004645 if (lhsType->isVoidPointerType()) // an exception to the rule.
4646 return Compatible;
4647 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004648 }
4649 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004650 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004651 return Compatible;
4652 return Incompatible;
4653 }
Eli Friedman3360d892008-05-30 18:07:22 +00004654
Chris Lattnera52c2f22008-01-04 23:18:45 +00004655 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004656 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004657 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004658 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004659 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004660}
4661
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004662/// \brief Constructs a transparent union from an expression that is
4663/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004664static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004665 QualType UnionType, FieldDecl *Field) {
4666 // Build an initializer list that designates the appropriate member
4667 // of the transparent union.
4668 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4669 &E, 1,
4670 SourceLocation());
4671 Initializer->setType(UnionType);
4672 Initializer->setInitializedFieldInUnion(Field);
4673
4674 // Build a compound literal constructing a value of the transparent
4675 // union type from this initializer list.
4676 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4677 false);
4678}
4679
4680Sema::AssignConvertType
4681Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4682 QualType FromType = rExpr->getType();
4683
Mike Stump11289f42009-09-09 15:08:12 +00004684 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004685 // transparent_union GCC extension.
4686 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004687 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004688 return Incompatible;
4689
4690 // The field to initialize within the transparent union.
4691 RecordDecl *UD = UT->getDecl();
4692 FieldDecl *InitField = 0;
4693 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004694 for (RecordDecl::field_iterator it = UD->field_begin(),
4695 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004696 it != itend; ++it) {
4697 if (it->getType()->isPointerType()) {
4698 // If the transparent union contains a pointer type, we allow:
4699 // 1) void pointer
4700 // 2) null pointer constant
4701 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004702 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004703 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004704 InitField = *it;
4705 break;
4706 }
Mike Stump11289f42009-09-09 15:08:12 +00004707
Douglas Gregor56751b52009-09-25 04:25:58 +00004708 if (rExpr->isNullPointerConstant(Context,
4709 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004710 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004711 InitField = *it;
4712 break;
4713 }
4714 }
4715
4716 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4717 == Compatible) {
4718 InitField = *it;
4719 break;
4720 }
4721 }
4722
4723 if (!InitField)
4724 return Incompatible;
4725
4726 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4727 return Compatible;
4728}
4729
Chris Lattner9bad62c2008-01-04 18:04:52 +00004730Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004731Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004732 if (getLangOptions().CPlusPlus) {
4733 if (!lhsType->isRecordType()) {
4734 // C++ 5.17p3: If the left operand is not of class type, the
4735 // expression is implicitly converted (C++ 4) to the
4736 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004737 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004738 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004739 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004740 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004741 }
4742
4743 // FIXME: Currently, we fall through and treat C++ classes like C
4744 // structures.
4745 }
4746
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004747 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4748 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004749 if ((lhsType->isPointerType() ||
4750 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004751 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004752 && rExpr->isNullPointerConstant(Context,
4753 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004754 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004755 return Compatible;
4756 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004757
Chris Lattnere6dcd502007-10-16 02:55:40 +00004758 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004759 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004760 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004761 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004762 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004763 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004764 if (!lhsType->isReferenceType())
4765 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004766
Chris Lattner9bad62c2008-01-04 18:04:52 +00004767 Sema::AssignConvertType result =
4768 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004769
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004770 // C99 6.5.16.1p2: The value of the right operand is converted to the
4771 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004772 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4773 // so that we can use references in built-in functions even in C.
4774 // The getNonReferenceType() call makes sure that the resulting expression
4775 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004776 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004777 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4778 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004779 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004780}
4781
Chris Lattner326f7572008-11-18 01:30:42 +00004782QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004783 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004784 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004785 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004786 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004787}
4788
Mike Stump4e1f26a2009-02-19 03:04:26 +00004789inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004790 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004791 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004792 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004793 QualType lhsType =
4794 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4795 QualType rhsType =
4796 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004797
Nate Begeman191a6b12008-07-14 18:02:46 +00004798 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004799 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004800 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004801
Nate Begeman191a6b12008-07-14 18:02:46 +00004802 // Handle the case of a vector & extvector type of the same size and element
4803 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004804 if (getLangOptions().LaxVectorConversions) {
4805 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004806 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4807 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004808 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004809 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004810 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004811 }
4812 }
4813 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004814
Nate Begemanbd956c42009-06-28 02:36:38 +00004815 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4816 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4817 bool swapped = false;
4818 if (rhsType->isExtVectorType()) {
4819 swapped = true;
4820 std::swap(rex, lex);
4821 std::swap(rhsType, lhsType);
4822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823
Nate Begeman886448d2009-06-28 19:12:57 +00004824 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004825 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004826 QualType EltTy = LV->getElementType();
4827 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4828 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004829 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004830 if (swapped) std::swap(rex, lex);
4831 return lhsType;
4832 }
4833 }
4834 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4835 rhsType->isRealFloatingType()) {
4836 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004837 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004838 if (swapped) std::swap(rex, lex);
4839 return lhsType;
4840 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004841 }
4842 }
Mike Stump11289f42009-09-09 15:08:12 +00004843
Nate Begeman886448d2009-06-28 19:12:57 +00004844 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004845 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004846 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004847 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004848 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004849}
4850
Steve Naroff218bc2b2007-05-04 21:54:46 +00004851inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004852 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004853 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004854 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004855
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004856 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004857
Steve Naroffdbd9e892007-07-17 00:58:39 +00004858 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004859 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004860 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004861}
4862
Steve Naroff218bc2b2007-05-04 21:54:46 +00004863inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004864 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004865 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4866 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4867 return CheckVectorOperands(Loc, lex, rex);
4868 return InvalidOperands(Loc, lex, rex);
4869 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004870
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004871 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004872
Steve Naroffdbd9e892007-07-17 00:58:39 +00004873 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004874 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004875 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004876}
4877
4878inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004879 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004880 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4881 QualType compType = CheckVectorOperands(Loc, lex, rex);
4882 if (CompLHSTy) *CompLHSTy = compType;
4883 return compType;
4884 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004885
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004886 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004887
Steve Naroffe4718892007-04-27 18:30:00 +00004888 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004889 if (lex->getType()->isArithmeticType() &&
4890 rex->getType()->isArithmeticType()) {
4891 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004892 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004893 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004894
Eli Friedman8e122982008-05-18 18:08:51 +00004895 // Put any potential pointer into PExp
4896 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004897 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004898 std::swap(PExp, IExp);
4899
Steve Naroff6b712a72009-07-14 18:25:06 +00004900 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004901
Eli Friedman8e122982008-05-18 18:08:51 +00004902 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004903 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004904
Chris Lattner12bdebb2009-04-24 23:50:08 +00004905 // Check for arithmetic on pointers to incomplete types.
4906 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004907 if (getLangOptions().CPlusPlus) {
4908 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004909 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004910 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004911 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004912
4913 // GNU extension: arithmetic on pointer to void
4914 Diag(Loc, diag::ext_gnu_void_ptr)
4915 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004916 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004917 if (getLangOptions().CPlusPlus) {
4918 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4919 << lex->getType() << lex->getSourceRange();
4920 return QualType();
4921 }
4922
4923 // GNU extension: arithmetic on pointer to function
4924 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4925 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004926 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004927 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004928 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004929 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004930 PExp->getType()->isObjCObjectPointerType()) &&
4931 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004932 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4933 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004934 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004935 return QualType();
4936 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004937 // Diagnose bad cases where we step over interface counts.
4938 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4939 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4940 << PointeeTy << PExp->getSourceRange();
4941 return QualType();
4942 }
Mike Stump11289f42009-09-09 15:08:12 +00004943
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004944 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004945 QualType LHSTy = Context.isPromotableBitField(lex);
4946 if (LHSTy.isNull()) {
4947 LHSTy = lex->getType();
4948 if (LHSTy->isPromotableIntegerType())
4949 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004950 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004951 *CompLHSTy = LHSTy;
4952 }
Eli Friedman8e122982008-05-18 18:08:51 +00004953 return PExp->getType();
4954 }
4955 }
4956
Chris Lattner326f7572008-11-18 01:30:42 +00004957 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004958}
4959
Chris Lattner2a3569b2008-04-07 05:30:13 +00004960// C99 6.5.6
4961QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004962 SourceLocation Loc, QualType* CompLHSTy) {
4963 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4964 QualType compType = CheckVectorOperands(Loc, lex, rex);
4965 if (CompLHSTy) *CompLHSTy = compType;
4966 return compType;
4967 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004968
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004969 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004970
Chris Lattner4d62f422007-12-09 21:53:25 +00004971 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004972
Chris Lattner4d62f422007-12-09 21:53:25 +00004973 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004974 if (lex->getType()->isArithmeticType()
4975 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004976 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004977 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004978 }
Mike Stump11289f42009-09-09 15:08:12 +00004979
Chris Lattner4d62f422007-12-09 21:53:25 +00004980 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004981 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004982 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004983
Douglas Gregorac1fb652009-03-24 19:52:54 +00004984 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004985
Douglas Gregorac1fb652009-03-24 19:52:54 +00004986 bool ComplainAboutVoid = false;
4987 Expr *ComplainAboutFunc = 0;
4988 if (lpointee->isVoidType()) {
4989 if (getLangOptions().CPlusPlus) {
4990 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4991 << lex->getSourceRange() << rex->getSourceRange();
4992 return QualType();
4993 }
4994
4995 // GNU C extension: arithmetic on pointer to void
4996 ComplainAboutVoid = true;
4997 } else if (lpointee->isFunctionType()) {
4998 if (getLangOptions().CPlusPlus) {
4999 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005000 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005001 return QualType();
5002 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005003
5004 // GNU C extension: arithmetic on pointer to function
5005 ComplainAboutFunc = lex;
5006 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005007 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005008 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005009 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005010 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005011 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005012
Chris Lattner12bdebb2009-04-24 23:50:08 +00005013 // Diagnose bad cases where we step over interface counts.
5014 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5015 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5016 << lpointee << lex->getSourceRange();
5017 return QualType();
5018 }
Mike Stump11289f42009-09-09 15:08:12 +00005019
Chris Lattner4d62f422007-12-09 21:53:25 +00005020 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005021 if (rex->getType()->isIntegerType()) {
5022 if (ComplainAboutVoid)
5023 Diag(Loc, diag::ext_gnu_void_ptr)
5024 << lex->getSourceRange() << rex->getSourceRange();
5025 if (ComplainAboutFunc)
5026 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005027 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005028 << ComplainAboutFunc->getSourceRange();
5029
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005030 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005031 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005032 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005033
Chris Lattner4d62f422007-12-09 21:53:25 +00005034 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005035 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005036 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005037
Douglas Gregorac1fb652009-03-24 19:52:54 +00005038 // RHS must be a completely-type object type.
5039 // Handle the GNU void* extension.
5040 if (rpointee->isVoidType()) {
5041 if (getLangOptions().CPlusPlus) {
5042 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5043 << lex->getSourceRange() << rex->getSourceRange();
5044 return QualType();
5045 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005046
Douglas Gregorac1fb652009-03-24 19:52:54 +00005047 ComplainAboutVoid = true;
5048 } else if (rpointee->isFunctionType()) {
5049 if (getLangOptions().CPlusPlus) {
5050 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005051 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005052 return QualType();
5053 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005054
5055 // GNU extension: arithmetic on pointer to function
5056 if (!ComplainAboutFunc)
5057 ComplainAboutFunc = rex;
5058 } else if (!rpointee->isDependentType() &&
5059 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005060 PDiag(diag::err_typecheck_sub_ptr_object)
5061 << rex->getSourceRange()
5062 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005063 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005064
Eli Friedman168fe152009-05-16 13:54:38 +00005065 if (getLangOptions().CPlusPlus) {
5066 // Pointee types must be the same: C++ [expr.add]
5067 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5068 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5069 << lex->getType() << rex->getType()
5070 << lex->getSourceRange() << rex->getSourceRange();
5071 return QualType();
5072 }
5073 } else {
5074 // Pointee types must be compatible C99 6.5.6p3
5075 if (!Context.typesAreCompatible(
5076 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5077 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5078 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5079 << lex->getType() << rex->getType()
5080 << lex->getSourceRange() << rex->getSourceRange();
5081 return QualType();
5082 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005083 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005084
Douglas Gregorac1fb652009-03-24 19:52:54 +00005085 if (ComplainAboutVoid)
5086 Diag(Loc, diag::ext_gnu_void_ptr)
5087 << lex->getSourceRange() << rex->getSourceRange();
5088 if (ComplainAboutFunc)
5089 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005090 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005091 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005092
5093 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005094 return Context.getPointerDiffType();
5095 }
5096 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005097
Chris Lattner326f7572008-11-18 01:30:42 +00005098 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005099}
5100
Chris Lattner2a3569b2008-04-07 05:30:13 +00005101// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005102QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005103 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005104 // C99 6.5.7p2: Each of the operands shall have integer type.
5105 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005106 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005107
Nate Begemane46ee9a2009-10-25 02:26:48 +00005108 // Vector shifts promote their scalar inputs to vector type.
5109 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5110 return CheckVectorOperands(Loc, lex, rex);
5111
Chris Lattner5c11c412007-12-12 05:47:28 +00005112 // Shifts don't perform usual arithmetic conversions, they just do integer
5113 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005114 QualType LHSTy = Context.isPromotableBitField(lex);
5115 if (LHSTy.isNull()) {
5116 LHSTy = lex->getType();
5117 if (LHSTy->isPromotableIntegerType())
5118 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005119 }
Chris Lattner3c133402007-12-13 07:28:16 +00005120 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005121 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005122
Chris Lattner5c11c412007-12-12 05:47:28 +00005123 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005124
Ryan Flynnf53fab82009-08-07 16:20:20 +00005125 // Sanity-check shift operands
5126 llvm::APSInt Right;
5127 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005128 if (!rex->isValueDependent() &&
5129 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005130 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005131 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5132 else {
5133 llvm::APInt LeftBits(Right.getBitWidth(),
5134 Context.getTypeSize(lex->getType()));
5135 if (Right.uge(LeftBits))
5136 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5137 }
5138 }
5139
Chris Lattner5c11c412007-12-12 05:47:28 +00005140 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005141 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005142}
5143
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005144// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005145QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005146 unsigned OpaqueOpc, bool isRelational) {
5147 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5148
Chris Lattner9a152e22009-12-05 05:40:13 +00005149 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005150 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005151 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
John McCall99ce6bf2009-11-06 08:49:08 +00005153 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5154 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005155
Chris Lattnerb620c342007-08-26 01:18:55 +00005156 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005157 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5158 UsualArithmeticConversions(lex, rex);
5159 else {
5160 UsualUnaryConversions(lex);
5161 UsualUnaryConversions(rex);
5162 }
Steve Naroff31090012007-07-16 21:54:35 +00005163 QualType lType = lex->getType();
5164 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005165
Mike Stumpf70bcf72009-05-07 18:43:07 +00005166 if (!lType->isFloatingType()
5167 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005168 // For non-floating point types, check for self-comparisons of the form
5169 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5170 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005171 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005172 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005173 Expr *LHSStripped = lex->IgnoreParens();
5174 Expr *RHSStripped = rex->IgnoreParens();
5175 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5176 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005177 if (DRL->getDecl() == DRR->getDecl() &&
5178 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005179 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005180
Chris Lattner222b8bd2009-03-08 19:39:53 +00005181 if (isa<CastExpr>(LHSStripped))
5182 LHSStripped = LHSStripped->IgnoreParenCasts();
5183 if (isa<CastExpr>(RHSStripped))
5184 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005185
Chris Lattner222b8bd2009-03-08 19:39:53 +00005186 // Warn about comparisons against a string constant (unless the other
5187 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005188 Expr *literalString = 0;
5189 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005190 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005191 !RHSStripped->isNullPointerConstant(Context,
5192 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005193 literalString = lex;
5194 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005195 } else if ((isa<StringLiteral>(RHSStripped) ||
5196 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005197 !LHSStripped->isNullPointerConstant(Context,
5198 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005199 literalString = rex;
5200 literalStringStripped = RHSStripped;
5201 }
5202
5203 if (literalString) {
5204 std::string resultComparison;
5205 switch (Opc) {
5206 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5207 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5208 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5209 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5210 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5211 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5212 default: assert(false && "Invalid comparison operator");
5213 }
5214 Diag(Loc, diag::warn_stringcompare)
5215 << isa<ObjCEncodeExpr>(literalStringStripped)
5216 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005217 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5218 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5219 "strcmp(")
5220 << CodeModificationHint::CreateInsertion(
5221 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005222 resultComparison);
5223 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005224 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005225
Douglas Gregorca63811b2008-11-19 03:25:36 +00005226 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005227 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005228
Chris Lattnerb620c342007-08-26 01:18:55 +00005229 if (isRelational) {
5230 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005231 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005232 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005233 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005234 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005235 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005236
Chris Lattnerb620c342007-08-26 01:18:55 +00005237 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005238 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005239 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005240
Douglas Gregor56751b52009-09-25 04:25:58 +00005241 bool LHSIsNull = lex->isNullPointerConstant(Context,
5242 Expr::NPC_ValueDependentIsNull);
5243 bool RHSIsNull = rex->isNullPointerConstant(Context,
5244 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005245
Chris Lattnerb620c342007-08-26 01:18:55 +00005246 // All of the following pointer related warnings are GCC extensions, except
5247 // when handling null pointer constants. One day, we can consider making them
5248 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005249 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005250 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005251 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005252 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005253 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005254
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005255 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005256 if (LCanPointeeTy == RCanPointeeTy)
5257 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005258 if (!isRelational &&
5259 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5260 // Valid unless comparison between non-null pointer and function pointer
5261 // This is a gcc extension compatibility comparison.
5262 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5263 && !LHSIsNull && !RHSIsNull) {
5264 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5265 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5266 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5267 return ResultTy;
5268 }
5269 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005270 // C++ [expr.rel]p2:
5271 // [...] Pointer conversions (4.10) and qualification
5272 // conversions (4.4) are performed on pointer operands (or on
5273 // a pointer operand and a null pointer constant) to bring
5274 // them to their composite pointer type. [...]
5275 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005276 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005277 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005278 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005279 if (T.isNull()) {
5280 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5281 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5282 return QualType();
5283 }
5284
Eli Friedman06ed2a52009-10-20 08:27:19 +00005285 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5286 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005287 return ResultTy;
5288 }
Eli Friedman16c209612009-08-23 00:27:47 +00005289 // C99 6.5.9p2 and C99 6.5.8p2
5290 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5291 RCanPointeeTy.getUnqualifiedType())) {
5292 // Valid unless a relational comparison of function pointers
5293 if (isRelational && LCanPointeeTy->isFunctionType()) {
5294 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5295 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5296 }
5297 } else if (!isRelational &&
5298 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5299 // Valid unless comparison between non-null pointer and function pointer
5300 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5301 && !LHSIsNull && !RHSIsNull) {
5302 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5303 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5304 }
5305 } else {
5306 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005307 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005308 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005309 }
Eli Friedman16c209612009-08-23 00:27:47 +00005310 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005311 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005312 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005313 }
Mike Stump11289f42009-09-09 15:08:12 +00005314
Sebastian Redl576fd422009-05-10 18:38:11 +00005315 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005316 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005317 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005318 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005319 (lType->isPointerType() ||
5320 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005321 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005322 return ResultTy;
5323 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005324 if (LHSIsNull &&
5325 (rType->isPointerType() ||
5326 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005327 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005328 return ResultTy;
5329 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005330
5331 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005332 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005333 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5334 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005335 // In addition, pointers to members can be compared, or a pointer to
5336 // member and a null pointer constant. Pointer to member conversions
5337 // (4.11) and qualification conversions (4.4) are performed to bring
5338 // them to a common type. If one operand is a null pointer constant,
5339 // the common type is the type of the other operand. Otherwise, the
5340 // common type is a pointer to member type similar (4.4) to the type
5341 // of one of the operands, with a cv-qualification signature (4.4)
5342 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005343 // types.
5344 QualType T = FindCompositePointerType(lex, rex);
5345 if (T.isNull()) {
5346 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5347 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5348 return QualType();
5349 }
Mike Stump11289f42009-09-09 15:08:12 +00005350
Eli Friedman06ed2a52009-10-20 08:27:19 +00005351 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5352 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005353 return ResultTy;
5354 }
Mike Stump11289f42009-09-09 15:08:12 +00005355
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005356 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005357 if (lType->isNullPtrType() && rType->isNullPtrType())
5358 return ResultTy;
5359 }
Mike Stump11289f42009-09-09 15:08:12 +00005360
Steve Naroff081c7422008-09-04 15:10:53 +00005361 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005362 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005363 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5364 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005365
Steve Naroff081c7422008-09-04 15:10:53 +00005366 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005367 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005368 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005369 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005370 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005371 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005372 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005373 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005374 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005375 if (!isRelational
5376 && ((lType->isBlockPointerType() && rType->isPointerType())
5377 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005378 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005379 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005380 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005381 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005382 ->getPointeeType()->isVoidType())))
5383 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5384 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005385 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005386 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005387 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005388 }
Steve Naroff081c7422008-09-04 15:10:53 +00005389
Steve Naroff7cae42b2009-07-10 23:34:53 +00005390 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005391 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005392 const PointerType *LPT = lType->getAs<PointerType>();
5393 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005394 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005395 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005396 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005397 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005398
Steve Naroff753567f2008-11-17 19:49:16 +00005399 if (!LPtrToVoid && !RPtrToVoid &&
5400 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005401 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005402 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005403 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005404 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005405 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005406 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005407 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005408 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005409 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5410 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005411 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005412 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005413 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005414 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005415 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005416 unsigned DiagID = 0;
5417 if (RHSIsNull) {
5418 if (isRelational)
5419 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5420 } else if (isRelational)
5421 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5422 else
5423 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005424
Chris Lattnerd99bd522009-08-23 00:03:44 +00005425 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005426 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005427 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005428 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005429 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005430 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005431 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005432 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005433 unsigned DiagID = 0;
5434 if (LHSIsNull) {
5435 if (isRelational)
5436 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5437 } else if (isRelational)
5438 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5439 else
5440 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005441
Chris Lattnerd99bd522009-08-23 00:03:44 +00005442 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005443 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005444 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005445 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005446 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005447 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005448 }
Steve Naroff4b191572008-09-04 16:56:14 +00005449 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005450 if (!isRelational && RHSIsNull
5451 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005452 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005453 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005454 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005455 if (!isRelational && LHSIsNull
5456 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005457 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005458 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005459 }
Chris Lattner326f7572008-11-18 01:30:42 +00005460 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005461}
5462
Nate Begeman191a6b12008-07-14 18:02:46 +00005463/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005464/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005465/// like a scalar comparison, a vector comparison produces a vector of integer
5466/// types.
5467QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005468 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005469 bool isRelational) {
5470 // Check to make sure we're operating on vectors of the same type and width,
5471 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005472 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005473 if (vType.isNull())
5474 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005475
Nate Begeman191a6b12008-07-14 18:02:46 +00005476 QualType lType = lex->getType();
5477 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478
Nate Begeman191a6b12008-07-14 18:02:46 +00005479 // For non-floating point types, check for self-comparisons of the form
5480 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5481 // often indicate logic errors in the program.
5482 if (!lType->isFloatingType()) {
5483 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5484 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5485 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005486 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005487 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005488
Nate Begeman191a6b12008-07-14 18:02:46 +00005489 // Check for comparisons of floating point operands using != and ==.
5490 if (!isRelational && lType->isFloatingType()) {
5491 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005492 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005493 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005494
Nate Begeman191a6b12008-07-14 18:02:46 +00005495 // Return the type for the comparison, which is the same as vector type for
5496 // integer vectors, or an integer type of identical size and number of
5497 // elements for floating point vectors.
5498 if (lType->isIntegerType())
5499 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005500
John McCall9dd450b2009-09-21 23:43:11 +00005501 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005502 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005503 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005504 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005505 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005506 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5507
Mike Stump4e1f26a2009-02-19 03:04:26 +00005508 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005509 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005510 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5511}
5512
Steve Naroff218bc2b2007-05-04 21:54:46 +00005513inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005514 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005515 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005516 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005517
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005518 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005519
Steve Naroffdbd9e892007-07-17 00:58:39 +00005520 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005521 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005522 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005523}
5524
Steve Naroff218bc2b2007-05-04 21:54:46 +00005525inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005526 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005527 if (!Context.getLangOptions().CPlusPlus) {
5528 UsualUnaryConversions(lex);
5529 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005530
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005531 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5532 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005533
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005534 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005535 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005536
5537 // C++ [expr.log.and]p1
5538 // C++ [expr.log.or]p1
5539 // The operands are both implicitly converted to type bool (clause 4).
5540 StandardConversionSequence LHS;
5541 if (!IsStandardConversion(lex, Context.BoolTy,
5542 /*InOverloadResolution=*/false, LHS))
5543 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005544
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005545 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005546 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005547 return InvalidOperands(Loc, lex, rex);
5548
5549 StandardConversionSequence RHS;
5550 if (!IsStandardConversion(rex, Context.BoolTy,
5551 /*InOverloadResolution=*/false, RHS))
5552 return InvalidOperands(Loc, lex, rex);
5553
5554 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005555 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005556 return InvalidOperands(Loc, lex, rex);
5557
5558 // C++ [expr.log.and]p2
5559 // C++ [expr.log.or]p2
5560 // The result is a bool.
5561 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005562}
5563
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005564/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5565/// is a read-only property; return true if so. A readonly property expression
5566/// depends on various declarations and thus must be treated specially.
5567///
Mike Stump11289f42009-09-09 15:08:12 +00005568static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005569 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5570 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5571 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5572 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005573 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005574 BaseType->getAsObjCInterfacePointerType())
5575 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5576 if (S.isPropertyReadonly(PDecl, IFace))
5577 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005578 }
5579 }
5580 return false;
5581}
5582
Chris Lattner30bd3272008-11-18 01:22:49 +00005583/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5584/// emit an error and return true. If so, return false.
5585static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005586 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005587 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005588 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005589 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5590 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005591 if (IsLV == Expr::MLV_Valid)
5592 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005593
Chris Lattner30bd3272008-11-18 01:22:49 +00005594 unsigned Diag = 0;
5595 bool NeedType = false;
5596 switch (IsLV) { // C99 6.5.16p2
5597 default: assert(0 && "Unknown result from isModifiableLvalue!");
5598 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005599 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005600 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5601 NeedType = true;
5602 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005603 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005604 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5605 NeedType = true;
5606 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005607 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005608 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5609 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005610 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005611 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5612 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005613 case Expr::MLV_IncompleteType:
5614 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005615 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005616 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5617 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005618 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005619 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5620 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005621 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005622 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5623 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005624 case Expr::MLV_ReadonlyProperty:
5625 Diag = diag::error_readonly_property_assignment;
5626 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005627 case Expr::MLV_NoSetterProperty:
5628 Diag = diag::error_nosetter_property_assignment;
5629 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005630 case Expr::MLV_SubObjCPropertySetting:
5631 Diag = diag::error_no_subobject_property_setting;
5632 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005633 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005634
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005635 SourceRange Assign;
5636 if (Loc != OrigLoc)
5637 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005638 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005639 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005640 else
Mike Stump11289f42009-09-09 15:08:12 +00005641 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005642 return true;
5643}
5644
5645
5646
5647// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005648QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5649 SourceLocation Loc,
5650 QualType CompoundType) {
5651 // Verify that LHS is a modifiable lvalue, and emit error if not.
5652 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005653 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005654
5655 QualType LHSType = LHS->getType();
5656 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005657
Chris Lattner9bad62c2008-01-04 18:04:52 +00005658 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005659 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005660 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005661 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005662 // Special case of NSObject attributes on c-style pointer types.
5663 if (ConvTy == IncompatiblePointer &&
5664 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005665 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005666 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005667 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005668 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005669
Chris Lattnerea714382008-08-21 18:04:13 +00005670 // If the RHS is a unary plus or minus, check to see if they = and + are
5671 // right next to each other. If so, the user may have typo'd "x =+ 4"
5672 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005673 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5675 RHSCheck = ICE->getSubExpr();
5676 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5677 if ((UO->getOpcode() == UnaryOperator::Plus ||
5678 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005679 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005680 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005681 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5682 // And there is a space or other character before the subexpr of the
5683 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005684 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5685 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005686 Diag(Loc, diag::warn_not_compound_assign)
5687 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5688 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005689 }
Chris Lattnerea714382008-08-21 18:04:13 +00005690 }
5691 } else {
5692 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005693 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005694 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005695
Chris Lattner326f7572008-11-18 01:30:42 +00005696 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005697 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005698 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005699
Steve Naroff98cf3e92007-06-06 18:38:38 +00005700 // C99 6.5.16p3: The type of an assignment expression is the type of the
5701 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005702 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005703 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5704 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005705 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005706 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005707 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005708}
5709
Chris Lattner326f7572008-11-18 01:30:42 +00005710// C99 6.5.17
5711QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005712 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005713 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005714
5715 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5716 // incomplete in C++).
5717
Chris Lattner326f7572008-11-18 01:30:42 +00005718 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005719}
5720
Steve Naroff7a5af782007-07-13 16:58:59 +00005721/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5722/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005723QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5724 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005725 if (Op->isTypeDependent())
5726 return Context.DependentTy;
5727
Chris Lattner6b0cf142008-11-21 07:05:48 +00005728 QualType ResType = Op->getType();
5729 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005730
Sebastian Redle10c2c32008-12-20 09:35:34 +00005731 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5732 // Decrement of bool is not allowed.
5733 if (!isInc) {
5734 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5735 return QualType();
5736 }
5737 // Increment of bool sets it to true, but is deprecated.
5738 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5739 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005740 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005741 } else if (ResType->isAnyPointerType()) {
5742 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005743
Chris Lattner6b0cf142008-11-21 07:05:48 +00005744 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005745 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005746 if (getLangOptions().CPlusPlus) {
5747 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5748 << Op->getSourceRange();
5749 return QualType();
5750 }
5751
5752 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005753 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005754 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005755 if (getLangOptions().CPlusPlus) {
5756 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5757 << Op->getType() << Op->getSourceRange();
5758 return QualType();
5759 }
5760
5761 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005762 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005763 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005764 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005765 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005766 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005767 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005768 // Diagnose bad cases where we step over interface counts.
5769 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5770 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5771 << PointeeTy << Op->getSourceRange();
5772 return QualType();
5773 }
Eli Friedman090addd2010-01-03 00:20:48 +00005774 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005775 // C99 does not support ++/-- on complex types, we allow as an extension.
5776 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005777 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005778 } else {
5779 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005780 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005781 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005782 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005783 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005784 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005785 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005786 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005787 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005788}
5789
Anders Carlsson806700f2008-02-01 07:15:58 +00005790/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005791/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005792/// where the declaration is needed for type checking. We only need to
5793/// handle cases when the expression references a function designator
5794/// or is an lvalue. Here are some examples:
5795/// - &(x) => x
5796/// - &*****f => f for f a function designator.
5797/// - &s.xx => s
5798/// - &s.zz[1].yy -> s, if zz is an array
5799/// - *(x + 1) -> x, if x is an array
5800/// - &"123"[2] -> 0
5801/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005802static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005803 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005804 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005805 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005806 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005807 // If this is an arrow operator, the address is an offset from
5808 // the base's value, so the object the base refers to is
5809 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005810 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005811 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005812 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005813 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005814 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005815 // FIXME: This code shouldn't be necessary! We should catch the implicit
5816 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005817 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5818 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5819 if (ICE->getSubExpr()->getType()->isArrayType())
5820 return getPrimaryDecl(ICE->getSubExpr());
5821 }
5822 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005823 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005824 case Stmt::UnaryOperatorClass: {
5825 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005826
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005827 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005828 case UnaryOperator::Real:
5829 case UnaryOperator::Imag:
5830 case UnaryOperator::Extension:
5831 return getPrimaryDecl(UO->getSubExpr());
5832 default:
5833 return 0;
5834 }
5835 }
Steve Naroff47500512007-04-19 23:00:49 +00005836 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005837 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005838 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005839 // If the result of an implicit cast is an l-value, we care about
5840 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005841 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005842 default:
5843 return 0;
5844 }
5845}
5846
5847/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005848/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005849/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005850/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005851/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005852/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005853/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005854QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005855 // Make sure to ignore parentheses in subsequent checks
5856 op = op->IgnoreParens();
5857
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005858 if (op->isTypeDependent())
5859 return Context.DependentTy;
5860
Steve Naroff826e91a2008-01-13 17:10:08 +00005861 if (getLangOptions().C99) {
5862 // Implement C99-only parts of addressof rules.
5863 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5864 if (uOp->getOpcode() == UnaryOperator::Deref)
5865 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5866 // (assuming the deref expression is valid).
5867 return uOp->getSubExpr()->getType();
5868 }
5869 // Technically, there should be a check for array subscript
5870 // expressions here, but the result of one is always an lvalue anyway.
5871 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005872 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005873 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005874
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005875 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5876 if (lval == Expr::LV_MemberFunction && ME &&
5877 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5878 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5879 // &f where f is a member of the current object, or &o.f, or &p->f
5880 // All these are not allowed, and we need to catch them before the dcl
5881 // branch of the if, below.
5882 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5883 << dcl;
5884 // FIXME: Improve this diagnostic and provide a fixit.
5885
5886 // Now recover by acting as if the function had been accessed qualified.
5887 return Context.getMemberPointerType(op->getType(),
5888 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5889 .getTypePtr());
5890 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00005891 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005892 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005893 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005894 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005895 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5896 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005897 return QualType();
5898 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005899 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005900 // The operand cannot be a bit-field
5901 Diag(OpLoc, diag::err_typecheck_address_of)
5902 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005903 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005904 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5905 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005906 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005907 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005908 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005909 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005910 } else if (isa<ObjCPropertyRefExpr>(op)) {
5911 // cannot take address of a property expression.
5912 Diag(OpLoc, diag::err_typecheck_address_of)
5913 << "property expression" << op->getSourceRange();
5914 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005915 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5916 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005917 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5918 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005919 } else if (isa<UnresolvedLookupExpr>(op)) {
5920 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005921 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005922 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005923 // with the register storage-class specifier.
5924 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005925 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005926 Diag(OpLoc, diag::err_typecheck_address_of)
5927 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005928 return QualType();
5929 }
John McCalld14a8642009-11-21 08:51:07 +00005930 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005931 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005932 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005933 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005934 // Could be a pointer to member, though, if there is an explicit
5935 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005936 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005937 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005938 if (Ctx && Ctx->isRecord()) {
5939 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005940 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005941 diag::err_cannot_form_pointer_to_member_of_reference_type)
5942 << FD->getDeclName() << FD->getType();
5943 return QualType();
5944 }
Mike Stump11289f42009-09-09 15:08:12 +00005945
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005946 return Context.getMemberPointerType(op->getType(),
5947 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005948 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005949 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005950 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005951 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005952 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005953 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5954 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005955 return Context.getMemberPointerType(op->getType(),
5956 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5957 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005958 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005959 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005960
Eli Friedmance7f9002009-05-16 23:27:50 +00005961 if (lval == Expr::LV_IncompleteVoidType) {
5962 // Taking the address of a void variable is technically illegal, but we
5963 // allow it in cases which are otherwise valid.
5964 // Example: "extern void x; void* y = &x;".
5965 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5966 }
5967
Steve Naroff47500512007-04-19 23:00:49 +00005968 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005969 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005970}
5971
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005972QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005973 if (Op->isTypeDependent())
5974 return Context.DependentTy;
5975
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005976 UsualUnaryConversions(Op);
5977 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005978
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005979 // Note that per both C89 and C99, this is always legal, even if ptype is an
5980 // incomplete type or void. It would be possible to warn about dereferencing
5981 // a void pointer, but it's completely well-defined, and such a warning is
5982 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005983 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005984 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005985
John McCall9dd450b2009-09-21 23:43:11 +00005986 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005987 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005988
Chris Lattner29e812b2008-11-20 06:06:08 +00005989 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005990 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005991 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005992}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005993
5994static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5995 tok::TokenKind Kind) {
5996 BinaryOperator::Opcode Opc;
5997 switch (Kind) {
5998 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005999 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6000 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006001 case tok::star: Opc = BinaryOperator::Mul; break;
6002 case tok::slash: Opc = BinaryOperator::Div; break;
6003 case tok::percent: Opc = BinaryOperator::Rem; break;
6004 case tok::plus: Opc = BinaryOperator::Add; break;
6005 case tok::minus: Opc = BinaryOperator::Sub; break;
6006 case tok::lessless: Opc = BinaryOperator::Shl; break;
6007 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6008 case tok::lessequal: Opc = BinaryOperator::LE; break;
6009 case tok::less: Opc = BinaryOperator::LT; break;
6010 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6011 case tok::greater: Opc = BinaryOperator::GT; break;
6012 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6013 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6014 case tok::amp: Opc = BinaryOperator::And; break;
6015 case tok::caret: Opc = BinaryOperator::Xor; break;
6016 case tok::pipe: Opc = BinaryOperator::Or; break;
6017 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6018 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6019 case tok::equal: Opc = BinaryOperator::Assign; break;
6020 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6021 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6022 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6023 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6024 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6025 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6026 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6027 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6028 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6029 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6030 case tok::comma: Opc = BinaryOperator::Comma; break;
6031 }
6032 return Opc;
6033}
6034
Steve Naroff35d85152007-05-07 00:24:15 +00006035static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6036 tok::TokenKind Kind) {
6037 UnaryOperator::Opcode Opc;
6038 switch (Kind) {
6039 default: assert(0 && "Unknown unary op!");
6040 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6041 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6042 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6043 case tok::star: Opc = UnaryOperator::Deref; break;
6044 case tok::plus: Opc = UnaryOperator::Plus; break;
6045 case tok::minus: Opc = UnaryOperator::Minus; break;
6046 case tok::tilde: Opc = UnaryOperator::Not; break;
6047 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006048 case tok::kw___real: Opc = UnaryOperator::Real; break;
6049 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006050 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006051 }
6052 return Opc;
6053}
6054
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006055/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6056/// operator @p Opc at location @c TokLoc. This routine only supports
6057/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006058Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6059 unsigned Op,
6060 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006061 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006062 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006063 // The following two variables are used for compound assignment operators
6064 QualType CompLHSTy; // Type of LHS after promotions for computation
6065 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006066
6067 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006068 case BinaryOperator::Assign:
6069 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6070 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006071 case BinaryOperator::PtrMemD:
6072 case BinaryOperator::PtrMemI:
6073 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6074 Opc == BinaryOperator::PtrMemI);
6075 break;
6076 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006077 case BinaryOperator::Div:
6078 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6079 break;
6080 case BinaryOperator::Rem:
6081 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6082 break;
6083 case BinaryOperator::Add:
6084 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6085 break;
6086 case BinaryOperator::Sub:
6087 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6088 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006089 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006090 case BinaryOperator::Shr:
6091 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6092 break;
6093 case BinaryOperator::LE:
6094 case BinaryOperator::LT:
6095 case BinaryOperator::GE:
6096 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006097 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006098 break;
6099 case BinaryOperator::EQ:
6100 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006101 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006102 break;
6103 case BinaryOperator::And:
6104 case BinaryOperator::Xor:
6105 case BinaryOperator::Or:
6106 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6107 break;
6108 case BinaryOperator::LAnd:
6109 case BinaryOperator::LOr:
6110 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6111 break;
6112 case BinaryOperator::MulAssign:
6113 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006114 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6115 CompLHSTy = CompResultTy;
6116 if (!CompResultTy.isNull())
6117 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006118 break;
6119 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006120 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6121 CompLHSTy = CompResultTy;
6122 if (!CompResultTy.isNull())
6123 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006124 break;
6125 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006126 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6127 if (!CompResultTy.isNull())
6128 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006129 break;
6130 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006131 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6132 if (!CompResultTy.isNull())
6133 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006134 break;
6135 case BinaryOperator::ShlAssign:
6136 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006137 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6138 CompLHSTy = CompResultTy;
6139 if (!CompResultTy.isNull())
6140 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006141 break;
6142 case BinaryOperator::AndAssign:
6143 case BinaryOperator::XorAssign:
6144 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006145 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6146 CompLHSTy = CompResultTy;
6147 if (!CompResultTy.isNull())
6148 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006149 break;
6150 case BinaryOperator::Comma:
6151 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6152 break;
6153 }
6154 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006155 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006156 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006157 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6158 else
6159 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006160 CompLHSTy, CompResultTy,
6161 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006162}
6163
Sebastian Redl44615072009-10-27 12:10:02 +00006164/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6165/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006166static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6167 const PartialDiagnostic &PD,
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006168 SourceRange ParenRange,
6169 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6170 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006171 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6172 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6173 // We can't display the parentheses, so just dig the
6174 // warning/error and return.
6175 Self.Diag(Loc, PD);
6176 return;
6177 }
6178
6179 Self.Diag(Loc, PD)
6180 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6181 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006182
6183 if (!SecondPD.getDiagID())
6184 return;
6185
6186 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6187 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6188 // We can't display the parentheses, so just dig the
6189 // warning/error and return.
6190 Self.Diag(Loc, SecondPD);
6191 return;
6192 }
6193
6194 Self.Diag(Loc, SecondPD)
6195 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6196 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006197}
6198
Sebastian Redl44615072009-10-27 12:10:02 +00006199/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6200/// operators are mixed in a way that suggests that the programmer forgot that
6201/// comparison operators have higher precedence. The most typical example of
6202/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006203static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6204 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006205 typedef BinaryOperator BinOp;
6206 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6207 rhsopc = static_cast<BinOp::Opcode>(-1);
6208 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006209 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006210 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006211 rhsopc = BO->getOpcode();
6212
6213 // Subs are not binary operators.
6214 if (lhsopc == -1 && rhsopc == -1)
6215 return;
6216
6217 // Bitwise operations are sometimes used as eager logical ops.
6218 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006219 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6220 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006221 return;
6222
Sebastian Redl44615072009-10-27 12:10:02 +00006223 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006224 SuggestParentheses(Self, OpLoc,
6225 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006226 << SourceRange(lhs->getLocStart(), OpLoc)
6227 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006228 lhs->getSourceRange(),
6229 PDiag(diag::note_precedence_bitwise_first)
6230 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006231 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6232 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006233 SuggestParentheses(Self, OpLoc,
6234 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006235 << SourceRange(OpLoc, rhs->getLocEnd())
6236 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006237 rhs->getSourceRange(),
6238 PDiag(diag::note_precedence_bitwise_first)
6239 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006240 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006241}
6242
6243/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6244/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6245/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6246static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6247 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006248 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006249 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6250}
6251
Steve Naroff218bc2b2007-05-04 21:54:46 +00006252// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006253Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6254 tok::TokenKind Kind,
6255 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006256 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006257 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006258
Steve Naroff83895f72007-09-16 03:34:24 +00006259 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6260 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006261
Sebastian Redl43028242009-10-26 15:24:15 +00006262 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6263 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6264
Douglas Gregor5287f092009-11-05 00:51:44 +00006265 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6266}
6267
6268Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6269 BinaryOperator::Opcode Opc,
6270 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006271 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006272 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006273 rhs->getType()->isOverloadableType())) {
6274 // Find all of the overloaded operators visible from this
6275 // point. We perform both an operator-name lookup from the local
6276 // scope and an argument-dependent lookup based on the types of
6277 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006278 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006279 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6280 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006281 if (S)
6282 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6283 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006284 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006285 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006286 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006287 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006288 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006289
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006290 // Build the (potentially-overloaded, potentially-dependent)
6291 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006292 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006293 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006294
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006295 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006296 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006297}
6298
Douglas Gregor084d8552009-03-13 23:49:33 +00006299Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006300 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006301 ExprArg InputArg) {
6302 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006303
Mike Stump87c57ac2009-05-16 07:39:55 +00006304 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006305 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006306 QualType resultType;
6307 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006308 case UnaryOperator::OffsetOf:
6309 assert(false && "Invalid unary operator");
6310 break;
6311
Steve Naroff35d85152007-05-07 00:24:15 +00006312 case UnaryOperator::PreInc:
6313 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006314 case UnaryOperator::PostInc:
6315 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006316 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006317 Opc == UnaryOperator::PreInc ||
6318 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006319 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006320 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006321 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006322 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006323 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006324 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006325 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006326 break;
6327 case UnaryOperator::Plus:
6328 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006329 UsualUnaryConversions(Input);
6330 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006331 if (resultType->isDependentType())
6332 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006333 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6334 break;
6335 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6336 resultType->isEnumeralType())
6337 break;
6338 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6339 Opc == UnaryOperator::Plus &&
6340 resultType->isPointerType())
6341 break;
6342
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006343 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6344 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006345 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006346 UsualUnaryConversions(Input);
6347 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006348 if (resultType->isDependentType())
6349 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006350 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6351 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6352 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006353 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006354 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006355 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006356 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6357 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006358 break;
6359 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006360 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006361 DefaultFunctionArrayConversion(Input);
6362 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006363 if (resultType->isDependentType())
6364 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006365 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006366 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6367 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006368 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006369 // In C++, it's bool. C++ 5.3.1p8
6370 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006371 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006372 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006373 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006374 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006375 break;
Chris Lattner86554282007-06-08 22:32:33 +00006376 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006377 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006378 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006379 }
6380 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006381 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006382
6383 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006384 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006385}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006386
Douglas Gregor5287f092009-11-05 00:51:44 +00006387Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6388 UnaryOperator::Opcode Opc,
6389 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006390 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006391 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6392 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006393 // Find all of the overloaded operators visible from this
6394 // point. We perform both an operator-name lookup from the local
6395 // scope and an argument-dependent lookup based on the types of
6396 // the arguments.
6397 FunctionSet Functions;
6398 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6399 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006400 if (S)
6401 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6402 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006403 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006404 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006405 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006406 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006407
Douglas Gregor084d8552009-03-13 23:49:33 +00006408 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6409 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006410
Douglas Gregor084d8552009-03-13 23:49:33 +00006411 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6412}
6413
Douglas Gregor5287f092009-11-05 00:51:44 +00006414// Unary Operators. 'Tok' is the token for the operator.
6415Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6416 tok::TokenKind Op, ExprArg input) {
6417 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6418}
6419
Steve Naroff66356bd2007-09-16 14:56:35 +00006420/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006421Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6422 SourceLocation LabLoc,
6423 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006424 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006425 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006426
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006427 // If we haven't seen this label yet, create a forward reference. It
6428 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006429 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006430 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006431
Chris Lattnereefa10e2007-05-28 06:56:27 +00006432 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006433 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6434 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006435}
6436
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006437Sema::OwningExprResult
6438Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6439 SourceLocation RPLoc) { // "({..})"
6440 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006441 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6442 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6443
Eli Friedman52cc0162009-01-24 23:09:00 +00006444 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006445 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006446 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006447
Chris Lattner366727f2007-07-24 16:58:17 +00006448 // FIXME: there are a variety of strange constraints to enforce here, for
6449 // example, it is not possible to goto into a stmt expression apparently.
6450 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006451
Chris Lattner366727f2007-07-24 16:58:17 +00006452 // If there are sub stmts in the compound stmt, take the type of the last one
6453 // as the type of the stmtexpr.
6454 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006455
Chris Lattner944d3062008-07-26 19:51:01 +00006456 if (!Compound->body_empty()) {
6457 Stmt *LastStmt = Compound->body_back();
6458 // If LastStmt is a label, skip down through into the body.
6459 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6460 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006461
Chris Lattner944d3062008-07-26 19:51:01 +00006462 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006463 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006464 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006465
Eli Friedmanba961a92009-03-23 00:24:07 +00006466 // FIXME: Check that expression type is complete/non-abstract; statement
6467 // expressions are not lvalues.
6468
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006469 substmt.release();
6470 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006471}
Steve Naroff78864672007-08-01 22:05:33 +00006472
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006473Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6474 SourceLocation BuiltinLoc,
6475 SourceLocation TypeLoc,
6476 TypeTy *argty,
6477 OffsetOfComponent *CompPtr,
6478 unsigned NumComponents,
6479 SourceLocation RPLoc) {
6480 // FIXME: This function leaks all expressions in the offset components on
6481 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006482 // FIXME: Preserve type source info.
6483 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006484 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006485
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006486 bool Dependent = ArgTy->isDependentType();
6487
Chris Lattnerf17bd422007-08-30 17:45:32 +00006488 // We must have at least one component that refers to the type, and the first
6489 // one is known to be a field designator. Verify that the ArgTy represents
6490 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006491 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006492 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006493
Eli Friedmanba961a92009-03-23 00:24:07 +00006494 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6495 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006496
Eli Friedman988a16b2009-02-27 06:44:11 +00006497 // Otherwise, create a null pointer as the base, and iteratively process
6498 // the offsetof designators.
6499 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6500 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006501 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006502 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006503
Chris Lattner78502cf2007-08-31 21:49:13 +00006504 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6505 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006506 // FIXME: This diagnostic isn't actually visible because the location is in
6507 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006508 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006509 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6510 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006511
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006512 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006513 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006514
John McCall9eff4e62009-11-04 03:03:43 +00006515 if (RequireCompleteType(TypeLoc, Res->getType(),
6516 diag::err_offsetof_incomplete_type))
6517 return ExprError();
6518
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006519 // FIXME: Dependent case loses a lot of information here. And probably
6520 // leaks like a sieve.
6521 for (unsigned i = 0; i != NumComponents; ++i) {
6522 const OffsetOfComponent &OC = CompPtr[i];
6523 if (OC.isBrackets) {
6524 // Offset of an array sub-field. TODO: Should we allow vector elements?
6525 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6526 if (!AT) {
6527 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006528 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6529 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006530 }
6531
6532 // FIXME: C++: Verify that operator[] isn't overloaded.
6533
Eli Friedman988a16b2009-02-27 06:44:11 +00006534 // Promote the array so it looks more like a normal array subscript
6535 // expression.
6536 DefaultFunctionArrayConversion(Res);
6537
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006538 // C99 6.5.2.1p1
6539 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006540 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006541 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006542 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006543 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006544 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006545
6546 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6547 OC.LocEnd);
6548 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006549 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006550
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006551 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006552 if (!RC) {
6553 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006554 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6555 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006556 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006557
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006558 // Get the decl corresponding to this.
6559 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006560 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006561 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6562 DiagRuntimeBehavior(BuiltinLoc,
6563 PDiag(diag::warn_offsetof_non_pod_type)
6564 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6565 << Res->getType()))
6566 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006567 }
Mike Stump11289f42009-09-09 15:08:12 +00006568
John McCall27b18f82009-11-17 02:14:36 +00006569 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6570 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006571
John McCall67c00872009-12-02 08:25:40 +00006572 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006573 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006574 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006575 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6576 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006577
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006578 // FIXME: C++: Verify that MemberDecl isn't a static field.
6579 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006580 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006581 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006582 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006583 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006584 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006585 // MemberDecl->getType() doesn't get the right qualifiers, but it
6586 // doesn't matter here.
6587 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6588 MemberDecl->getType().getNonReferenceType());
6589 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006590 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006591 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006592
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006593 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6594 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006595}
6596
6597
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006598Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6599 TypeTy *arg1,TypeTy *arg2,
6600 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006601 // FIXME: Preserve type source info.
6602 QualType argT1 = GetTypeFromParser(arg1);
6603 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006604
Steve Naroff78864672007-08-01 22:05:33 +00006605 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006606
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006607 if (getLangOptions().CPlusPlus) {
6608 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6609 << SourceRange(BuiltinLoc, RPLoc);
6610 return ExprError();
6611 }
6612
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006613 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6614 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006615}
6616
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006617Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6618 ExprArg cond,
6619 ExprArg expr1, ExprArg expr2,
6620 SourceLocation RPLoc) {
6621 Expr *CondExpr = static_cast<Expr*>(cond.get());
6622 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6623 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006624
Steve Naroff9efdabc2007-08-03 21:21:27 +00006625 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6626
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006627 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006628 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006629 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006630 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006631 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006632 } else {
6633 // The conditional expression is required to be a constant expression.
6634 llvm::APSInt condEval(32);
6635 SourceLocation ExpLoc;
6636 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006637 return ExprError(Diag(ExpLoc,
6638 diag::err_typecheck_choose_expr_requires_constant)
6639 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006640
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006641 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6642 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006643 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6644 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006645 }
6646
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006647 cond.release(); expr1.release(); expr2.release();
6648 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006649 resType, RPLoc,
6650 resType->isDependentType(),
6651 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006652}
6653
Steve Naroffc540d662008-09-03 18:15:37 +00006654//===----------------------------------------------------------------------===//
6655// Clang Extensions.
6656//===----------------------------------------------------------------------===//
6657
6658/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006659void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006660 // Analyze block parameters.
6661 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006662
Steve Naroffc540d662008-09-03 18:15:37 +00006663 // Add BSI to CurBlock.
6664 BSI->PrevBlockInfo = CurBlock;
6665 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006666
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006667 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006668 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006669 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006670 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006671 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6672 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006673
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006674 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006675 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006676 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006677}
6678
Mike Stump82f071f2009-02-04 22:31:32 +00006679void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006680 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006681
6682 if (ParamInfo.getNumTypeObjects() == 0
6683 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006684 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006685 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6686
Mike Stumpd456c482009-04-28 01:10:27 +00006687 if (T->isArrayType()) {
6688 Diag(ParamInfo.getSourceRange().getBegin(),
6689 diag::err_block_returns_array);
6690 return;
6691 }
6692
Mike Stump82f071f2009-02-04 22:31:32 +00006693 // The parameter list is optional, if there was none, assume ().
6694 if (!T->isFunctionType())
6695 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6696
6697 CurBlock->hasPrototype = true;
6698 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006699 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006700 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006701 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006702 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006703 // FIXME: remove the attribute.
6704 }
John McCall9dd450b2009-09-21 23:43:11 +00006705 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006706
Chris Lattner6de05082009-04-11 19:27:54 +00006707 // Do not allow returning a objc interface by-value.
6708 if (RetTy->isObjCInterfaceType()) {
6709 Diag(ParamInfo.getSourceRange().getBegin(),
6710 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6711 return;
6712 }
Mike Stump82f071f2009-02-04 22:31:32 +00006713 return;
6714 }
6715
Steve Naroffc540d662008-09-03 18:15:37 +00006716 // Analyze arguments to block.
6717 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6718 "Not a function declarator!");
6719 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006720
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006721 CurBlock->hasPrototype = FTI.hasPrototype;
6722 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006723
Steve Naroffc540d662008-09-03 18:15:37 +00006724 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6725 // no arguments, not a function that takes a single void argument.
6726 if (FTI.hasPrototype &&
6727 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006728 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6729 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006730 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006731 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006732 } else if (FTI.hasPrototype) {
6733 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006734 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006735 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006736 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006737 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006738 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006739 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006740 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006741 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6742 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6743 // If this has an identifier, add it to the scope stack.
6744 if ((*AI)->getIdentifier())
6745 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006746
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006747 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006748 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006749 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006750 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006751 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006752 // FIXME: remove the attribute.
6753 }
Mike Stump11289f42009-09-09 15:08:12 +00006754
Chris Lattner6de05082009-04-11 19:27:54 +00006755 // Analyze the return type.
6756 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006757 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006758
Chris Lattner6de05082009-04-11 19:27:54 +00006759 // Do not allow returning a objc interface by-value.
6760 if (RetTy->isObjCInterfaceType()) {
6761 Diag(ParamInfo.getSourceRange().getBegin(),
6762 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6763 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006764 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006765}
6766
6767/// ActOnBlockError - If there is an error parsing a block, this callback
6768/// is invoked to pop the information about the block from the action impl.
6769void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6770 // Ensure that CurBlock is deleted.
6771 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006772
Chris Lattner45542ea2009-04-19 05:28:12 +00006773 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6774
Steve Naroffc540d662008-09-03 18:15:37 +00006775 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006776 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006777 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006778 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006779}
6780
6781/// ActOnBlockStmtExpr - This is called when the body of a block statement
6782/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006783Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6784 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006785 // If blocks are disabled, emit an error.
6786 if (!LangOpts.Blocks)
6787 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006788
Steve Naroffc540d662008-09-03 18:15:37 +00006789 // Ensure that CurBlock is deleted.
6790 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006791
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006792 PopDeclContext();
6793
Steve Naroffc540d662008-09-03 18:15:37 +00006794 // Pop off CurBlock, handle nested blocks.
6795 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006796
Steve Naroffc540d662008-09-03 18:15:37 +00006797 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006798 if (!BSI->ReturnType.isNull())
6799 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006800
Steve Naroffc540d662008-09-03 18:15:37 +00006801 llvm::SmallVector<QualType, 8> ArgTypes;
6802 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6803 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006804
Mike Stump3bf1ab42009-07-28 22:04:01 +00006805 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006806 QualType BlockTy;
6807 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006808 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6809 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006810 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006811 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006812 BSI->isVariadic, 0, false, false, 0, 0,
6813 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006814
Eli Friedmanba961a92009-03-23 00:24:07 +00006815 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006816 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006817 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006818
Chris Lattner45542ea2009-04-19 05:28:12 +00006819 // If needed, diagnose invalid gotos and switches in the block.
6820 if (CurFunctionNeedsScopeChecking)
6821 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6822 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006823
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006824 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006825 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006826 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6827 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006828}
6829
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006830Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6831 ExprArg expr, TypeTy *type,
6832 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006833 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006834 Expr *E = static_cast<Expr*>(expr.get());
6835 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006836
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006837 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006838
6839 // Get the va_list type
6840 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006841 if (VaListType->isArrayType()) {
6842 // Deal with implicit array decay; for example, on x86-64,
6843 // va_list is an array, but it's supposed to decay to
6844 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006845 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006846 // Make sure the input expression also decays appropriately.
6847 UsualUnaryConversions(E);
6848 } else {
6849 // Otherwise, the va_list argument must be an l-value because
6850 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006851 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006852 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006853 return ExprError();
6854 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006855
Douglas Gregorad3150c2009-05-19 23:10:31 +00006856 if (!E->isTypeDependent() &&
6857 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006858 return ExprError(Diag(E->getLocStart(),
6859 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006860 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006861 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006862
Eli Friedmanba961a92009-03-23 00:24:07 +00006863 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006864 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006865
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006866 expr.release();
6867 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6868 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006869}
6870
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006871Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006872 // The type of __null will be int or long, depending on the size of
6873 // pointers on the target.
6874 QualType Ty;
6875 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6876 Ty = Context.IntTy;
6877 else
6878 Ty = Context.LongTy;
6879
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006880 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006881}
6882
Anders Carlssonace5d072009-11-10 04:46:30 +00006883static void
6884MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6885 QualType DstType,
6886 Expr *SrcExpr,
6887 CodeModificationHint &Hint) {
6888 if (!SemaRef.getLangOptions().ObjC1)
6889 return;
6890
6891 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6892 if (!PT)
6893 return;
6894
6895 // Check if the destination is of type 'id'.
6896 if (!PT->isObjCIdType()) {
6897 // Check if the destination is the 'NSString' interface.
6898 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6899 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6900 return;
6901 }
6902
6903 // Strip off any parens and casts.
6904 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6905 if (!SL || SL->isWide())
6906 return;
6907
6908 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6909}
6910
Chris Lattner9bad62c2008-01-04 18:04:52 +00006911bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6912 SourceLocation Loc,
6913 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006914 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00006915 // Decode the result (notice that AST's are still created for extensions).
6916 bool isInvalid = false;
6917 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006918 CodeModificationHint Hint;
6919
Chris Lattner9bad62c2008-01-04 18:04:52 +00006920 switch (ConvTy) {
6921 default: assert(0 && "Unknown conversion type");
6922 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006923 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006924 DiagKind = diag::ext_typecheck_convert_pointer_int;
6925 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006926 case IntToPointer:
6927 DiagKind = diag::ext_typecheck_convert_int_pointer;
6928 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006929 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006930 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006931 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6932 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006933 case IncompatiblePointerSign:
6934 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6935 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006936 case FunctionVoidPointer:
6937 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6938 break;
6939 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006940 // If the qualifiers lost were because we were applying the
6941 // (deprecated) C++ conversion from a string literal to a char*
6942 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6943 // Ideally, this check would be performed in
6944 // CheckPointerTypesForAssignment. However, that would require a
6945 // bit of refactoring (so that the second argument is an
6946 // expression, rather than a type), which should be done as part
6947 // of a larger effort to fix CheckPointerTypesForAssignment for
6948 // C++ semantics.
6949 if (getLangOptions().CPlusPlus &&
6950 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6951 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006952 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6953 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006954 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006955 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006956 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006957 case IntToBlockPointer:
6958 DiagKind = diag::err_int_to_block_pointer;
6959 break;
6960 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006961 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006962 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006963 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006964 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006965 // it can give a more specific diagnostic.
6966 DiagKind = diag::warn_incompatible_qualified_id;
6967 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006968 case IncompatibleVectors:
6969 DiagKind = diag::warn_incompatible_vectors;
6970 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006971 case Incompatible:
6972 DiagKind = diag::err_typecheck_convert_incompatible;
6973 isInvalid = true;
6974 break;
6975 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006976
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006977 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00006978 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006979 return isInvalid;
6980}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006981
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006982bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006983 llvm::APSInt ICEResult;
6984 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6985 if (Result)
6986 *Result = ICEResult;
6987 return false;
6988 }
6989
Anders Carlssone54e8a12008-11-30 19:50:32 +00006990 Expr::EvalResult EvalResult;
6991
Mike Stump4e1f26a2009-02-19 03:04:26 +00006992 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006993 EvalResult.HasSideEffects) {
6994 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6995
6996 if (EvalResult.Diag) {
6997 // We only show the note if it's not the usual "invalid subexpression"
6998 // or if it's actually in a subexpression.
6999 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7000 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7001 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7002 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007003
Anders Carlssone54e8a12008-11-30 19:50:32 +00007004 return true;
7005 }
7006
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007007 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7008 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007009
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007010 if (EvalResult.Diag &&
7011 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7012 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007013
Anders Carlssone54e8a12008-11-30 19:50:32 +00007014 if (Result)
7015 *Result = EvalResult.Val.getInt();
7016 return false;
7017}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007018
Douglas Gregorff790f12009-11-26 00:44:06 +00007019void
Mike Stump11289f42009-09-09 15:08:12 +00007020Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007021 ExprEvalContexts.push_back(
7022 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007023}
7024
Mike Stump11289f42009-09-09 15:08:12 +00007025void
Douglas Gregorff790f12009-11-26 00:44:06 +00007026Sema::PopExpressionEvaluationContext() {
7027 // Pop the current expression evaluation context off the stack.
7028 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7029 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007030
Douglas Gregorfab31f42009-12-12 07:57:52 +00007031 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7032 if (Rec.PotentiallyReferenced) {
7033 // Mark any remaining declarations in the current position of the stack
7034 // as "referenced". If they were not meant to be referenced, semantic
7035 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7036 for (PotentiallyReferencedDecls::iterator
7037 I = Rec.PotentiallyReferenced->begin(),
7038 IEnd = Rec.PotentiallyReferenced->end();
7039 I != IEnd; ++I)
7040 MarkDeclarationReferenced(I->first, I->second);
7041 }
7042
7043 if (Rec.PotentiallyDiagnosed) {
7044 // Emit any pending diagnostics.
7045 for (PotentiallyEmittedDiagnostics::iterator
7046 I = Rec.PotentiallyDiagnosed->begin(),
7047 IEnd = Rec.PotentiallyDiagnosed->end();
7048 I != IEnd; ++I)
7049 Diag(I->first, I->second);
7050 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007051 }
7052
7053 // When are coming out of an unevaluated context, clear out any
7054 // temporaries that we may have created as part of the evaluation of
7055 // the expression in that context: they aren't relevant because they
7056 // will never be constructed.
7057 if (Rec.Context == Unevaluated &&
7058 ExprTemporaries.size() > Rec.NumTemporaries)
7059 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7060 ExprTemporaries.end());
7061
7062 // Destroy the popped expression evaluation record.
7063 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007064}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007065
7066/// \brief Note that the given declaration was referenced in the source code.
7067///
7068/// This routine should be invoke whenever a given declaration is referenced
7069/// in the source code, and where that reference occurred. If this declaration
7070/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7071/// C99 6.9p3), then the declaration will be marked as used.
7072///
7073/// \param Loc the location where the declaration was referenced.
7074///
7075/// \param D the declaration that has been referenced by the source code.
7076void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7077 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007078
Douglas Gregor77b50e12009-06-22 23:06:13 +00007079 if (D->isUsed())
7080 return;
Mike Stump11289f42009-09-09 15:08:12 +00007081
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007082 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7083 // template or not. The reason for this is that unevaluated expressions
7084 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7085 // -Wunused-parameters)
7086 if (isa<ParmVarDecl>(D) ||
7087 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007088 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007089
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007090 // Do not mark anything as "used" within a dependent context; wait for
7091 // an instantiation.
7092 if (CurContext->isDependentContext())
7093 return;
Mike Stump11289f42009-09-09 15:08:12 +00007094
Douglas Gregorff790f12009-11-26 00:44:06 +00007095 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007096 case Unevaluated:
7097 // We are in an expression that is not potentially evaluated; do nothing.
7098 return;
Mike Stump11289f42009-09-09 15:08:12 +00007099
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007100 case PotentiallyEvaluated:
7101 // We are in a potentially-evaluated expression, so this declaration is
7102 // "used"; handle this below.
7103 break;
Mike Stump11289f42009-09-09 15:08:12 +00007104
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007105 case PotentiallyPotentiallyEvaluated:
7106 // We are in an expression that may be potentially evaluated; queue this
7107 // declaration reference until we know whether the expression is
7108 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007109 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007110 return;
7111 }
Mike Stump11289f42009-09-09 15:08:12 +00007112
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007113 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007114 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007115 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007116 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7117 if (!Constructor->isUsed())
7118 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007119 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007120 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007121 if (!Constructor->isUsed())
7122 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7123 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007124
7125 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007126 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7127 if (Destructor->isImplicit() && !Destructor->isUsed())
7128 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007129
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007130 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7131 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7132 MethodDecl->getOverloadedOperator() == OO_Equal) {
7133 if (!MethodDecl->isUsed())
7134 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7135 }
7136 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007137 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007138 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007139 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007140 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007141 bool AlreadyInstantiated = false;
7142 if (FunctionTemplateSpecializationInfo *SpecInfo
7143 = Function->getTemplateSpecializationInfo()) {
7144 if (SpecInfo->getPointOfInstantiation().isInvalid())
7145 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007146 else if (SpecInfo->getTemplateSpecializationKind()
7147 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007148 AlreadyInstantiated = true;
7149 } else if (MemberSpecializationInfo *MSInfo
7150 = Function->getMemberSpecializationInfo()) {
7151 if (MSInfo->getPointOfInstantiation().isInvalid())
7152 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007153 else if (MSInfo->getTemplateSpecializationKind()
7154 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007155 AlreadyInstantiated = true;
7156 }
7157
7158 if (!AlreadyInstantiated)
7159 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7160 }
7161
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007162 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007163 Function->setUsed(true);
7164 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007165 }
Mike Stump11289f42009-09-09 15:08:12 +00007166
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007167 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007168 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007169 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007170 Var->getInstantiatedFromStaticDataMember()) {
7171 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7172 assert(MSInfo && "Missing member specialization information?");
7173 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7174 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7175 MSInfo->setPointOfInstantiation(Loc);
7176 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7177 }
7178 }
Mike Stump11289f42009-09-09 15:08:12 +00007179
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007180 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007181
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007182 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007183 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007184 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007185}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007186
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007187/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7188/// of the program being compiled.
7189///
7190/// This routine emits the given diagnostic when the code currently being
7191/// type-checked is "potentially evaluated", meaning that there is a
7192/// possibility that the code will actually be executable. Code in sizeof()
7193/// expressions, code used only during overload resolution, etc., are not
7194/// potentially evaluated. This routine will suppress such diagnostics or,
7195/// in the absolutely nutty case of potentially potentially evaluated
7196/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7197/// later.
7198///
7199/// This routine should be used for all diagnostics that describe the run-time
7200/// behavior of a program, such as passing a non-POD value through an ellipsis.
7201/// Failure to do so will likely result in spurious diagnostics or failures
7202/// during overload resolution or within sizeof/alignof/typeof/typeid.
7203bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7204 const PartialDiagnostic &PD) {
7205 switch (ExprEvalContexts.back().Context ) {
7206 case Unevaluated:
7207 // The argument will never be evaluated, so don't complain.
7208 break;
7209
7210 case PotentiallyEvaluated:
7211 Diag(Loc, PD);
7212 return true;
7213
7214 case PotentiallyPotentiallyEvaluated:
7215 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7216 break;
7217 }
7218
7219 return false;
7220}
7221
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007222bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7223 CallExpr *CE, FunctionDecl *FD) {
7224 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7225 return false;
7226
7227 PartialDiagnostic Note =
7228 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7229 << FD->getDeclName() : PDiag();
7230 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7231
7232 if (RequireCompleteType(Loc, ReturnType,
7233 FD ?
7234 PDiag(diag::err_call_function_incomplete_return)
7235 << CE->getSourceRange() << FD->getDeclName() :
7236 PDiag(diag::err_call_incomplete_return)
7237 << CE->getSourceRange(),
7238 std::make_pair(NoteLoc, Note)))
7239 return true;
7240
7241 return false;
7242}
7243
John McCalld5707ab2009-10-12 21:59:07 +00007244// Diagnose the common s/=/==/ typo. Note that adding parentheses
7245// will prevent this condition from triggering, which is what we want.
7246void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7247 SourceLocation Loc;
7248
John McCall0506e4a2009-11-11 02:41:58 +00007249 unsigned diagnostic = diag::warn_condition_is_assignment;
7250
John McCalld5707ab2009-10-12 21:59:07 +00007251 if (isa<BinaryOperator>(E)) {
7252 BinaryOperator *Op = cast<BinaryOperator>(E);
7253 if (Op->getOpcode() != BinaryOperator::Assign)
7254 return;
7255
John McCallb0e419e2009-11-12 00:06:05 +00007256 // Greylist some idioms by putting them into a warning subcategory.
7257 if (ObjCMessageExpr *ME
7258 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7259 Selector Sel = ME->getSelector();
7260
John McCallb0e419e2009-11-12 00:06:05 +00007261 // self = [<foo> init...]
7262 if (isSelfExpr(Op->getLHS())
7263 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7264 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7265
7266 // <foo> = [<bar> nextObject]
7267 else if (Sel.isUnarySelector() &&
7268 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7269 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7270 }
John McCall0506e4a2009-11-11 02:41:58 +00007271
John McCalld5707ab2009-10-12 21:59:07 +00007272 Loc = Op->getOperatorLoc();
7273 } else if (isa<CXXOperatorCallExpr>(E)) {
7274 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7275 if (Op->getOperator() != OO_Equal)
7276 return;
7277
7278 Loc = Op->getOperatorLoc();
7279 } else {
7280 // Not an assignment.
7281 return;
7282 }
7283
John McCalld5707ab2009-10-12 21:59:07 +00007284 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007285 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007286
John McCall0506e4a2009-11-11 02:41:58 +00007287 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007288 << E->getSourceRange()
7289 << CodeModificationHint::CreateInsertion(Open, "(")
7290 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007291 Diag(Loc, diag::note_condition_assign_to_comparison)
7292 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00007293}
7294
7295bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7296 DiagnoseAssignmentAsCondition(E);
7297
7298 if (!E->isTypeDependent()) {
7299 DefaultFunctionArrayConversion(E);
7300
7301 QualType T = E->getType();
7302
7303 if (getLangOptions().CPlusPlus) {
7304 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7305 return true;
7306 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7307 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7308 << T << E->getSourceRange();
7309 return true;
7310 }
7311 }
7312
7313 return false;
7314}