blob: 26c2e176cf01de2684a4e672ab7c1de8f0eaaf8a [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:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001013 // -- an identifier that was declared with a dependent type,
1014 // (note: handled after lookup)
1015 // -- a template-id that is dependent,
1016 // (note: handled in BuildTemplateIdExpr)
1017 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001018 // -- a nested-name-specifier that contains a class-name that
1019 // names a dependent type.
1020 // Determine whether this is a member of an unknown specialization;
1021 // we need to handle these differently.
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001022 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1023 Name.getCXXNameType()->isDependentType()) ||
1024 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCalle66edc12009-11-24 19:00:30 +00001025 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001026 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001027 TemplateArgs);
1028 }
John McCalld14a8642009-11-21 08:51:07 +00001029
John McCalle66edc12009-11-24 19:00:30 +00001030 // Perform the required lookup.
1031 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1032 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001033 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001034 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001035 } else {
1036 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +00001037
John McCalle66edc12009-11-24 19:00:30 +00001038 // If this reference is in an Objective-C method, then we need to do
1039 // some special Objective-C lookup, too.
1040 if (!SS.isSet() && II && getCurMethodDecl()) {
1041 OwningExprResult E(LookupInObjCMethod(R, S, II));
1042 if (E.isInvalid())
1043 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001044
John McCalle66edc12009-11-24 19:00:30 +00001045 Expr *Ex = E.takeAs<Expr>();
1046 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001047 }
Chris Lattner59a25942008-03-31 00:36:02 +00001048 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001049
John McCalle66edc12009-11-24 19:00:30 +00001050 if (R.isAmbiguous())
1051 return ExprError();
1052
Douglas Gregor171c45a2009-02-18 21:56:37 +00001053 // Determine whether this name might be a candidate for
1054 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001055 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001056
John McCalle66edc12009-11-24 19:00:30 +00001057 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001058 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001059 // in C90, extension in C99, forbidden in C++).
1060 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1061 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1062 if (D) R.addDecl(D);
1063 }
1064
1065 // If this name wasn't predeclared and if this is not a function
1066 // call, diagnose the problem.
1067 if (R.empty()) {
Douglas Gregor598b08f2009-12-31 05:20:13 +00001068 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001069 return ExprError();
1070
1071 assert(!R.empty() &&
1072 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001073
1074 // If we found an Objective-C instance variable, let
1075 // LookupInObjCMethod build the appropriate expression to
1076 // reference the ivar.
1077 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1078 R.clear();
1079 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1080 assert(E.isInvalid() || E.get());
1081 return move(E);
1082 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001083 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCalle66edc12009-11-24 19:00:30 +00001086 // This is guaranteed from this point on.
1087 assert(!R.empty() || ADL);
1088
1089 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001090 // Warn about constructs like:
1091 // if (void *X = foo()) { ... } else { X }.
1092 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001093
Douglas Gregor3256d042009-06-30 15:47:41 +00001094 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1095 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001096 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001098 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001099 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001100 << Var->getDeclName()
1101 << (Var->getType()->isPointerType()? 2 :
1102 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001103 break;
1104 }
Mike Stump11289f42009-09-09 15:08:12 +00001105
Douglas Gregor13a2c032009-11-05 17:49:26 +00001106 // Move to the parent of this scope.
1107 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001108 }
1109 }
John McCalle66edc12009-11-24 19:00:30 +00001110 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001111 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1112 // C99 DR 316 says that, if a function type comes from a
1113 // function definition (without a prototype), that type is only
1114 // used for checking compatibility. Therefore, when referencing
1115 // the function, we pretend that we don't have the full function
1116 // type.
John McCalle66edc12009-11-24 19:00:30 +00001117 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001118 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001119
Douglas Gregor3256d042009-06-30 15:47:41 +00001120 QualType T = Func->getType();
1121 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001122 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001123 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001124 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001125 }
1126 }
Mike Stump11289f42009-09-09 15:08:12 +00001127
John McCall2d74de92009-12-01 22:10:20 +00001128 // Check whether this might be a C++ implicit instance member access.
1129 // C++ [expr.prim.general]p6:
1130 // Within the definition of a non-static member function, an
1131 // identifier that names a non-static member is transformed to a
1132 // class member access expression.
1133 // But note that &SomeClass::foo is grammatically distinct, even
1134 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001135 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001136 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001137 if (!isAbstractMemberPointer)
1138 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001139 }
1140
John McCalle66edc12009-11-24 19:00:30 +00001141 if (TemplateArgs)
1142 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001143
John McCalle66edc12009-11-24 19:00:30 +00001144 return BuildDeclarationNameExpr(SS, R, ADL);
1145}
1146
John McCall57500772009-12-16 12:17:52 +00001147/// Builds an expression which might be an implicit member expression.
1148Sema::OwningExprResult
1149Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1150 LookupResult &R,
1151 const TemplateArgumentListInfo *TemplateArgs) {
1152 switch (ClassifyImplicitMemberAccess(*this, R)) {
1153 case IMA_Instance:
1154 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1155
1156 case IMA_AnonymousMember:
1157 assert(R.isSingleResult());
1158 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1159 R.getAsSingle<FieldDecl>());
1160
1161 case IMA_Mixed:
1162 case IMA_Mixed_Unrelated:
1163 case IMA_Unresolved:
1164 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1165
1166 case IMA_Static:
1167 case IMA_Mixed_StaticContext:
1168 case IMA_Unresolved_StaticContext:
1169 if (TemplateArgs)
1170 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1171 return BuildDeclarationNameExpr(SS, R, false);
1172
1173 case IMA_Error_StaticContext:
1174 case IMA_Error_Unrelated:
1175 DiagnoseInstanceReference(*this, SS, R);
1176 return ExprError();
1177 }
1178
1179 llvm_unreachable("unexpected instance member access kind");
1180 return ExprError();
1181}
1182
John McCall10eae182009-11-30 22:42:35 +00001183/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1184/// declaration name, generally during template instantiation.
1185/// There's a large number of things which don't need to be done along
1186/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001187Sema::OwningExprResult
1188Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1189 DeclarationName Name,
1190 SourceLocation NameLoc) {
1191 DeclContext *DC;
1192 if (!(DC = computeDeclContext(SS, false)) ||
1193 DC->isDependentContext() ||
1194 RequireCompleteDeclContext(SS))
1195 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1196
1197 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1198 LookupQualifiedName(R, DC);
1199
1200 if (R.isAmbiguous())
1201 return ExprError();
1202
1203 if (R.empty()) {
1204 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1205 return ExprError();
1206 }
1207
1208 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1209}
1210
1211/// LookupInObjCMethod - The parser has read a name in, and Sema has
1212/// detected that we're currently inside an ObjC method. Perform some
1213/// additional lookup.
1214///
1215/// Ideally, most of this would be done by lookup, but there's
1216/// actually quite a lot of extra work involved.
1217///
1218/// Returns a null sentinel to indicate trivial success.
1219Sema::OwningExprResult
1220Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1221 IdentifierInfo *II) {
1222 SourceLocation Loc = Lookup.getNameLoc();
1223
1224 // There are two cases to handle here. 1) scoped lookup could have failed,
1225 // in which case we should look for an ivar. 2) scoped lookup could have
1226 // found a decl, but that decl is outside the current instance method (i.e.
1227 // a global variable). In these two cases, we do a lookup for an ivar with
1228 // this name, if the lookup sucedes, we replace it our current decl.
1229
1230 // If we're in a class method, we don't normally want to look for
1231 // ivars. But if we don't find anything else, and there's an
1232 // ivar, that's an error.
1233 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1234
1235 bool LookForIvars;
1236 if (Lookup.empty())
1237 LookForIvars = true;
1238 else if (IsClassMethod)
1239 LookForIvars = false;
1240 else
1241 LookForIvars = (Lookup.isSingleResult() &&
1242 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1243
1244 if (LookForIvars) {
1245 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1246 ObjCInterfaceDecl *ClassDeclared;
1247 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1248 // Diagnose using an ivar in a class method.
1249 if (IsClassMethod)
1250 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1251 << IV->getDeclName());
1252
1253 // If we're referencing an invalid decl, just return this as a silent
1254 // error node. The error diagnostic was already emitted on the decl.
1255 if (IV->isInvalidDecl())
1256 return ExprError();
1257
1258 // Check if referencing a field with __attribute__((deprecated)).
1259 if (DiagnoseUseOfDecl(IV, Loc))
1260 return ExprError();
1261
1262 // Diagnose the use of an ivar outside of the declaring class.
1263 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1264 ClassDeclared != IFace)
1265 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1266
1267 // FIXME: This should use a new expr for a direct reference, don't
1268 // turn this into Self->ivar, just return a BareIVarExpr or something.
1269 IdentifierInfo &II = Context.Idents.get("self");
1270 UnqualifiedId SelfName;
1271 SelfName.setIdentifier(&II, SourceLocation());
1272 CXXScopeSpec SelfScopeSpec;
1273 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1274 SelfName, false, false);
1275 MarkDeclarationReferenced(Loc, IV);
1276 return Owned(new (Context)
1277 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1278 SelfExpr.takeAs<Expr>(), true, true));
1279 }
1280 } else if (getCurMethodDecl()->isInstanceMethod()) {
1281 // We should warn if a local variable hides an ivar.
1282 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1283 ObjCInterfaceDecl *ClassDeclared;
1284 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1285 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1286 IFace == ClassDeclared)
1287 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1288 }
1289 }
1290
1291 // Needed to implement property "super.method" notation.
1292 if (Lookup.empty() && II->isStr("super")) {
1293 QualType T;
1294
1295 if (getCurMethodDecl()->isInstanceMethod())
1296 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1297 getCurMethodDecl()->getClassInterface()));
1298 else
1299 T = Context.getObjCClassType();
1300 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1301 }
1302
1303 // Sentinel value saying that we didn't do anything special.
1304 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001305}
John McCalld14a8642009-11-21 08:51:07 +00001306
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001307/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001308bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001309Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1310 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001311 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001312 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001313 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001314 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001315 if (DestType->isDependentType() || From->getType()->isDependentType())
1316 return false;
1317 QualType FromRecordType = From->getType();
1318 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001319 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001320 DestType = Context.getPointerType(DestType);
1321 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001322 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001323 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1324 CheckDerivedToBaseConversion(FromRecordType,
1325 DestRecordType,
1326 From->getSourceRange().getBegin(),
1327 From->getSourceRange()))
1328 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001329 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1330 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001331 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001332 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001333}
Douglas Gregor3256d042009-06-30 15:47:41 +00001334
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001335/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001336static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001337 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001338 SourceLocation Loc, QualType Ty,
1339 const TemplateArgumentListInfo *TemplateArgs = 0) {
1340 NestedNameSpecifier *Qualifier = 0;
1341 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001342 if (SS.isSet()) {
1343 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1344 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001345 }
Mike Stump11289f42009-09-09 15:08:12 +00001346
John McCalle66edc12009-11-24 19:00:30 +00001347 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1348 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001349}
1350
John McCall2d74de92009-12-01 22:10:20 +00001351/// Builds an implicit member access expression. The current context
1352/// is known to be an instance method, and the given unqualified lookup
1353/// set is known to contain only instance members, at least one of which
1354/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001355Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001356Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1357 LookupResult &R,
1358 const TemplateArgumentListInfo *TemplateArgs,
1359 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001360 assert(!R.empty() && !R.isAmbiguous());
1361
John McCalld14a8642009-11-21 08:51:07 +00001362 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001363
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001364 // We may have found a field within an anonymous union or struct
1365 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001366 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001367 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001368 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001369 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001370 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001371
John McCall2d74de92009-12-01 22:10:20 +00001372 // If this is known to be an instance access, go ahead and build a
1373 // 'this' expression now.
1374 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1375 Expr *This = 0; // null signifies implicit access
1376 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001377 SourceLocation Loc = R.getNameLoc();
1378 if (SS.getRange().isValid())
1379 Loc = SS.getRange().getBegin();
1380 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001381 }
1382
John McCall2d74de92009-12-01 22:10:20 +00001383 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1384 /*OpLoc*/ SourceLocation(),
1385 /*IsArrow*/ true,
1386 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001387}
1388
John McCalle66edc12009-11-24 19:00:30 +00001389bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001390 const LookupResult &R,
1391 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001392 // Only when used directly as the postfix-expression of a call.
1393 if (!HasTrailingLParen)
1394 return false;
1395
1396 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001397 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001398 return false;
1399
1400 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001401 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001402 return false;
1403
1404 // Turn off ADL when we find certain kinds of declarations during
1405 // normal lookup:
1406 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1407 NamedDecl *D = *I;
1408
1409 // C++0x [basic.lookup.argdep]p3:
1410 // -- a declaration of a class member
1411 // Since using decls preserve this property, we check this on the
1412 // original decl.
John McCall57500772009-12-16 12:17:52 +00001413 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001414 return false;
1415
1416 // C++0x [basic.lookup.argdep]p3:
1417 // -- a block-scope function declaration that is not a
1418 // using-declaration
1419 // NOTE: we also trigger this for function templates (in fact, we
1420 // don't check the decl type at all, since all other decl types
1421 // turn off ADL anyway).
1422 if (isa<UsingShadowDecl>(D))
1423 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1424 else if (D->getDeclContext()->isFunctionOrMethod())
1425 return false;
1426
1427 // C++0x [basic.lookup.argdep]p3:
1428 // -- a declaration that is neither a function or a function
1429 // template
1430 // And also for builtin functions.
1431 if (isa<FunctionDecl>(D)) {
1432 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1433
1434 // But also builtin functions.
1435 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1436 return false;
1437 } else if (!isa<FunctionTemplateDecl>(D))
1438 return false;
1439 }
1440
1441 return true;
1442}
1443
1444
John McCalld14a8642009-11-21 08:51:07 +00001445/// Diagnoses obvious problems with the use of the given declaration
1446/// as an expression. This is only actually called for lookups that
1447/// were not overloaded, and it doesn't promise that the declaration
1448/// will in fact be used.
1449static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1450 if (isa<TypedefDecl>(D)) {
1451 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1452 return true;
1453 }
1454
1455 if (isa<ObjCInterfaceDecl>(D)) {
1456 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1457 return true;
1458 }
1459
1460 if (isa<NamespaceDecl>(D)) {
1461 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1462 return true;
1463 }
1464
1465 return false;
1466}
1467
1468Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001469Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001470 LookupResult &R,
1471 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001472 // If this is a single, fully-resolved result and we don't need ADL,
1473 // just build an ordinary singleton decl ref.
1474 if (!NeedsADL && R.isSingleResult())
John McCallb53bbd42009-11-22 01:44:31 +00001475 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001476
1477 // We only need to check the declaration if there's exactly one
1478 // result, because in the overloaded case the results can only be
1479 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001480 if (R.isSingleResult() &&
1481 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001482 return ExprError();
1483
John McCalle66edc12009-11-24 19:00:30 +00001484 bool Dependent
1485 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001486 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001487 = UnresolvedLookupExpr::Create(Context, Dependent,
1488 (NestedNameSpecifier*) SS.getScopeRep(),
1489 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001490 R.getLookupName(), R.getNameLoc(),
1491 NeedsADL, R.isOverloadedResult());
1492 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1493 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001494
1495 return Owned(ULE);
1496}
1497
1498
1499/// \brief Complete semantic analysis for a reference to the given declaration.
1500Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001501Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001502 SourceLocation Loc, NamedDecl *D) {
1503 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001504 assert(!isa<FunctionTemplateDecl>(D) &&
1505 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001506
1507 if (CheckDeclInExpr(*this, Loc, D))
1508 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001509
Douglas Gregore7488b92009-12-01 16:58:18 +00001510 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1511 // Specifically diagnose references to class templates that are missing
1512 // a template argument list.
1513 Diag(Loc, diag::err_template_decl_ref)
1514 << Template << SS.getRange();
1515 Diag(Template->getLocation(), diag::note_template_decl_here);
1516 return ExprError();
1517 }
1518
1519 // Make sure that we're referring to a value.
1520 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1521 if (!VD) {
1522 Diag(Loc, diag::err_ref_non_value)
1523 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001524 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001525 return ExprError();
1526 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001527
Douglas Gregor171c45a2009-02-18 21:56:37 +00001528 // Check whether this declaration can be used. Note that we suppress
1529 // this check when we're going to perform argument-dependent lookup
1530 // on this function name, because this might not be the function
1531 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001532 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001533 return ExprError();
1534
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001535 // Only create DeclRefExpr's for valid Decl's.
1536 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001537 return ExprError();
1538
Chris Lattner2a9d9892008-10-20 05:16:36 +00001539 // If the identifier reference is inside a block, and it refers to a value
1540 // that is outside the block, create a BlockDeclRefExpr instead of a
1541 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1542 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001543 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001544 // We do not do this for things like enum constants, global variables, etc,
1545 // as they do not get snapshotted.
1546 //
1547 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001548 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1549 Diag(Loc, diag::err_ref_vm_type);
1550 Diag(D->getLocation(), diag::note_declared_at);
1551 return ExprError();
1552 }
1553
Mike Stump8971a862010-01-05 03:10:36 +00001554 if (VD->getType()->isArrayType()) {
1555 Diag(Loc, diag::err_ref_array_type);
1556 Diag(D->getLocation(), diag::note_declared_at);
1557 return ExprError();
1558 }
1559
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001560 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001561 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001562 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001563 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001564 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001565 // This is to record that a 'const' was actually synthesize and added.
1566 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001567 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001568
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001569 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001570 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001571 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001572 }
1573 // If this reference is not in a block or if the referenced variable is
1574 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001575
John McCalle66edc12009-11-24 19:00:30 +00001576 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001577}
Chris Lattnere168f762006-11-10 05:29:30 +00001578
Sebastian Redlffbcf962009-01-18 18:53:16 +00001579Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1580 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001581 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001582
Chris Lattnere168f762006-11-10 05:29:30 +00001583 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001584 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001585 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1586 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1587 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001588 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001589
Chris Lattnera81a0272008-01-12 08:14:25 +00001590 // Pre-defined identifiers are of type char[x], where x is the length of the
1591 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001592
Anders Carlsson2fb08242009-09-08 18:24:21 +00001593 Decl *currentDecl = getCurFunctionOrMethodDecl();
1594 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001595 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001596 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001597 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001598
Anders Carlsson0b209a82009-09-11 01:22:35 +00001599 QualType ResTy;
1600 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1601 ResTy = Context.DependentTy;
1602 } else {
1603 unsigned Length =
1604 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001605
Anders Carlsson0b209a82009-09-11 01:22:35 +00001606 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001607 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001608 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1609 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001610 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001611}
1612
Sebastian Redlffbcf962009-01-18 18:53:16 +00001613Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001614 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001615 CharBuffer.resize(Tok.getLength());
1616 const char *ThisTokBegin = &CharBuffer[0];
1617 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001618
Steve Naroffae4143e2007-04-26 20:39:23 +00001619 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1620 Tok.getLocation(), PP);
1621 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001622 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001623
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001624 QualType Ty;
1625 if (!getLangOptions().CPlusPlus)
1626 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1627 else if (Literal.isWide())
1628 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1629 else
1630 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001631
Sebastian Redl20614a72009-01-20 22:23:13 +00001632 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1633 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001634 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001635}
1636
Sebastian Redlffbcf962009-01-18 18:53:16 +00001637Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1638 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001639 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1640 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001641 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001642 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001643 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001644 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001645 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001646
Chris Lattner23b7eb62007-06-15 23:05:46 +00001647 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001648 // Add padding so that NumericLiteralParser can overread by one character.
1649 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001650 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001651
Chris Lattner67ca9252007-05-21 01:08:44 +00001652 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001653 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001654
Mike Stump11289f42009-09-09 15:08:12 +00001655 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001656 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001657 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001658 return ExprError();
1659
Chris Lattner1c20a172007-08-26 03:42:43 +00001660 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001661
Chris Lattner1c20a172007-08-26 03:42:43 +00001662 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001663 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001664 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001665 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001666 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001667 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001668 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001669 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001670
1671 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1672
John McCall53b93a02009-12-24 09:08:04 +00001673 using llvm::APFloat;
1674 APFloat Val(Format);
1675
1676 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001677
1678 // Overflow is always an error, but underflow is only an error if
1679 // we underflowed to zero (APFloat reports denormals as underflow).
1680 if ((result & APFloat::opOverflow) ||
1681 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001682 unsigned diagnostic;
1683 llvm::SmallVector<char, 20> buffer;
1684 if (result & APFloat::opOverflow) {
1685 diagnostic = diag::err_float_overflow;
1686 APFloat::getLargest(Format).toString(buffer);
1687 } else {
1688 diagnostic = diag::err_float_underflow;
1689 APFloat::getSmallest(Format).toString(buffer);
1690 }
1691
1692 Diag(Tok.getLocation(), diagnostic)
1693 << Ty
1694 << llvm::StringRef(buffer.data(), buffer.size());
1695 }
1696
1697 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001698 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001699
Chris Lattner1c20a172007-08-26 03:42:43 +00001700 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001701 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001702 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001703 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001704
Neil Boothac582c52007-08-29 22:00:19 +00001705 // long long is a C99 feature.
1706 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001707 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001708 Diag(Tok.getLocation(), diag::ext_longlong);
1709
Chris Lattner67ca9252007-05-21 01:08:44 +00001710 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001711 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001712
Chris Lattner67ca9252007-05-21 01:08:44 +00001713 if (Literal.GetIntegerValue(ResultVal)) {
1714 // If this value didn't fit into uintmax_t, warn and force to ull.
1715 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001716 Ty = Context.UnsignedLongLongTy;
1717 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001718 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001719 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001720 // If this value fits into a ULL, try to figure out what else it fits into
1721 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001722
Chris Lattner67ca9252007-05-21 01:08:44 +00001723 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1724 // be an unsigned int.
1725 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1726
1727 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001728 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001729 if (!Literal.isLong && !Literal.isLongLong) {
1730 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001731 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001732
Chris Lattner67ca9252007-05-21 01:08:44 +00001733 // Does it fit in a unsigned int?
1734 if (ResultVal.isIntN(IntSize)) {
1735 // Does it fit in a signed int?
1736 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001737 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001738 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001739 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001740 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001741 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001742 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001743
Chris Lattner67ca9252007-05-21 01:08:44 +00001744 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001745 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001746 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001747
Chris Lattner67ca9252007-05-21 01:08:44 +00001748 // Does it fit in a unsigned long?
1749 if (ResultVal.isIntN(LongSize)) {
1750 // Does it fit in a signed long?
1751 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001752 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001753 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001754 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001755 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001756 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001757 }
1758
Chris Lattner67ca9252007-05-21 01:08:44 +00001759 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001760 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001761 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001762
Chris Lattner67ca9252007-05-21 01:08:44 +00001763 // Does it fit in a unsigned long long?
1764 if (ResultVal.isIntN(LongLongSize)) {
1765 // Does it fit in a signed long long?
1766 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001767 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001768 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001769 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001770 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001771 }
1772 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001773
Chris Lattner67ca9252007-05-21 01:08:44 +00001774 // If we still couldn't decide a type, we probably have something that
1775 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001776 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001777 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001778 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001779 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001780 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001781
Chris Lattner55258cf2008-05-09 05:59:00 +00001782 if (ResultVal.getBitWidth() != Width)
1783 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001784 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001785 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001786 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001787
Chris Lattner1c20a172007-08-26 03:42:43 +00001788 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1789 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001790 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001791 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001792
1793 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001794}
1795
Sebastian Redlffbcf962009-01-18 18:53:16 +00001796Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1797 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001798 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001799 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001800 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001801}
1802
Steve Naroff71b59a92007-06-04 22:22:31 +00001803/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001804/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001805bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001806 SourceLocation OpLoc,
1807 const SourceRange &ExprRange,
1808 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001809 if (exprType->isDependentType())
1810 return false;
1811
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001812 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1813 // the result is the size of the referenced type."
1814 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1815 // result shall be the alignment of the referenced type."
1816 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1817 exprType = Ref->getPointeeType();
1818
Steve Naroff043d45d2007-05-15 02:32:35 +00001819 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001820 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001821 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001822 if (isSizeof)
1823 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1824 return false;
1825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Chris Lattner62975a72009-04-24 00:30:45 +00001827 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001828 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001829 Diag(OpLoc, diag::ext_sizeof_void_type)
1830 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001831 return false;
1832 }
Mike Stump11289f42009-09-09 15:08:12 +00001833
Chris Lattner62975a72009-04-24 00:30:45 +00001834 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001835 PDiag(diag::err_sizeof_alignof_incomplete_type)
1836 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001837 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001838
Chris Lattner62975a72009-04-24 00:30:45 +00001839 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001840 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001841 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001842 << exprType << isSizeof << ExprRange;
1843 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattner62975a72009-04-24 00:30:45 +00001846 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001847}
1848
Chris Lattner8dff0172009-01-24 20:17:12 +00001849bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1850 const SourceRange &ExprRange) {
1851 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001852
Mike Stump11289f42009-09-09 15:08:12 +00001853 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001854 if (isa<DeclRefExpr>(E))
1855 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001856
1857 // Cannot know anything else if the expression is dependent.
1858 if (E->isTypeDependent())
1859 return false;
1860
Douglas Gregor71235ec2009-05-02 02:18:30 +00001861 if (E->getBitField()) {
1862 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1863 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001864 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001865
1866 // Alignment of a field access is always okay, so long as it isn't a
1867 // bit-field.
1868 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001869 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001870 return false;
1871
Chris Lattner8dff0172009-01-24 20:17:12 +00001872 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1873}
1874
Douglas Gregor0950e412009-03-13 21:01:28 +00001875/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001876Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001877Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001878 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001879 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001880 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001881 return ExprError();
1882
John McCallbcd03502009-12-07 02:54:59 +00001883 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001884
Douglas Gregor0950e412009-03-13 21:01:28 +00001885 if (!T->isDependentType() &&
1886 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1887 return ExprError();
1888
1889 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001890 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001891 Context.getSizeType(), OpLoc,
1892 R.getEnd()));
1893}
1894
1895/// \brief Build a sizeof or alignof expression given an expression
1896/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001897Action::OwningExprResult
1898Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001899 bool isSizeOf, SourceRange R) {
1900 // Verify that the operand is valid.
1901 bool isInvalid = false;
1902 if (E->isTypeDependent()) {
1903 // Delay type-checking for type-dependent expressions.
1904 } else if (!isSizeOf) {
1905 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001906 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001907 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1908 isInvalid = true;
1909 } else {
1910 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1911 }
1912
1913 if (isInvalid)
1914 return ExprError();
1915
1916 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1917 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1918 Context.getSizeType(), OpLoc,
1919 R.getEnd()));
1920}
1921
Sebastian Redl6f282892008-11-11 17:56:53 +00001922/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1923/// the same for @c alignof and @c __alignof
1924/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001925Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001926Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1927 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001928 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001929 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001930
Sebastian Redl6f282892008-11-11 17:56:53 +00001931 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001932 TypeSourceInfo *TInfo;
1933 (void) GetTypeFromParser(TyOrEx, &TInfo);
1934 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001935 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001936
Douglas Gregor0950e412009-03-13 21:01:28 +00001937 Expr *ArgEx = (Expr *)TyOrEx;
1938 Action::OwningExprResult Result
1939 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1940
1941 if (Result.isInvalid())
1942 DeleteExpr(ArgEx);
1943
1944 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001945}
1946
Chris Lattner709322b2009-02-17 08:12:06 +00001947QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001948 if (V->isTypeDependent())
1949 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattnere267f5d2007-08-26 05:39:26 +00001951 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001952 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001953 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001954
Chris Lattnere267f5d2007-08-26 05:39:26 +00001955 // Otherwise they pass through real integer and floating point types here.
1956 if (V->getType()->isArithmeticType())
1957 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001958
Chris Lattnere267f5d2007-08-26 05:39:26 +00001959 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001960 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1961 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001962 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001963}
1964
1965
Chris Lattnere168f762006-11-10 05:29:30 +00001966
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001967Action::OwningExprResult
1968Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1969 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001970 UnaryOperator::Opcode Opc;
1971 switch (Kind) {
1972 default: assert(0 && "Unknown unary op!");
1973 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1974 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1975 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001976
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001977 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001978}
1979
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001980Action::OwningExprResult
1981Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1982 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001983 // Since this might be a postfix expression, get rid of ParenListExprs.
1984 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1985
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001986 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1987 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregor40412ac2008-11-19 17:17:41 +00001989 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001990 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1991 Base.release();
1992 Idx.release();
1993 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1994 Context.DependentTy, RLoc));
1995 }
1996
Mike Stump11289f42009-09-09 15:08:12 +00001997 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001998 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001999 LHSExp->getType()->isEnumeralType() ||
2000 RHSExp->getType()->isRecordType() ||
2001 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00002002 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00002003 }
2004
Sebastian Redladba46e2009-10-29 20:17:01 +00002005 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2006}
2007
2008
2009Action::OwningExprResult
2010Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2011 ExprArg Idx, SourceLocation RLoc) {
2012 Expr *LHSExp = static_cast<Expr*>(Base.get());
2013 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2014
Chris Lattner36d572b2007-07-16 00:14:47 +00002015 // Perform default conversions.
2016 DefaultFunctionArrayConversion(LHSExp);
2017 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002018
Chris Lattner36d572b2007-07-16 00:14:47 +00002019 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002020
Steve Naroffc1aadb12007-03-28 21:49:40 +00002021 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002022 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002023 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002024 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002025 Expr *BaseExpr, *IndexExpr;
2026 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002027 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2028 BaseExpr = LHSExp;
2029 IndexExpr = RHSExp;
2030 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002031 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002032 BaseExpr = LHSExp;
2033 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002034 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002035 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002036 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002037 BaseExpr = RHSExp;
2038 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002039 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002040 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002041 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002042 BaseExpr = LHSExp;
2043 IndexExpr = RHSExp;
2044 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002045 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002046 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002047 // Handle the uncommon case of "123[Ptr]".
2048 BaseExpr = RHSExp;
2049 IndexExpr = LHSExp;
2050 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002051 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002052 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002053 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002054
Chris Lattner36d572b2007-07-16 00:14:47 +00002055 // FIXME: need to deal with const...
2056 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002057 } else if (LHSTy->isArrayType()) {
2058 // If we see an array that wasn't promoted by
2059 // DefaultFunctionArrayConversion, it must be an array that
2060 // wasn't promoted because of the C90 rule that doesn't
2061 // allow promoting non-lvalue arrays. Warn, then
2062 // force the promotion here.
2063 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2064 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002065 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2066 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002067 LHSTy = LHSExp->getType();
2068
2069 BaseExpr = LHSExp;
2070 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002071 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002072 } else if (RHSTy->isArrayType()) {
2073 // Same as previous, except for 123[f().a] case
2074 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2075 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002076 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2077 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002078 RHSTy = RHSExp->getType();
2079
2080 BaseExpr = RHSExp;
2081 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002082 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002083 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002084 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2085 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002086 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002087 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002088 if (!(IndexExpr->getType()->isIntegerType() &&
2089 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002090 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2091 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002092
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002093 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002094 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2095 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002096 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2097
Douglas Gregorac1fb652009-03-24 19:52:54 +00002098 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002099 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2100 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002101 // incomplete types are not object types.
2102 if (ResultType->isFunctionType()) {
2103 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2104 << ResultType << BaseExpr->getSourceRange();
2105 return ExprError();
2106 }
Mike Stump11289f42009-09-09 15:08:12 +00002107
Douglas Gregorac1fb652009-03-24 19:52:54 +00002108 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002109 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002110 PDiag(diag::err_subscript_incomplete_type)
2111 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002112 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattner62975a72009-04-24 00:30:45 +00002114 // Diagnose bad cases where we step over interface counts.
2115 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2116 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2117 << ResultType << BaseExpr->getSourceRange();
2118 return ExprError();
2119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002121 Base.release();
2122 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002123 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002124 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002125}
2126
Steve Narofff8fd09e2007-07-27 22:15:19 +00002127QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002128CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002129 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002130 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002131 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2132 // see FIXME there.
2133 //
2134 // FIXME: This logic can be greatly simplified by splitting it along
2135 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002136 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002137
Steve Narofff8fd09e2007-07-27 22:15:19 +00002138 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002139 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002140
Mike Stump4e1f26a2009-02-19 03:04:26 +00002141 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002142 // special names that indicate a subset of exactly half the elements are
2143 // to be selected.
2144 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002145
Nate Begemanbb70bf62009-01-18 01:47:54 +00002146 // This flag determines whether or not CompName has an 's' char prefix,
2147 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002148 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002149
2150 // Check that we've found one of the special components, or that the component
2151 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002152 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002153 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2154 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002155 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002156 do
2157 compStr++;
2158 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002159 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002160 do
2161 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002162 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002163 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002164
Mike Stump4e1f26a2009-02-19 03:04:26 +00002165 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002166 // We didn't get to the end of the string. This means the component names
2167 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002168 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2169 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002170 return QualType();
2171 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002172
Nate Begemanbb70bf62009-01-18 01:47:54 +00002173 // Ensure no component accessor exceeds the width of the vector type it
2174 // operates on.
2175 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002176 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002177
2178 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002179 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002180
2181 while (*compStr) {
2182 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2183 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2184 << baseType << SourceRange(CompLoc);
2185 return QualType();
2186 }
2187 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002188 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002189
Steve Narofff8fd09e2007-07-27 22:15:19 +00002190 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002191 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002192 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002193 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002194 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002195 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002196 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002197 if (HexSwizzle)
2198 CompSize--;
2199
Steve Narofff8fd09e2007-07-27 22:15:19 +00002200 if (CompSize == 1)
2201 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002202
Nate Begemance4d7fc2008-04-18 23:10:10 +00002203 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002204 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002205 // diagostics look bad. We want extended vector types to appear built-in.
2206 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2207 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2208 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002209 }
2210 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002211}
2212
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002213static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002214 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002215 const Selector &Sel,
2216 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002217
Anders Carlssonf571c112009-08-26 18:25:21 +00002218 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002219 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002220 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002221 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002222
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002223 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2224 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002225 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002226 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002227 return D;
2228 }
2229 return 0;
2230}
2231
Steve Narofffb4330f2009-06-17 22:40:22 +00002232static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002233 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002234 const Selector &Sel,
2235 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002236 // Check protocols on qualified interfaces.
2237 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002238 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002239 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002240 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002241 GDecl = PD;
2242 break;
2243 }
2244 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002245 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002246 GDecl = OMD;
2247 break;
2248 }
2249 }
2250 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002251 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002252 E = QIdTy->qual_end(); I != E; ++I) {
2253 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002254 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002255 if (GDecl)
2256 return GDecl;
2257 }
2258 }
2259 return GDecl;
2260}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002261
John McCall10eae182009-11-30 22:42:35 +00002262Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002263Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2264 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002265 const CXXScopeSpec &SS,
2266 NamedDecl *FirstQualifierInScope,
2267 DeclarationName Name, SourceLocation NameLoc,
2268 const TemplateArgumentListInfo *TemplateArgs) {
2269 Expr *BaseExpr = Base.takeAs<Expr>();
2270
2271 // Even in dependent contexts, try to diagnose base expressions with
2272 // obviously wrong types, e.g.:
2273 //
2274 // T* t;
2275 // t.f;
2276 //
2277 // In Obj-C++, however, the above expression is valid, since it could be
2278 // accessing the 'f' property if T is an Obj-C interface. The extra check
2279 // allows this, while still reporting an error if T is a struct pointer.
2280 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002281 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002282 if (PT && (!getLangOptions().ObjC1 ||
2283 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002284 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002285 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002286 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002287 return ExprError();
2288 }
2289 }
2290
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002291 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall10eae182009-11-30 22:42:35 +00002292
2293 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2294 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002295 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002296 IsArrow, OpLoc,
2297 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2298 SS.getRange(),
2299 FirstQualifierInScope,
2300 Name, NameLoc,
2301 TemplateArgs));
2302}
2303
2304/// We know that the given qualified member reference points only to
2305/// declarations which do not belong to the static type of the base
2306/// expression. Diagnose the problem.
2307static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2308 Expr *BaseExpr,
2309 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002310 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002311 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002312 // If this is an implicit member access, use a different set of
2313 // diagnostics.
2314 if (!BaseExpr)
2315 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002316
2317 // FIXME: this is an exceedingly lame diagnostic for some of the more
2318 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002319 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002320 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002321 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002322}
2323
2324// Check whether the declarations we found through a nested-name
2325// specifier in a member expression are actually members of the base
2326// type. The restriction here is:
2327//
2328// C++ [expr.ref]p2:
2329// ... In these cases, the id-expression shall name a
2330// member of the class or of one of its base classes.
2331//
2332// So it's perfectly legitimate for the nested-name specifier to name
2333// an unrelated class, and for us to find an overload set including
2334// decls from classes which are not superclasses, as long as the decl
2335// we actually pick through overload resolution is from a superclass.
2336bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2337 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002338 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002339 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002340 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2341 if (!BaseRT) {
2342 // We can't check this yet because the base type is still
2343 // dependent.
2344 assert(BaseType->isDependentType());
2345 return false;
2346 }
2347 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002348
2349 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002350 // If this is an implicit member reference and we find a
2351 // non-instance member, it's not an error.
2352 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2353 return false;
John McCall10eae182009-11-30 22:42:35 +00002354
John McCall2d74de92009-12-01 22:10:20 +00002355 // Note that we use the DC of the decl, not the underlying decl.
2356 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2357 while (RecordD->isAnonymousStructOrUnion())
2358 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2359
2360 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2361 MemberRecord.insert(RecordD->getCanonicalDecl());
2362
2363 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2364 return false;
2365 }
2366
John McCallcd4b4772009-12-02 03:53:29 +00002367 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002368 return true;
2369}
2370
2371static bool
2372LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2373 SourceRange BaseRange, const RecordType *RTy,
2374 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2375 RecordDecl *RDecl = RTy->getDecl();
2376 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2377 PDiag(diag::err_typecheck_incomplete_tag)
2378 << BaseRange))
2379 return true;
2380
2381 DeclContext *DC = RDecl;
2382 if (SS.isSet()) {
2383 // If the member name was a qualified-id, look into the
2384 // nested-name-specifier.
2385 DC = SemaRef.computeDeclContext(SS, false);
2386
John McCallcd4b4772009-12-02 03:53:29 +00002387 if (SemaRef.RequireCompleteDeclContext(SS)) {
2388 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2389 << SS.getRange() << DC;
2390 return true;
2391 }
2392
John McCall2d74de92009-12-01 22:10:20 +00002393 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2394
2395 if (!isa<TypeDecl>(DC)) {
2396 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2397 << DC << SS.getRange();
2398 return true;
John McCall10eae182009-11-30 22:42:35 +00002399 }
2400 }
2401
John McCall2d74de92009-12-01 22:10:20 +00002402 // The record definition is complete, now look up the member.
2403 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002404
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002405 if (!R.empty())
2406 return false;
2407
2408 // We didn't find anything with the given name, so try to correct
2409 // for typos.
2410 DeclarationName Name = R.getLookupName();
2411 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2412 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2413 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2414 << Name << DC << R.getLookupName() << SS.getRange()
2415 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2416 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002417 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2418 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2419 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002420 return false;
2421 } else {
2422 R.clear();
2423 }
2424
John McCall10eae182009-11-30 22:42:35 +00002425 return false;
2426}
2427
2428Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002429Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002430 SourceLocation OpLoc, bool IsArrow,
2431 const CXXScopeSpec &SS,
2432 NamedDecl *FirstQualifierInScope,
2433 DeclarationName Name, SourceLocation NameLoc,
2434 const TemplateArgumentListInfo *TemplateArgs) {
2435 Expr *Base = BaseArg.takeAs<Expr>();
2436
John McCallcd4b4772009-12-02 03:53:29 +00002437 if (BaseType->isDependentType() ||
2438 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002439 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002440 IsArrow, OpLoc,
2441 SS, FirstQualifierInScope,
2442 Name, NameLoc,
2443 TemplateArgs);
2444
2445 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002446
John McCall2d74de92009-12-01 22:10:20 +00002447 // Implicit member accesses.
2448 if (!Base) {
2449 QualType RecordTy = BaseType;
2450 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2451 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2452 RecordTy->getAs<RecordType>(),
2453 OpLoc, SS))
2454 return ExprError();
2455
2456 // Explicit member accesses.
2457 } else {
2458 OwningExprResult Result =
2459 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2460 SS, FirstQualifierInScope,
2461 /*ObjCImpDecl*/ DeclPtrTy());
2462
2463 if (Result.isInvalid()) {
2464 Owned(Base);
2465 return ExprError();
2466 }
2467
2468 if (Result.get())
2469 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002470 }
2471
John McCall2d74de92009-12-01 22:10:20 +00002472 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2473 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002474}
2475
2476Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002477Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2478 SourceLocation OpLoc, bool IsArrow,
2479 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002480 LookupResult &R,
2481 const TemplateArgumentListInfo *TemplateArgs) {
2482 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002483 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002484 if (IsArrow) {
2485 assert(BaseType->isPointerType());
2486 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2487 }
2488
2489 NestedNameSpecifier *Qualifier =
2490 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2491 DeclarationName MemberName = R.getLookupName();
2492 SourceLocation MemberLoc = R.getNameLoc();
2493
2494 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002495 return ExprError();
2496
John McCall10eae182009-11-30 22:42:35 +00002497 if (R.empty()) {
2498 // Rederive where we looked up.
2499 DeclContext *DC = (SS.isSet()
2500 ? computeDeclContext(SS, false)
2501 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002502
John McCall10eae182009-11-30 22:42:35 +00002503 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002504 << MemberName << DC
2505 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002506 return ExprError();
2507 }
2508
John McCallcd4b4772009-12-02 03:53:29 +00002509 // Diagnose qualified lookups that find only declarations from a
2510 // non-base type. Note that it's okay for lookup to find
2511 // declarations from a non-base type as long as those aren't the
2512 // ones picked by overload resolution.
2513 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002514 return ExprError();
2515
2516 // Construct an unresolved result if we in fact got an unresolved
2517 // result.
2518 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002519 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002520 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002521 R.isUnresolvableResult() ||
2522 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002523
2524 UnresolvedMemberExpr *MemExpr
2525 = UnresolvedMemberExpr::Create(Context, Dependent,
2526 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002527 BaseExpr, BaseExprType,
2528 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002529 Qualifier, SS.getRange(),
2530 MemberName, MemberLoc,
2531 TemplateArgs);
2532 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2533 MemExpr->addDecl(*I);
2534
2535 return Owned(MemExpr);
2536 }
2537
2538 assert(R.isSingleResult());
2539 NamedDecl *MemberDecl = R.getFoundDecl();
2540
2541 // FIXME: diagnose the presence of template arguments now.
2542
2543 // If the decl being referenced had an error, return an error for this
2544 // sub-expr without emitting another error, in order to avoid cascading
2545 // error cases.
2546 if (MemberDecl->isInvalidDecl())
2547 return ExprError();
2548
John McCall2d74de92009-12-01 22:10:20 +00002549 // Handle the implicit-member-access case.
2550 if (!BaseExpr) {
2551 // If this is not an instance member, convert to a non-member access.
2552 if (!IsInstanceMember(MemberDecl))
2553 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2554
Douglas Gregorb15af892010-01-07 23:12:05 +00002555 SourceLocation Loc = R.getNameLoc();
2556 if (SS.getRange().isValid())
2557 Loc = SS.getRange().getBegin();
2558 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002559 }
2560
John McCall10eae182009-11-30 22:42:35 +00002561 bool ShouldCheckUse = true;
2562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2563 // Don't diagnose the use of a virtual member function unless it's
2564 // explicitly qualified.
2565 if (MD->isVirtual() && !SS.isSet())
2566 ShouldCheckUse = false;
2567 }
2568
2569 // Check the use of this member.
2570 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2571 Owned(BaseExpr);
2572 return ExprError();
2573 }
2574
2575 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2576 // We may have found a field within an anonymous union or struct
2577 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002578 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2579 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002580 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2581 BaseExpr, OpLoc);
2582
2583 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2584 QualType MemberType = FD->getType();
2585 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2586 MemberType = Ref->getPointeeType();
2587 else {
2588 Qualifiers BaseQuals = BaseType.getQualifiers();
2589 BaseQuals.removeObjCGCAttr();
2590 if (FD->isMutable()) BaseQuals.removeConst();
2591
2592 Qualifiers MemberQuals
2593 = Context.getCanonicalType(MemberType).getQualifiers();
2594
2595 Qualifiers Combined = BaseQuals + MemberQuals;
2596 if (Combined != MemberQuals)
2597 MemberType = Context.getQualifiedType(MemberType, Combined);
2598 }
2599
2600 MarkDeclarationReferenced(MemberLoc, FD);
2601 if (PerformObjectMemberConversion(BaseExpr, FD))
2602 return ExprError();
2603 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2604 FD, MemberLoc, MemberType));
2605 }
2606
2607 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2608 MarkDeclarationReferenced(MemberLoc, Var);
2609 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2610 Var, MemberLoc,
2611 Var->getType().getNonReferenceType()));
2612 }
2613
2614 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2615 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2616 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2617 MemberFn, MemberLoc,
2618 MemberFn->getType()));
2619 }
2620
2621 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2622 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2623 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2624 Enum, MemberLoc, Enum->getType()));
2625 }
2626
2627 Owned(BaseExpr);
2628
2629 if (isa<TypeDecl>(MemberDecl))
2630 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2631 << MemberName << int(IsArrow));
2632
2633 // We found a declaration kind that we didn't expect. This is a
2634 // generic error message that tells the user that she can't refer
2635 // to this member with '.' or '->'.
2636 return ExprError(Diag(MemberLoc,
2637 diag::err_typecheck_member_reference_unknown)
2638 << MemberName << int(IsArrow));
2639}
2640
2641/// Look up the given member of the given non-type-dependent
2642/// expression. This can return in one of two ways:
2643/// * If it returns a sentinel null-but-valid result, the caller will
2644/// assume that lookup was performed and the results written into
2645/// the provided structure. It will take over from there.
2646/// * Otherwise, the returned expression will be produced in place of
2647/// an ordinary member expression.
2648///
2649/// The ObjCImpDecl bit is a gross hack that will need to be properly
2650/// fixed for ObjC++.
2651Sema::OwningExprResult
2652Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002653 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002654 const CXXScopeSpec &SS,
2655 NamedDecl *FirstQualifierInScope,
2656 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002657 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002658
Steve Naroffeaaae462007-12-16 21:42:28 +00002659 // Perform default conversions.
2660 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002661
Steve Naroff185616f2007-07-26 03:11:44 +00002662 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002663 assert(!BaseType->isDependentType());
2664
2665 DeclarationName MemberName = R.getLookupName();
2666 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002667
2668 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002669 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002670 // function. Suggest the addition of those parentheses, build the
2671 // call, and continue on.
2672 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2673 if (const FunctionProtoType *Fun
2674 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2675 QualType ResultTy = Fun->getResultType();
2676 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002677 ((!IsArrow && ResultTy->isRecordType()) ||
2678 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002679 ResultTy->getAs<PointerType>()->getPointeeType()
2680 ->isRecordType()))) {
2681 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2682 Diag(Loc, diag::err_member_reference_needs_call)
2683 << QualType(Fun, 0)
2684 << CodeModificationHint::CreateInsertion(Loc, "()");
2685
2686 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002687 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002688 MultiExprArg(*this, 0, 0), 0, Loc);
2689 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002690 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002691
2692 BaseExpr = NewBase.takeAs<Expr>();
2693 DefaultFunctionArrayConversion(BaseExpr);
2694 BaseType = BaseExpr->getType();
2695 }
2696 }
2697 }
2698
David Chisnall9f57c292009-08-17 16:35:33 +00002699 // If this is an Objective-C pseudo-builtin and a definition is provided then
2700 // use that.
2701 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002702 if (IsArrow) {
2703 // Handle the following exceptional case PObj->isa.
2704 if (const ObjCObjectPointerType *OPT =
2705 BaseType->getAs<ObjCObjectPointerType>()) {
2706 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2707 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002708 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2709 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002710 }
2711 }
David Chisnall9f57c292009-08-17 16:35:33 +00002712 // We have an 'id' type. Rather than fall through, we check if this
2713 // is a reference to 'isa'.
2714 if (BaseType != Context.ObjCIdRedefinitionType) {
2715 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002716 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002717 }
David Chisnall9f57c292009-08-17 16:35:33 +00002718 }
John McCall10eae182009-11-30 22:42:35 +00002719
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002720 // If this is an Objective-C pseudo-builtin and a definition is provided then
2721 // use that.
2722 if (Context.isObjCSelType(BaseType)) {
2723 // We have an 'SEL' type. Rather than fall through, we check if this
2724 // is a reference to 'sel_id'.
2725 if (BaseType != Context.ObjCSelRedefinitionType) {
2726 BaseType = Context.ObjCSelRedefinitionType;
2727 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2728 }
2729 }
John McCall10eae182009-11-30 22:42:35 +00002730
Steve Naroff185616f2007-07-26 03:11:44 +00002731 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002732
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002733 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002734 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002735 // Also must look for a getter name which uses property syntax.
2736 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2737 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2738 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2739 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2740 ObjCMethodDecl *Getter;
2741 // FIXME: need to also look locally in the implementation.
2742 if ((Getter = IFace->lookupClassMethod(Sel))) {
2743 // Check the use of this method.
2744 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2745 return ExprError();
2746 }
2747 // If we found a getter then this may be a valid dot-reference, we
2748 // will look for the matching setter, in case it is needed.
2749 Selector SetterSel =
2750 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2751 PP.getSelectorTable(), Member);
2752 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2753 if (!Setter) {
2754 // If this reference is in an @implementation, also check for 'private'
2755 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002756 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002757 }
2758 // Look through local category implementations associated with the class.
2759 if (!Setter)
2760 Setter = IFace->getCategoryClassMethod(SetterSel);
2761
2762 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2763 return ExprError();
2764
2765 if (Getter || Setter) {
2766 QualType PType;
2767
2768 if (Getter)
2769 PType = Getter->getResultType();
2770 else
2771 // Get the expression type from Setter's incoming parameter.
2772 PType = (*(Setter->param_end() -1))->getType();
2773 // FIXME: we must check that the setter has property type.
2774 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2775 PType,
2776 Setter, MemberLoc, BaseExpr));
2777 }
2778 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2779 << MemberName << BaseType);
2780 }
2781 }
2782
2783 if (BaseType->isObjCClassType() &&
2784 BaseType != Context.ObjCClassRedefinitionType) {
2785 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002786 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002787 }
Mike Stump11289f42009-09-09 15:08:12 +00002788
John McCall10eae182009-11-30 22:42:35 +00002789 if (IsArrow) {
2790 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002791 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002792 else if (BaseType->isObjCObjectPointerType())
2793 ;
John McCalla928c652009-12-07 22:46:59 +00002794 else if (BaseType->isRecordType()) {
2795 // Recover from arrow accesses to records, e.g.:
2796 // struct MyRecord foo;
2797 // foo->bar
2798 // This is actually well-formed in C++ if MyRecord has an
2799 // overloaded operator->, but that should have been dealt with
2800 // by now.
2801 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2802 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2803 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2804 IsArrow = false;
2805 } else {
John McCall10eae182009-11-30 22:42:35 +00002806 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2807 << BaseType << BaseExpr->getSourceRange();
2808 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002809 }
John McCalla928c652009-12-07 22:46:59 +00002810 } else {
2811 // Recover from dot accesses to pointers, e.g.:
2812 // type *foo;
2813 // foo.bar
2814 // This is actually well-formed in two cases:
2815 // - 'type' is an Objective C type
2816 // - 'bar' is a pseudo-destructor name which happens to refer to
2817 // the appropriate pointer type
2818 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2819 const PointerType *PT = BaseType->getAs<PointerType>();
2820 if (PT && PT->getPointeeType()->isRecordType()) {
2821 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2822 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2823 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2824 BaseType = PT->getPointeeType();
2825 IsArrow = true;
2826 }
2827 }
John McCall10eae182009-11-30 22:42:35 +00002828 }
John McCalla928c652009-12-07 22:46:59 +00002829
John McCall10eae182009-11-30 22:42:35 +00002830 // Handle field access to simple records. This also handles access
2831 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002832 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002833 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2834 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002835 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002836 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002837 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002838
Douglas Gregorad8a3362009-09-04 17:36:40 +00002839 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2840 // into a record type was handled above, any destructor we see here is a
2841 // pseudo-destructor.
2842 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2843 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002844 // The left hand side of the dot operator shall be of scalar type. The
2845 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002846 // type.
2847 if (!BaseType->isScalarType())
2848 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2849 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002850
Douglas Gregorad8a3362009-09-04 17:36:40 +00002851 // [...] The type designated by the pseudo-destructor-name shall be the
2852 // same as the object type.
2853 if (!MemberName.getCXXNameType()->isDependentType() &&
2854 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2855 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2856 << BaseType << MemberName.getCXXNameType()
2857 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002858
2859 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002860 // the form
2861 //
Mike Stump11289f42009-09-09 15:08:12 +00002862 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2863 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002864 // shall designate the same scalar type.
2865 //
2866 // FIXME: DPG can't see any way to trigger this particular clause, so it
2867 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002868
Douglas Gregorad8a3362009-09-04 17:36:40 +00002869 // FIXME: We've lost the precise spelling of the type by going through
2870 // DeclarationName. Can we do better?
2871 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002872 IsArrow, OpLoc,
2873 (NestedNameSpecifier *) SS.getScopeRep(),
2874 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002875 MemberName.getCXXNameType(),
2876 MemberLoc));
2877 }
Mike Stump11289f42009-09-09 15:08:12 +00002878
Chris Lattnerdc420f42008-07-21 04:59:05 +00002879 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2880 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002881 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2882 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002883 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002884 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002885 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002886 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002887 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2888
Steve Naroffa057ba92009-07-16 00:25:06 +00002889 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2890 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002891 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002893 if (!IV) {
2894 // Attempt to correct for typos in ivar names.
2895 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2896 LookupMemberName);
2897 if (CorrectTypo(Res, 0, 0, IDecl) &&
2898 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2899 Diag(R.getNameLoc(),
2900 diag::err_typecheck_member_reference_ivar_suggest)
2901 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2902 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2903 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002904 Diag(IV->getLocation(), diag::note_previous_decl)
2905 << IV->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002906 }
2907 }
2908
Steve Naroffa057ba92009-07-16 00:25:06 +00002909 if (IV) {
2910 // If the decl being referenced had an error, return an error for this
2911 // sub-expr without emitting another error, in order to avoid cascading
2912 // error cases.
2913 if (IV->isInvalidDecl())
2914 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002915
Steve Naroffa057ba92009-07-16 00:25:06 +00002916 // Check whether we can reference this field.
2917 if (DiagnoseUseOfDecl(IV, MemberLoc))
2918 return ExprError();
2919 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2920 IV->getAccessControl() != ObjCIvarDecl::Package) {
2921 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2922 if (ObjCMethodDecl *MD = getCurMethodDecl())
2923 ClassOfMethodDecl = MD->getClassInterface();
2924 else if (ObjCImpDecl && getCurFunctionDecl()) {
2925 // Case of a c-function declared inside an objc implementation.
2926 // FIXME: For a c-style function nested inside an objc implementation
2927 // class, there is no implementation context available, so we pass
2928 // down the context as argument to this routine. Ideally, this context
2929 // need be passed down in the AST node and somehow calculated from the
2930 // AST for a function decl.
2931 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002932 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002933 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2934 ClassOfMethodDecl = IMPD->getClassInterface();
2935 else if (ObjCCategoryImplDecl* CatImplClass =
2936 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2937 ClassOfMethodDecl = CatImplClass->getClassInterface();
2938 }
Mike Stump11289f42009-09-09 15:08:12 +00002939
2940 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2941 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002942 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002943 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002944 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002945 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2946 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002947 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002948 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002949 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002950
2951 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2952 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002953 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002954 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002955 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002956 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002957 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002958 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002959 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002960 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002961 if (!IsArrow && (BaseType->isObjCIdType() ||
2962 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002963 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002964 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002965
Steve Naroff7cae42b2009-07-10 23:34:53 +00002966 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002967 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002968 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2969 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2970 // Check the use of this declaration
2971 if (DiagnoseUseOfDecl(PD, MemberLoc))
2972 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002973
Steve Naroff7cae42b2009-07-10 23:34:53 +00002974 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2975 MemberLoc, BaseExpr));
2976 }
2977 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2978 // Check the use of this method.
2979 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2980 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002981
Steve Naroff7cae42b2009-07-10 23:34:53 +00002982 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002983 OMD->getResultType(),
2984 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002985 NULL, 0));
2986 }
2987 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002988
Steve Naroff7cae42b2009-07-10 23:34:53 +00002989 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002990 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002991 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002992 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2993 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002994 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002995 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002996 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2997 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002998 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002999
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003000 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00003001 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003002 // Check whether we can reference this property.
3003 if (DiagnoseUseOfDecl(PD, MemberLoc))
3004 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003005 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00003006 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003007 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00003008 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3009 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003010 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00003011 MemberLoc, BaseExpr));
3012 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003013 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00003014 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3015 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00003016 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003017 // Check whether we can reference this property.
3018 if (DiagnoseUseOfDecl(PD, MemberLoc))
3019 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00003020
Steve Narofff6009ed2009-01-21 00:14:39 +00003021 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00003022 MemberLoc, BaseExpr));
3023 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003024 // If that failed, look for an "implicit" property by seeing if the nullary
3025 // selector is implemented.
3026
3027 // FIXME: The logic for looking up nullary and unary selectors should be
3028 // shared with the code in ActOnInstanceMessage.
3029
Anders Carlssonf571c112009-08-26 18:25:21 +00003030 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003031 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003032
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003033 // If this reference is in an @implementation, check for 'private' methods.
3034 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00003035 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003036
Steve Naroff1df62692008-10-22 19:16:27 +00003037 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003038 if (!Getter)
3039 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003040 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003041 // Check if we can reference this property.
3042 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3043 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003044 }
3045 // If we found a getter then this may be a valid dot-reference, we
3046 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00003047 Selector SetterSel =
3048 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00003049 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003050 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003051 if (!Setter) {
3052 // If this reference is in an @implementation, also check for 'private'
3053 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003054 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003055 }
3056 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003057 if (!Setter)
3058 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003059
Steve Naroff1d984fe2009-03-11 13:48:17 +00003060 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3061 return ExprError();
3062
3063 if (Getter || Setter) {
3064 QualType PType;
3065
3066 if (Getter)
3067 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00003068 else
3069 // Get the expression type from Setter's incoming parameter.
3070 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003071 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00003072 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00003073 Setter, MemberLoc, BaseExpr));
3074 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003075
3076 // Attempt to correct for typos in property names.
3077 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3078 LookupOrdinaryName);
3079 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3080 Res.getAsSingle<ObjCPropertyDecl>()) {
3081 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3082 << MemberName << BaseType << Res.getLookupName()
3083 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3084 Res.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003085 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3086 Diag(Property->getLocation(), diag::note_previous_decl)
3087 << Property->getDeclName();
3088
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003089 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
3090 FirstQualifierInScope, ObjCImpDecl);
3091 }
3092
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003093 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003094 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00003095 }
Mike Stump11289f42009-09-09 15:08:12 +00003096
Steve Naroffe87026a2009-07-24 17:54:45 +00003097 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003098 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00003099 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003100 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003101 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003102 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003103
Chris Lattnerb63a7452008-07-21 04:28:12 +00003104 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003105 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003106 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003107 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3108 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003109 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003110 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003111 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003112 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003113
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003114 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3115 << BaseType << BaseExpr->getSourceRange();
3116
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003117 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003118}
3119
John McCall10eae182009-11-30 22:42:35 +00003120static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3121 SourceLocation NameLoc,
3122 Sema::ExprArg MemExpr) {
3123 Expr *E = (Expr *) MemExpr.get();
3124 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3125 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00003126 << isa<CXXPseudoDestructorExpr>(E)
3127 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3128
John McCall10eae182009-11-30 22:42:35 +00003129 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3130 move(MemExpr),
3131 /*LPLoc*/ ExpectedLParenLoc,
3132 Sema::MultiExprArg(SemaRef, 0, 0),
3133 /*CommaLocs*/ 0,
3134 /*RPLoc*/ ExpectedLParenLoc);
3135}
3136
3137/// The main callback when the parser finds something like
3138/// expression . [nested-name-specifier] identifier
3139/// expression -> [nested-name-specifier] identifier
3140/// where 'identifier' encompasses a fairly broad spectrum of
3141/// possibilities, including destructor and operator references.
3142///
3143/// \param OpKind either tok::arrow or tok::period
3144/// \param HasTrailingLParen whether the next token is '(', which
3145/// is used to diagnose mis-uses of special members that can
3146/// only be called
3147/// \param ObjCImpDecl the current ObjC @implementation decl;
3148/// this is an ugly hack around the fact that ObjC @implementations
3149/// aren't properly put in the context chain
3150Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3151 SourceLocation OpLoc,
3152 tok::TokenKind OpKind,
3153 const CXXScopeSpec &SS,
3154 UnqualifiedId &Id,
3155 DeclPtrTy ObjCImpDecl,
3156 bool HasTrailingLParen) {
3157 if (SS.isSet() && SS.isInvalid())
3158 return ExprError();
3159
3160 TemplateArgumentListInfo TemplateArgsBuffer;
3161
3162 // Decompose the name into its component parts.
3163 DeclarationName Name;
3164 SourceLocation NameLoc;
3165 const TemplateArgumentListInfo *TemplateArgs;
3166 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3167 Name, NameLoc, TemplateArgs);
3168
3169 bool IsArrow = (OpKind == tok::arrow);
3170
3171 NamedDecl *FirstQualifierInScope
3172 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3173 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3174
3175 // This is a postfix expression, so get rid of ParenListExprs.
3176 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3177
3178 Expr *Base = BaseArg.takeAs<Expr>();
3179 OwningExprResult Result(*this);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003180 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCall2d74de92009-12-01 22:10:20 +00003181 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003182 IsArrow, OpLoc,
3183 SS, FirstQualifierInScope,
3184 Name, NameLoc,
3185 TemplateArgs);
3186 } else {
3187 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3188 if (TemplateArgs) {
3189 // Re-use the lookup done for the template name.
3190 DecomposeTemplateName(R, Id);
3191 } else {
3192 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3193 SS, FirstQualifierInScope,
3194 ObjCImpDecl);
3195
3196 if (Result.isInvalid()) {
3197 Owned(Base);
3198 return ExprError();
3199 }
3200
3201 if (Result.get()) {
3202 // The only way a reference to a destructor can be used is to
3203 // immediately call it, which falls into this case. If the
3204 // next token is not a '(', produce a diagnostic and build the
3205 // call now.
3206 if (!HasTrailingLParen &&
3207 Id.getKind() == UnqualifiedId::IK_DestructorName)
3208 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3209
3210 return move(Result);
3211 }
3212 }
3213
John McCall2d74de92009-12-01 22:10:20 +00003214 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3215 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003216 }
3217
3218 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003219}
3220
Anders Carlsson355933d2009-08-25 03:49:14 +00003221Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3222 FunctionDecl *FD,
3223 ParmVarDecl *Param) {
3224 if (Param->hasUnparsedDefaultArg()) {
3225 Diag (CallLoc,
3226 diag::err_use_of_default_argument_to_function_declared_later) <<
3227 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003228 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003229 diag::note_default_argument_declared_here);
3230 } else {
3231 if (Param->hasUninstantiatedDefaultArg()) {
3232 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3233
3234 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003235 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003236
Mike Stump11289f42009-09-09 15:08:12 +00003237 InstantiatingTemplate Inst(*this, CallLoc, Param,
3238 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003239 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003240
John McCall76d824f2009-08-25 22:02:44 +00003241 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003242 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003243 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003244
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003245 // Check the expression as an initializer for the parameter.
3246 InitializedEntity Entity
3247 = InitializedEntity::InitializeParameter(Param);
3248 InitializationKind Kind
3249 = InitializationKind::CreateCopy(Param->getLocation(),
3250 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3251 Expr *ResultE = Result.takeAs<Expr>();
3252
3253 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3254 Result = InitSeq.Perform(*this, Entity, Kind,
3255 MultiExprArg(*this, (void**)&ResultE, 1));
3256 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003257 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003258
3259 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003260 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003261 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003262 }
Mike Stump11289f42009-09-09 15:08:12 +00003263
Anders Carlsson355933d2009-08-25 03:49:14 +00003264 // If the default expression creates temporaries, we need to
3265 // push them to the current stack of expression temporaries so they'll
3266 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003267 // FIXME: We should really be rebuilding the default argument with new
3268 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003269 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3270 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003271 }
3272
3273 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003274 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003275}
3276
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003277/// ConvertArgumentsForCall - Converts the arguments specified in
3278/// Args/NumArgs to the parameter types of the function FDecl with
3279/// function prototype Proto. Call is the call expression itself, and
3280/// Fn is the function expression. For a C++ member function, this
3281/// routine does not attempt to convert the object argument. Returns
3282/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003283bool
3284Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003285 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003286 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003287 Expr **Args, unsigned NumArgs,
3288 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003289 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003290 // assignment, to the types of the corresponding parameter, ...
3291 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003292 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003293
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003294 // If too few arguments are available (and we don't have default
3295 // arguments for the remaining parameters), don't make the call.
3296 if (NumArgs < NumArgsInProto) {
3297 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3298 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3299 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003300 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003301 }
3302
3303 // If too many are passed and not variadic, error on the extras and drop
3304 // them.
3305 if (NumArgs > NumArgsInProto) {
3306 if (!Proto->isVariadic()) {
3307 Diag(Args[NumArgsInProto]->getLocStart(),
3308 diag::err_typecheck_call_too_many_args)
3309 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3310 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3311 Args[NumArgs-1]->getLocEnd());
3312 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003313 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003314 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003315 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003316 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003317 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003318 VariadicCallType CallType =
3319 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3320 if (Fn->getType()->isBlockPointerType())
3321 CallType = VariadicBlock; // Block
3322 else if (isa<MemberExpr>(Fn))
3323 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003324 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003325 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003326 if (Invalid)
3327 return true;
3328 unsigned TotalNumArgs = AllArgs.size();
3329 for (unsigned i = 0; i < TotalNumArgs; ++i)
3330 Call->setArg(i, AllArgs[i]);
3331
3332 return false;
3333}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003334
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003335bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3336 FunctionDecl *FDecl,
3337 const FunctionProtoType *Proto,
3338 unsigned FirstProtoArg,
3339 Expr **Args, unsigned NumArgs,
3340 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003341 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003342 unsigned NumArgsInProto = Proto->getNumArgs();
3343 unsigned NumArgsToCheck = NumArgs;
3344 bool Invalid = false;
3345 if (NumArgs != NumArgsInProto)
3346 // Use default arguments for missing arguments
3347 NumArgsToCheck = NumArgsInProto;
3348 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003349 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003350 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003351 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003352
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003353 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003354 if (ArgIx < NumArgs) {
3355 Arg = Args[ArgIx++];
3356
Eli Friedman3164fb12009-03-22 22:00:50 +00003357 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3358 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003359 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003360 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003361 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003362
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003363 // Pass the argument
3364 ParmVarDecl *Param = 0;
3365 if (FDecl && i < FDecl->getNumParams())
3366 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003367
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003368
3369 InitializedEntity Entity =
3370 Param? InitializedEntity::InitializeParameter(Param)
3371 : InitializedEntity::InitializeParameter(ProtoArgType);
3372 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3373 SourceLocation(),
3374 Owned(Arg));
3375 if (ArgE.isInvalid())
3376 return true;
3377
3378 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003379 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003380 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003381
Mike Stump11289f42009-09-09 15:08:12 +00003382 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003383 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003384 if (ArgExpr.isInvalid())
3385 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003386
Anders Carlsson355933d2009-08-25 03:49:14 +00003387 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003388 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003389 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003390 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003391
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003392 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003393 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003394 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003395 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003396 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003397 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003398 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003399 }
3400 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003401 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003402}
3403
Steve Naroff83895f72007-09-16 03:34:24 +00003404/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003405/// This provides the location of the left/right parens and a list of comma
3406/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003407Action::OwningExprResult
3408Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3409 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003410 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003411 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003412
3413 // Since this might be a postfix expression, get rid of ParenListExprs.
3414 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003415
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003416 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003417 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003418 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003419
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003420 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003421 // If this is a pseudo-destructor expression, build the call immediately.
3422 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3423 if (NumArgs > 0) {
3424 // Pseudo-destructor calls should not have any arguments.
3425 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3426 << CodeModificationHint::CreateRemoval(
3427 SourceRange(Args[0]->getLocStart(),
3428 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003429
Douglas Gregorad8a3362009-09-04 17:36:40 +00003430 for (unsigned I = 0; I != NumArgs; ++I)
3431 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003432
Douglas Gregorad8a3362009-09-04 17:36:40 +00003433 NumArgs = 0;
3434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregorad8a3362009-09-04 17:36:40 +00003436 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3437 RParenLoc));
3438 }
Mike Stump11289f42009-09-09 15:08:12 +00003439
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003440 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003441 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003442 // FIXME: Will need to cache the results of name lookup (including ADL) in
3443 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003444 bool Dependent = false;
3445 if (Fn->isTypeDependent())
3446 Dependent = true;
3447 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3448 Dependent = true;
3449
3450 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003451 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003452 Context.DependentTy, RParenLoc));
3453
3454 // Determine whether this is a call to an object (C++ [over.call.object]).
3455 if (Fn->getType()->isRecordType())
3456 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3457 CommaLocs, RParenLoc));
3458
John McCall10eae182009-11-30 22:42:35 +00003459 Expr *NakedFn = Fn->IgnoreParens();
3460
3461 // Determine whether this is a call to an unresolved member function.
3462 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3463 // If lookup was unresolved but not dependent (i.e. didn't find
3464 // an unresolved using declaration), it has to be an overloaded
3465 // function set, which means it must contain either multiple
3466 // declarations (all methods or method templates) or a single
3467 // method template.
3468 assert((MemE->getNumDecls() > 1) ||
3469 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003470 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003471
John McCall2d74de92009-12-01 22:10:20 +00003472 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3473 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003474 }
3475
Douglas Gregore254f902009-02-04 00:32:51 +00003476 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003477 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003478 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003479 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003480 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3481 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003482 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003483
3484 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003485 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003486 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3487 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003488 if (const FunctionProtoType *FPT =
3489 dyn_cast<FunctionProtoType>(BO->getType())) {
3490 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003491
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003492 ExprOwningPtr<CXXMemberCallExpr>
3493 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3494 NumArgs, ResultTy,
3495 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003496
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003497 if (CheckCallReturnType(FPT->getResultType(),
3498 BO->getRHS()->getSourceRange().getBegin(),
3499 TheCall.get(), 0))
3500 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003501
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003502 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3503 RParenLoc))
3504 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003505
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003506 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3507 }
3508 return ExprError(Diag(Fn->getLocStart(),
3509 diag::err_typecheck_call_not_function)
3510 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003511 }
3512 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003513 }
3514
Douglas Gregore254f902009-02-04 00:32:51 +00003515 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003516 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003517 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003518
Eli Friedmane14b1992009-12-26 03:35:45 +00003519 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003520 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3521 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3522 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3523 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003524 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003525
John McCall57500772009-12-16 12:17:52 +00003526 NamedDecl *NDecl = 0;
3527 if (isa<DeclRefExpr>(NakedFn))
3528 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3529
John McCall2d74de92009-12-01 22:10:20 +00003530 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3531}
3532
John McCall57500772009-12-16 12:17:52 +00003533/// BuildResolvedCallExpr - Build a call to a resolved expression,
3534/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003535/// unary-convert to an expression of function-pointer or
3536/// block-pointer type.
3537///
3538/// \param NDecl the declaration being called, if available
3539Sema::OwningExprResult
3540Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3541 SourceLocation LParenLoc,
3542 Expr **Args, unsigned NumArgs,
3543 SourceLocation RParenLoc) {
3544 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3545
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003546 // Promote the function operand.
3547 UsualUnaryConversions(Fn);
3548
Chris Lattner08464942007-12-28 05:29:59 +00003549 // Make the call expr early, before semantic checks. This guarantees cleanup
3550 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003551 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3552 Args, NumArgs,
3553 Context.BoolTy,
3554 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003555
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003556 const FunctionType *FuncT;
3557 if (!Fn->getType()->isBlockPointerType()) {
3558 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3559 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003560 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003561 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003562 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3563 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003564 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003565 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003566 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003567 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003568 }
Chris Lattner08464942007-12-28 05:29:59 +00003569 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003570 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3571 << Fn->getType() << Fn->getSourceRange());
3572
Eli Friedman3164fb12009-03-22 22:00:50 +00003573 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003574 if (CheckCallReturnType(FuncT->getResultType(),
3575 Fn->getSourceRange().getBegin(), TheCall.get(),
3576 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003577 return ExprError();
3578
Chris Lattner08464942007-12-28 05:29:59 +00003579 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003580 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003581
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003582 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003583 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003584 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003585 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003586 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003587 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003588
Douglas Gregord8e97de2009-04-02 15:37:10 +00003589 if (FDecl) {
3590 // Check if we have too few/too many template arguments, based
3591 // on our knowledge of the function definition.
3592 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003593 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003594 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003595 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003596 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3597 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3598 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3599 }
3600 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003601 }
3602
Steve Naroff0b661582007-08-28 23:30:39 +00003603 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003604 for (unsigned i = 0; i != NumArgs; i++) {
3605 Expr *Arg = Args[i];
3606 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003607 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3608 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003609 PDiag(diag::err_call_incomplete_argument)
3610 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003611 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003612 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003613 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003614 }
Chris Lattner08464942007-12-28 05:29:59 +00003615
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003616 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3617 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003618 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3619 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003620
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003621 // Check for sentinels
3622 if (NDecl)
3623 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003624
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003625 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003626 if (FDecl) {
3627 if (CheckFunctionCall(FDecl, TheCall.get()))
3628 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregor15fc9562009-09-12 00:22:50 +00003630 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003631 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3632 } else if (NDecl) {
3633 if (CheckBlockCall(NDecl, TheCall.get()))
3634 return ExprError();
3635 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003636
Anders Carlssonf8984012009-08-16 03:06:32 +00003637 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003638}
3639
Sebastian Redlb5d49352009-01-19 22:31:54 +00003640Action::OwningExprResult
3641Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3642 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003643 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor85dabae2009-12-16 01:38:02 +00003644
Douglas Gregor1b303932009-12-22 15:35:07 +00003645 QualType literalType = GetTypeFromParser(Ty);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003646
Steve Naroff57eb2c52007-07-19 21:32:11 +00003647 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003648 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003649 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003650
Eli Friedman37a186d2008-05-20 05:22:08 +00003651 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003652 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003653 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3654 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003655 } else if (!literalType->isDependentType() &&
3656 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003657 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003658 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003659 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003660 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003661
Douglas Gregor85dabae2009-12-16 01:38:02 +00003662 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003663 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003664 InitializationKind Kind
3665 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3666 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003667 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3668 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3669 MultiExprArg(*this, (void**)&literalExpr, 1),
3670 &literalType);
3671 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003672 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003673 InitExpr.release();
3674 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003675
Chris Lattner79413952008-12-04 23:50:19 +00003676 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003677 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003678 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003679 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003680 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003681
3682 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003683
3684 // FIXME: Store the TInfo to preserve type information better.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003685 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003686 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003687}
3688
Sebastian Redlb5d49352009-01-19 22:31:54 +00003689Action::OwningExprResult
3690Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003691 SourceLocation RBraceLoc) {
3692 unsigned NumInit = initlist.size();
3693 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003694
Steve Naroff30d242c2007-09-15 18:49:24 +00003695 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003696 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003697
Mike Stump4e1f26a2009-02-19 03:04:26 +00003698 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003699 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003700 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003701 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003702}
3703
Anders Carlsson094c4592009-10-18 18:12:03 +00003704static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3705 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003706 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003707 return CastExpr::CK_NoOp;
3708
3709 if (SrcTy->hasPointerRepresentation()) {
3710 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003711 return DestTy->isObjCObjectPointerType() ?
3712 CastExpr::CK_AnyPointerToObjCPointerCast :
3713 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003714 if (DestTy->isIntegerType())
3715 return CastExpr::CK_PointerToIntegral;
3716 }
3717
3718 if (SrcTy->isIntegerType()) {
3719 if (DestTy->isIntegerType())
3720 return CastExpr::CK_IntegralCast;
3721 if (DestTy->hasPointerRepresentation())
3722 return CastExpr::CK_IntegralToPointer;
3723 if (DestTy->isRealFloatingType())
3724 return CastExpr::CK_IntegralToFloating;
3725 }
3726
3727 if (SrcTy->isRealFloatingType()) {
3728 if (DestTy->isRealFloatingType())
3729 return CastExpr::CK_FloatingCast;
3730 if (DestTy->isIntegerType())
3731 return CastExpr::CK_FloatingToIntegral;
3732 }
3733
3734 // FIXME: Assert here.
3735 // assert(false && "Unhandled cast combination!");
3736 return CastExpr::CK_Unknown;
3737}
3738
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003739/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003740bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003741 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003742 CXXMethodDecl *& ConversionDecl,
3743 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003744 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003745 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3746 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003747
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003748 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003749
3750 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3751 // type needs to be scalar.
3752 if (castType->isVoidType()) {
3753 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003754 Kind = CastExpr::CK_ToVoid;
3755 return false;
3756 }
3757
3758 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003759 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003760 (castType->isStructureType() || castType->isUnionType())) {
3761 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003762 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003763 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3764 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003765 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003766 return false;
3767 }
3768
3769 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003770 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003771 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003772 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003773 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003774 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003775 if (Context.hasSameUnqualifiedType(Field->getType(),
3776 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003777 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3778 << castExpr->getSourceRange();
3779 break;
3780 }
3781 }
3782 if (Field == FieldEnd)
3783 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3784 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003785 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003786 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003787 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003788
3789 // Reject any other conversions to non-scalar types.
3790 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3791 << castType << castExpr->getSourceRange();
3792 }
3793
3794 if (!castExpr->getType()->isScalarType() &&
3795 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003796 return Diag(castExpr->getLocStart(),
3797 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003798 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003799 }
3800
Anders Carlsson43d70f82009-10-16 05:23:41 +00003801 if (castType->isExtVectorType())
3802 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3803
Anders Carlsson525b76b2009-10-16 02:48:28 +00003804 if (castType->isVectorType())
3805 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3806 if (castExpr->getType()->isVectorType())
3807 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3808
3809 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003810 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003811
Anders Carlsson43d70f82009-10-16 05:23:41 +00003812 if (isa<ObjCSelectorExpr>(castExpr))
3813 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3814
Anders Carlsson525b76b2009-10-16 02:48:28 +00003815 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003816 QualType castExprType = castExpr->getType();
3817 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3818 return Diag(castExpr->getLocStart(),
3819 diag::err_cast_pointer_from_non_pointer_int)
3820 << castExprType << castExpr->getSourceRange();
3821 } else if (!castExpr->getType()->isArithmeticType()) {
3822 if (!castType->isIntegralType() && castType->isArithmeticType())
3823 return Diag(castExpr->getLocStart(),
3824 diag::err_cast_pointer_to_non_pointer_int)
3825 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003826 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003827
3828 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003829 return false;
3830}
3831
Anders Carlsson525b76b2009-10-16 02:48:28 +00003832bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3833 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003834 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003835
Anders Carlssonde71adf2007-11-27 05:51:55 +00003836 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003837 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003838 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003839 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003840 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003841 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003842 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003843 } else
3844 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003845 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003846 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003847
Anders Carlsson525b76b2009-10-16 02:48:28 +00003848 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003849 return false;
3850}
3851
Anders Carlsson43d70f82009-10-16 05:23:41 +00003852bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3853 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003854 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003855
3856 QualType SrcTy = CastExpr->getType();
3857
Nate Begemanc8961a42009-06-27 22:05:55 +00003858 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3859 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003860 if (SrcTy->isVectorType()) {
3861 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3862 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3863 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003864 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003865 return false;
3866 }
3867
Nate Begemanbd956c42009-06-28 02:36:38 +00003868 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003869 // conversion will take place first from scalar to elt type, and then
3870 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003871 if (SrcTy->isPointerType())
3872 return Diag(R.getBegin(),
3873 diag::err_invalid_conversion_between_vector_and_scalar)
3874 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003875
3876 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3877 ImpCastExprToType(CastExpr, DestElemTy,
3878 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003879
3880 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003881 return false;
3882}
3883
Sebastian Redlb5d49352009-01-19 22:31:54 +00003884Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003885Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003886 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003887 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003888
Sebastian Redlb5d49352009-01-19 22:31:54 +00003889 assert((Ty != 0) && (Op.get() != 0) &&
3890 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003891
Nate Begeman5ec4b312009-08-10 23:49:36 +00003892 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003893 //FIXME: Preserve type source info.
3894 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003895
Nate Begeman5ec4b312009-08-10 23:49:36 +00003896 // If the Expr being casted is a ParenListExpr, handle it specially.
3897 if (isa<ParenListExpr>(castExpr))
3898 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003899 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003900 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003901 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003902 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003903
3904 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003905 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003906 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003907
Anders Carlssone9766d52009-09-09 21:33:21 +00003908 if (CastArg.isInvalid())
3909 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003910
Anders Carlssone9766d52009-09-09 21:33:21 +00003911 castExpr = CastArg.takeAs<Expr>();
3912 } else {
3913 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003914 }
Mike Stump11289f42009-09-09 15:08:12 +00003915
Sebastian Redl9f831db2009-07-25 15:41:38 +00003916 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003917 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003918 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003919}
3920
Nate Begeman5ec4b312009-08-10 23:49:36 +00003921/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3922/// of comma binary operators.
3923Action::OwningExprResult
3924Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3925 Expr *expr = EA.takeAs<Expr>();
3926 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3927 if (!E)
3928 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003929
Nate Begeman5ec4b312009-08-10 23:49:36 +00003930 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003931
Nate Begeman5ec4b312009-08-10 23:49:36 +00003932 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3933 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3934 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003935
Nate Begeman5ec4b312009-08-10 23:49:36 +00003936 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3937}
3938
3939Action::OwningExprResult
3940Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3941 SourceLocation RParenLoc, ExprArg Op,
3942 QualType Ty) {
3943 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003944
3945 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003946 // then handle it as such.
3947 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3948 if (PE->getNumExprs() == 0) {
3949 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3950 return ExprError();
3951 }
3952
3953 llvm::SmallVector<Expr *, 8> initExprs;
3954 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3955 initExprs.push_back(PE->getExpr(i));
3956
3957 // FIXME: This means that pretty-printing the final AST will produce curly
3958 // braces instead of the original commas.
3959 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003960 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003961 initExprs.size(), RParenLoc);
3962 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003963 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003964 Owned(E));
3965 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003966 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003967 // sequence of BinOp comma operators.
3968 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3969 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3970 }
3971}
3972
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003973Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003974 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003975 MultiExprArg Val,
3976 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003977 unsigned nexprs = Val.size();
3978 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003979 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3980 Expr *expr;
3981 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3982 expr = new (Context) ParenExpr(L, R, exprs[0]);
3983 else
3984 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003985 return Owned(expr);
3986}
3987
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003988/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3989/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003990/// C99 6.5.15
3991QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3992 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003993 // C++ is sufficiently different to merit its own checker.
3994 if (getLangOptions().CPlusPlus)
3995 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3996
John McCall1fa36b72009-11-05 09:23:39 +00003997 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3998
Chris Lattner432cff52009-02-18 04:28:32 +00003999 UsualUnaryConversions(Cond);
4000 UsualUnaryConversions(LHS);
4001 UsualUnaryConversions(RHS);
4002 QualType CondTy = Cond->getType();
4003 QualType LHSTy = LHS->getType();
4004 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004005
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004006 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004007 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4008 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4009 << CondTy;
4010 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004011 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004012
Chris Lattnere2949f42008-01-06 22:42:25 +00004013 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004014 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4015 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004016
Chris Lattnere2949f42008-01-06 22:42:25 +00004017 // If both operands have arithmetic type, do the usual arithmetic conversions
4018 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004019 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4020 UsualArithmeticConversions(LHS, RHS);
4021 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004022 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004023
Chris Lattnere2949f42008-01-06 22:42:25 +00004024 // If both operands are the same structure or union type, the result is that
4025 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004026 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4027 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004028 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004029 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004030 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004031 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004032 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004033 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004034
Chris Lattnere2949f42008-01-06 22:42:25 +00004035 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004036 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004037 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4038 if (!LHSTy->isVoidType())
4039 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4040 << RHS->getSourceRange();
4041 if (!RHSTy->isVoidType())
4042 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4043 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004044 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4045 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004046 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004047 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004048 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4049 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004050 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004051 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004052 // promote the null to a pointer.
4053 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004054 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004055 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004056 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004057 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004058 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004059 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004060 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004061
4062 // All objective-c pointer type analysis is done here.
4063 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4064 QuestionLoc);
4065 if (!compositeType.isNull())
4066 return compositeType;
4067
4068
Steve Naroff05efa972009-07-01 14:36:47 +00004069 // Handle block pointer types.
4070 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4071 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4072 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4073 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004074 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4075 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004076 return destType;
4077 }
4078 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004079 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004080 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004081 }
Steve Naroff05efa972009-07-01 14:36:47 +00004082 // We have 2 block pointer types.
4083 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4084 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004085 return LHSTy;
4086 }
Steve Naroff05efa972009-07-01 14:36:47 +00004087 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004088 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4089 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004090
Steve Naroff05efa972009-07-01 14:36:47 +00004091 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4092 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004093 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004094 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004095 // In this situation, we assume void* type. No especially good
4096 // reason, but this is what gcc does, and we do have to pick
4097 // to get a consistent AST.
4098 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004099 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4100 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004101 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004102 }
Steve Naroff05efa972009-07-01 14:36:47 +00004103 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004104 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4105 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004106 return LHSTy;
4107 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004108
Steve Naroff05efa972009-07-01 14:36:47 +00004109 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4110 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4111 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004112 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4113 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004114
4115 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4116 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4117 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004118 QualType destPointee
4119 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004120 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004121 // Add qualifiers if necessary.
4122 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4123 // Promote to void*.
4124 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004125 return destType;
4126 }
4127 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004128 QualType destPointee
4129 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004130 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004131 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004132 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004133 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004134 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004135 return destType;
4136 }
4137
4138 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4139 // Two identical pointer types are always compatible.
4140 return LHSTy;
4141 }
4142 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4143 rhptee.getUnqualifiedType())) {
4144 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4145 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4146 // In this situation, we assume void* type. No especially good
4147 // reason, but this is what gcc does, and we do have to pick
4148 // to get a consistent AST.
4149 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004150 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4151 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004152 return incompatTy;
4153 }
4154 // The pointer types are compatible.
4155 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4156 // differently qualified versions of compatible types, the result type is
4157 // a pointer to an appropriately qualified version of the *composite*
4158 // type.
4159 // FIXME: Need to calculate the composite type.
4160 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004161 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4162 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004163 return LHSTy;
4164 }
Mike Stump11289f42009-09-09 15:08:12 +00004165
Steve Naroff05efa972009-07-01 14:36:47 +00004166 // GCC compatibility: soften pointer/integer mismatch.
4167 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4168 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4169 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004170 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004171 return RHSTy;
4172 }
4173 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4174 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4175 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004176 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004177 return LHSTy;
4178 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004179
Chris Lattnere2949f42008-01-06 22:42:25 +00004180 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004181 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4182 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004183 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004184}
4185
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004186/// FindCompositeObjCPointerType - Helper method to find composite type of
4187/// two objective-c pointer types of the two input expressions.
4188QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4189 SourceLocation QuestionLoc) {
4190 QualType LHSTy = LHS->getType();
4191 QualType RHSTy = RHS->getType();
4192
4193 // Handle things like Class and struct objc_class*. Here we case the result
4194 // to the pseudo-builtin, because that will be implicitly cast back to the
4195 // redefinition type if an attempt is made to access its fields.
4196 if (LHSTy->isObjCClassType() &&
4197 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4198 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4199 return LHSTy;
4200 }
4201 if (RHSTy->isObjCClassType() &&
4202 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4203 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4204 return RHSTy;
4205 }
4206 // And the same for struct objc_object* / id
4207 if (LHSTy->isObjCIdType() &&
4208 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4209 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4210 return LHSTy;
4211 }
4212 if (RHSTy->isObjCIdType() &&
4213 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4214 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4215 return RHSTy;
4216 }
4217 // And the same for struct objc_selector* / SEL
4218 if (Context.isObjCSelType(LHSTy) &&
4219 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4220 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4221 return LHSTy;
4222 }
4223 if (Context.isObjCSelType(RHSTy) &&
4224 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4225 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4226 return RHSTy;
4227 }
4228 // Check constraints for Objective-C object pointers types.
4229 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4230
4231 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4232 // Two identical object pointer types are always compatible.
4233 return LHSTy;
4234 }
4235 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4236 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4237 QualType compositeType = LHSTy;
4238
4239 // If both operands are interfaces and either operand can be
4240 // assigned to the other, use that type as the composite
4241 // type. This allows
4242 // xxx ? (A*) a : (B*) b
4243 // where B is a subclass of A.
4244 //
4245 // Additionally, as for assignment, if either type is 'id'
4246 // allow silent coercion. Finally, if the types are
4247 // incompatible then make sure to use 'id' as the composite
4248 // type so the result is acceptable for sending messages to.
4249
4250 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4251 // It could return the composite type.
4252 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4253 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4254 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4255 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4256 } else if ((LHSTy->isObjCQualifiedIdType() ||
4257 RHSTy->isObjCQualifiedIdType()) &&
4258 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4259 // Need to handle "id<xx>" explicitly.
4260 // GCC allows qualified id and any Objective-C type to devolve to
4261 // id. Currently localizing to here until clear this should be
4262 // part of ObjCQualifiedIdTypesAreCompatible.
4263 compositeType = Context.getObjCIdType();
4264 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4265 compositeType = Context.getObjCIdType();
4266 } else if (!(compositeType =
4267 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4268 ;
4269 else {
4270 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4271 << LHSTy << RHSTy
4272 << LHS->getSourceRange() << RHS->getSourceRange();
4273 QualType incompatTy = Context.getObjCIdType();
4274 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4275 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4276 return incompatTy;
4277 }
4278 // The object pointer types are compatible.
4279 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4280 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4281 return compositeType;
4282 }
4283 // Check Objective-C object pointer types and 'void *'
4284 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4285 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4286 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4287 QualType destPointee
4288 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4289 QualType destType = Context.getPointerType(destPointee);
4290 // Add qualifiers if necessary.
4291 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4292 // Promote to void*.
4293 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4294 return destType;
4295 }
4296 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4297 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4298 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4299 QualType destPointee
4300 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4301 QualType destType = Context.getPointerType(destPointee);
4302 // Add qualifiers if necessary.
4303 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4304 // Promote to void*.
4305 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4306 return destType;
4307 }
4308 return QualType();
4309}
4310
Steve Naroff83895f72007-09-16 03:34:24 +00004311/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004312/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004313Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4314 SourceLocation ColonLoc,
4315 ExprArg Cond, ExprArg LHS,
4316 ExprArg RHS) {
4317 Expr *CondExpr = (Expr *) Cond.get();
4318 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004319
4320 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4321 // was the condition.
4322 bool isLHSNull = LHSExpr == 0;
4323 if (isLHSNull)
4324 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004325
4326 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004327 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004328 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004329 return ExprError();
4330
4331 Cond.release();
4332 LHS.release();
4333 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004334 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004335 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004336 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004337}
4338
Steve Naroff3f597292007-05-11 22:18:03 +00004339// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004340// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004341// routine is it effectively iqnores the qualifiers on the top level pointee.
4342// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4343// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004344Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004345Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004346 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004347
David Chisnall9f57c292009-08-17 16:35:33 +00004348 if ((lhsType->isObjCClassType() &&
4349 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4350 (rhsType->isObjCClassType() &&
4351 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4352 return Compatible;
4353 }
4354
Steve Naroff1f4d7272007-05-11 04:00:31 +00004355 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004356 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4357 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004358
Steve Naroff1f4d7272007-05-11 04:00:31 +00004359 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004360 lhptee = Context.getCanonicalType(lhptee);
4361 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004362
Chris Lattner9bad62c2008-01-04 18:04:52 +00004363 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004364
4365 // C99 6.5.16.1p1: This following citation is common to constraints
4366 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4367 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004368 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004369 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004370 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004371
Mike Stump4e1f26a2009-02-19 03:04:26 +00004372 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4373 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004374 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004375 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004376 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004377 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004378
Chris Lattner0a788432008-01-03 22:56:36 +00004379 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004380 assert(rhptee->isFunctionType());
4381 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004382 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004383
Chris Lattner0a788432008-01-03 22:56:36 +00004384 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004385 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004386 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004387
4388 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004389 assert(lhptee->isFunctionType());
4390 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004391 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004392 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004393 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004394 lhptee = lhptee.getUnqualifiedType();
4395 rhptee = rhptee.getUnqualifiedType();
4396 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4397 // Check if the pointee types are compatible ignoring the sign.
4398 // We explicitly check for char so that we catch "char" vs
4399 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004400 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004401 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004402 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004403 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004404
4405 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004406 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004407 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004408 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004409
Eli Friedman80160bd2009-03-22 23:59:44 +00004410 if (lhptee == rhptee) {
4411 // Types are compatible ignoring the sign. Qualifier incompatibility
4412 // takes priority over sign incompatibility because the sign
4413 // warning can be disabled.
4414 if (ConvTy != Compatible)
4415 return ConvTy;
4416 return IncompatiblePointerSign;
4417 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004418
4419 // If we are a multi-level pointer, it's possible that our issue is simply
4420 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4421 // the eventual target type is the same and the pointers have the same
4422 // level of indirection, this must be the issue.
4423 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4424 do {
4425 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4426 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4427
4428 lhptee = Context.getCanonicalType(lhptee);
4429 rhptee = Context.getCanonicalType(rhptee);
4430 } while (lhptee->isPointerType() && rhptee->isPointerType());
4431
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004432 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004433 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004434 }
4435
Eli Friedman80160bd2009-03-22 23:59:44 +00004436 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004437 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004438 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004439 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004440}
4441
Steve Naroff081c7422008-09-04 15:10:53 +00004442/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4443/// block pointer types are compatible or whether a block and normal pointer
4444/// are compatible. It is more restrict than comparing two function pointer
4445// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004446Sema::AssignConvertType
4447Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004448 QualType rhsType) {
4449 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004450
Steve Naroff081c7422008-09-04 15:10:53 +00004451 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004452 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4453 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004454
Steve Naroff081c7422008-09-04 15:10:53 +00004455 // make sure we operate on the canonical type
4456 lhptee = Context.getCanonicalType(lhptee);
4457 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004458
Steve Naroff081c7422008-09-04 15:10:53 +00004459 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004460
Steve Naroff081c7422008-09-04 15:10:53 +00004461 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004462 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004463 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004464
Eli Friedmana6638ca2009-06-08 05:08:54 +00004465 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004466 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004467 return ConvTy;
4468}
4469
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004470/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4471/// for assignment compatibility.
4472Sema::AssignConvertType
4473Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4474 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4475 return Compatible;
4476 QualType lhptee =
4477 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4478 QualType rhptee =
4479 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4480 // make sure we operate on the canonical type
4481 lhptee = Context.getCanonicalType(lhptee);
4482 rhptee = Context.getCanonicalType(rhptee);
4483 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4484 return CompatiblePointerDiscardsQualifiers;
4485
4486 if (Context.typesAreCompatible(lhsType, rhsType))
4487 return Compatible;
4488 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4489 return IncompatibleObjCQualifiedId;
4490 return IncompatiblePointer;
4491}
4492
Mike Stump4e1f26a2009-02-19 03:04:26 +00004493/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4494/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004495/// pointers. Here are some objectionable examples that GCC considers warnings:
4496///
4497/// int a, *pint;
4498/// short *pshort;
4499/// struct foo *pfoo;
4500///
4501/// pint = pshort; // warning: assignment from incompatible pointer type
4502/// a = pint; // warning: assignment makes integer from pointer without a cast
4503/// pint = a; // warning: assignment makes pointer from integer without a cast
4504/// pint = pfoo; // warning: assignment from incompatible pointer type
4505///
4506/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004507/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004508///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004509Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004510Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004511 // Get canonical types. We're not formatting these types, just comparing
4512 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004513 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4514 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004515
4516 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004517 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004518
David Chisnall9f57c292009-08-17 16:35:33 +00004519 if ((lhsType->isObjCClassType() &&
4520 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4521 (rhsType->isObjCClassType() &&
4522 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4523 return Compatible;
4524 }
4525
Douglas Gregor6b754842008-10-28 00:22:11 +00004526 // If the left-hand side is a reference type, then we are in a
4527 // (rare!) case where we've allowed the use of references in C,
4528 // e.g., as a parameter type in a built-in function. In this case,
4529 // just make sure that the type referenced is compatible with the
4530 // right-hand side type. The caller is responsible for adjusting
4531 // lhsType so that the resulting expression does not have reference
4532 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004533 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004534 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004535 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004536 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004537 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004538 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4539 // to the same ExtVector type.
4540 if (lhsType->isExtVectorType()) {
4541 if (rhsType->isExtVectorType())
4542 return lhsType == rhsType ? Compatible : Incompatible;
4543 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4544 return Compatible;
4545 }
Mike Stump11289f42009-09-09 15:08:12 +00004546
Nate Begeman191a6b12008-07-14 18:02:46 +00004547 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004548 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004549 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004550 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004551 if (getLangOptions().LaxVectorConversions &&
4552 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004553 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004554 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004555 }
4556 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004557 }
Eli Friedman3360d892008-05-30 18:07:22 +00004558
Chris Lattner881a2122008-01-04 23:32:24 +00004559 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004560 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004561
Chris Lattnerec646832008-04-07 06:49:41 +00004562 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004563 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004564 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004565
Chris Lattnerec646832008-04-07 06:49:41 +00004566 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004567 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004568
Steve Naroffaccc4882009-07-20 17:56:53 +00004569 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004570 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004571 if (lhsType->isVoidPointerType()) // an exception to the rule.
4572 return Compatible;
4573 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004574 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004575 if (rhsType->getAs<BlockPointerType>()) {
4576 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004577 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004578
4579 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004580 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004581 return Compatible;
4582 }
Steve Naroff081c7422008-09-04 15:10:53 +00004583 return Incompatible;
4584 }
4585
4586 if (isa<BlockPointerType>(lhsType)) {
4587 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004588 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004589
Steve Naroff32d072c2008-09-29 18:10:17 +00004590 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004591 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004592 return Compatible;
4593
Steve Naroff081c7422008-09-04 15:10:53 +00004594 if (rhsType->isBlockPointerType())
4595 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004596
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004597 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004598 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004599 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004600 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004601 return Incompatible;
4602 }
4603
Steve Naroff7cae42b2009-07-10 23:34:53 +00004604 if (isa<ObjCObjectPointerType>(lhsType)) {
4605 if (rhsType->isIntegerType())
4606 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004607
Steve Naroffaccc4882009-07-20 17:56:53 +00004608 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004609 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004610 if (rhsType->isVoidPointerType()) // an exception to the rule.
4611 return Compatible;
4612 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004613 }
4614 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004615 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004616 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004617 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004618 if (RHSPT->getPointeeType()->isVoidType())
4619 return Compatible;
4620 }
4621 // Treat block pointers as objects.
4622 if (rhsType->isBlockPointerType())
4623 return Compatible;
4624 return Incompatible;
4625 }
Chris Lattnerec646832008-04-07 06:49:41 +00004626 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004627 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004628 if (lhsType == Context.BoolTy)
4629 return Compatible;
4630
4631 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004632 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004633
Mike Stump4e1f26a2009-02-19 03:04:26 +00004634 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004635 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004636
4637 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004638 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004639 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004640 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004641 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004642 if (isa<ObjCObjectPointerType>(rhsType)) {
4643 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4644 if (lhsType == Context.BoolTy)
4645 return Compatible;
4646
4647 if (lhsType->isIntegerType())
4648 return PointerToInt;
4649
Steve Naroffaccc4882009-07-20 17:56:53 +00004650 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004651 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004652 if (lhsType->isVoidPointerType()) // an exception to the rule.
4653 return Compatible;
4654 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004655 }
4656 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004657 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004658 return Compatible;
4659 return Incompatible;
4660 }
Eli Friedman3360d892008-05-30 18:07:22 +00004661
Chris Lattnera52c2f22008-01-04 23:18:45 +00004662 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004663 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004664 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004665 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004666 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004667}
4668
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004669/// \brief Constructs a transparent union from an expression that is
4670/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004671static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004672 QualType UnionType, FieldDecl *Field) {
4673 // Build an initializer list that designates the appropriate member
4674 // of the transparent union.
4675 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4676 &E, 1,
4677 SourceLocation());
4678 Initializer->setType(UnionType);
4679 Initializer->setInitializedFieldInUnion(Field);
4680
4681 // Build a compound literal constructing a value of the transparent
4682 // union type from this initializer list.
4683 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4684 false);
4685}
4686
4687Sema::AssignConvertType
4688Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4689 QualType FromType = rExpr->getType();
4690
Mike Stump11289f42009-09-09 15:08:12 +00004691 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004692 // transparent_union GCC extension.
4693 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004694 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004695 return Incompatible;
4696
4697 // The field to initialize within the transparent union.
4698 RecordDecl *UD = UT->getDecl();
4699 FieldDecl *InitField = 0;
4700 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004701 for (RecordDecl::field_iterator it = UD->field_begin(),
4702 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004703 it != itend; ++it) {
4704 if (it->getType()->isPointerType()) {
4705 // If the transparent union contains a pointer type, we allow:
4706 // 1) void pointer
4707 // 2) null pointer constant
4708 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004709 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004710 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004711 InitField = *it;
4712 break;
4713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
Douglas Gregor56751b52009-09-25 04:25:58 +00004715 if (rExpr->isNullPointerConstant(Context,
4716 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004717 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004718 InitField = *it;
4719 break;
4720 }
4721 }
4722
4723 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4724 == Compatible) {
4725 InitField = *it;
4726 break;
4727 }
4728 }
4729
4730 if (!InitField)
4731 return Incompatible;
4732
4733 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4734 return Compatible;
4735}
4736
Chris Lattner9bad62c2008-01-04 18:04:52 +00004737Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004738Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004739 if (getLangOptions().CPlusPlus) {
4740 if (!lhsType->isRecordType()) {
4741 // C++ 5.17p3: If the left operand is not of class type, the
4742 // expression is implicitly converted (C++ 4) to the
4743 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004744 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004745 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004746 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004747 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004748 }
4749
4750 // FIXME: Currently, we fall through and treat C++ classes like C
4751 // structures.
4752 }
4753
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004754 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4755 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004756 if ((lhsType->isPointerType() ||
4757 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004758 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004759 && rExpr->isNullPointerConstant(Context,
4760 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004761 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004762 return Compatible;
4763 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004764
Chris Lattnere6dcd502007-10-16 02:55:40 +00004765 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004766 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004767 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004768 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004769 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004770 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004771 if (!lhsType->isReferenceType())
4772 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004773
Chris Lattner9bad62c2008-01-04 18:04:52 +00004774 Sema::AssignConvertType result =
4775 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004776
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004777 // C99 6.5.16.1p2: The value of the right operand is converted to the
4778 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004779 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4780 // so that we can use references in built-in functions even in C.
4781 // The getNonReferenceType() call makes sure that the resulting expression
4782 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004783 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004784 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4785 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004786 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004787}
4788
Chris Lattner326f7572008-11-18 01:30:42 +00004789QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004790 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004791 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004792 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004793 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004794}
4795
Chris Lattnerfaa54172010-01-12 21:23:57 +00004796QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004797 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004798 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004799 QualType lhsType =
4800 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4801 QualType rhsType =
4802 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004803
Nate Begeman191a6b12008-07-14 18:02:46 +00004804 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004805 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004806 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004807
Nate Begeman191a6b12008-07-14 18:02:46 +00004808 // Handle the case of a vector & extvector type of the same size and element
4809 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004810 if (getLangOptions().LaxVectorConversions) {
4811 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004812 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4813 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004814 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004815 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004816 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004817 }
4818 }
4819 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004820
Nate Begemanbd956c42009-06-28 02:36:38 +00004821 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4822 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4823 bool swapped = false;
4824 if (rhsType->isExtVectorType()) {
4825 swapped = true;
4826 std::swap(rex, lex);
4827 std::swap(rhsType, lhsType);
4828 }
Mike Stump11289f42009-09-09 15:08:12 +00004829
Nate Begeman886448d2009-06-28 19:12:57 +00004830 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004831 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004832 QualType EltTy = LV->getElementType();
4833 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4834 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004835 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004836 if (swapped) std::swap(rex, lex);
4837 return lhsType;
4838 }
4839 }
4840 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4841 rhsType->isRealFloatingType()) {
4842 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004843 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004844 if (swapped) std::swap(rex, lex);
4845 return lhsType;
4846 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004847 }
4848 }
Mike Stump11289f42009-09-09 15:08:12 +00004849
Nate Begeman886448d2009-06-28 19:12:57 +00004850 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004851 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004852 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004853 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004854 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004855}
4856
Chris Lattnerfaa54172010-01-12 21:23:57 +00004857QualType Sema::CheckMultiplyDivideOperands(
4858 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004859 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004860 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004861
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004862 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004863
Chris Lattnerfaa54172010-01-12 21:23:57 +00004864 if (!lex->getType()->isArithmeticType() ||
4865 !rex->getType()->isArithmeticType())
4866 return InvalidOperands(Loc, lex, rex);
4867
4868 // Check for division by zero.
4869 if (isDiv &&
4870 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004871 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4872 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004873
4874 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004875}
4876
Chris Lattnerfaa54172010-01-12 21:23:57 +00004877QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004878 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004879 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4880 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4881 return CheckVectorOperands(Loc, lex, rex);
4882 return InvalidOperands(Loc, lex, rex);
4883 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004884
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004885 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004886
Chris Lattnerfaa54172010-01-12 21:23:57 +00004887 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4888 return InvalidOperands(Loc, lex, rex);
4889
4890 // Check for remainder by zero.
4891 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004892 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4893 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004894
4895 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004896}
4897
Chris Lattnerfaa54172010-01-12 21:23:57 +00004898QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004899 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004900 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4901 QualType compType = CheckVectorOperands(Loc, lex, rex);
4902 if (CompLHSTy) *CompLHSTy = compType;
4903 return compType;
4904 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004905
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004906 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004907
Steve Naroffe4718892007-04-27 18:30:00 +00004908 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004909 if (lex->getType()->isArithmeticType() &&
4910 rex->getType()->isArithmeticType()) {
4911 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004912 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004913 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004914
Eli Friedman8e122982008-05-18 18:08:51 +00004915 // Put any potential pointer into PExp
4916 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004917 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004918 std::swap(PExp, IExp);
4919
Steve Naroff6b712a72009-07-14 18:25:06 +00004920 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004921
Eli Friedman8e122982008-05-18 18:08:51 +00004922 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004923 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004924
Chris Lattner12bdebb2009-04-24 23:50:08 +00004925 // Check for arithmetic on pointers to incomplete types.
4926 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004927 if (getLangOptions().CPlusPlus) {
4928 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004929 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004930 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004931 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004932
4933 // GNU extension: arithmetic on pointer to void
4934 Diag(Loc, diag::ext_gnu_void_ptr)
4935 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004936 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004937 if (getLangOptions().CPlusPlus) {
4938 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4939 << lex->getType() << lex->getSourceRange();
4940 return QualType();
4941 }
4942
4943 // GNU extension: arithmetic on pointer to function
4944 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4945 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004946 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004947 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004948 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004949 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004950 PExp->getType()->isObjCObjectPointerType()) &&
4951 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004952 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4953 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004954 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004955 return QualType();
4956 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004957 // Diagnose bad cases where we step over interface counts.
4958 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4959 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4960 << PointeeTy << PExp->getSourceRange();
4961 return QualType();
4962 }
Mike Stump11289f42009-09-09 15:08:12 +00004963
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004964 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004965 QualType LHSTy = Context.isPromotableBitField(lex);
4966 if (LHSTy.isNull()) {
4967 LHSTy = lex->getType();
4968 if (LHSTy->isPromotableIntegerType())
4969 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004970 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004971 *CompLHSTy = LHSTy;
4972 }
Eli Friedman8e122982008-05-18 18:08:51 +00004973 return PExp->getType();
4974 }
4975 }
4976
Chris Lattner326f7572008-11-18 01:30:42 +00004977 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004978}
4979
Chris Lattner2a3569b2008-04-07 05:30:13 +00004980// C99 6.5.6
4981QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004982 SourceLocation Loc, QualType* CompLHSTy) {
4983 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4984 QualType compType = CheckVectorOperands(Loc, lex, rex);
4985 if (CompLHSTy) *CompLHSTy = compType;
4986 return compType;
4987 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004988
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004989 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004990
Chris Lattner4d62f422007-12-09 21:53:25 +00004991 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004992
Chris Lattner4d62f422007-12-09 21:53:25 +00004993 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004994 if (lex->getType()->isArithmeticType()
4995 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004996 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004997 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004998 }
Mike Stump11289f42009-09-09 15:08:12 +00004999
Chris Lattner4d62f422007-12-09 21:53:25 +00005000 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005001 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005002 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005003
Douglas Gregorac1fb652009-03-24 19:52:54 +00005004 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005005
Douglas Gregorac1fb652009-03-24 19:52:54 +00005006 bool ComplainAboutVoid = false;
5007 Expr *ComplainAboutFunc = 0;
5008 if (lpointee->isVoidType()) {
5009 if (getLangOptions().CPlusPlus) {
5010 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5011 << lex->getSourceRange() << rex->getSourceRange();
5012 return QualType();
5013 }
5014
5015 // GNU C extension: arithmetic on pointer to void
5016 ComplainAboutVoid = true;
5017 } else if (lpointee->isFunctionType()) {
5018 if (getLangOptions().CPlusPlus) {
5019 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005020 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005021 return QualType();
5022 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005023
5024 // GNU C extension: arithmetic on pointer to function
5025 ComplainAboutFunc = lex;
5026 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005027 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005028 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005029 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005030 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005031 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005032
Chris Lattner12bdebb2009-04-24 23:50:08 +00005033 // Diagnose bad cases where we step over interface counts.
5034 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5035 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5036 << lpointee << lex->getSourceRange();
5037 return QualType();
5038 }
Mike Stump11289f42009-09-09 15:08:12 +00005039
Chris Lattner4d62f422007-12-09 21:53:25 +00005040 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005041 if (rex->getType()->isIntegerType()) {
5042 if (ComplainAboutVoid)
5043 Diag(Loc, diag::ext_gnu_void_ptr)
5044 << lex->getSourceRange() << rex->getSourceRange();
5045 if (ComplainAboutFunc)
5046 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005047 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005048 << ComplainAboutFunc->getSourceRange();
5049
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005050 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005051 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005052 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005053
Chris Lattner4d62f422007-12-09 21:53:25 +00005054 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005055 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005056 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005057
Douglas Gregorac1fb652009-03-24 19:52:54 +00005058 // RHS must be a completely-type object type.
5059 // Handle the GNU void* extension.
5060 if (rpointee->isVoidType()) {
5061 if (getLangOptions().CPlusPlus) {
5062 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5063 << lex->getSourceRange() << rex->getSourceRange();
5064 return QualType();
5065 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005066
Douglas Gregorac1fb652009-03-24 19:52:54 +00005067 ComplainAboutVoid = true;
5068 } else if (rpointee->isFunctionType()) {
5069 if (getLangOptions().CPlusPlus) {
5070 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005071 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005072 return QualType();
5073 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005074
5075 // GNU extension: arithmetic on pointer to function
5076 if (!ComplainAboutFunc)
5077 ComplainAboutFunc = rex;
5078 } else if (!rpointee->isDependentType() &&
5079 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005080 PDiag(diag::err_typecheck_sub_ptr_object)
5081 << rex->getSourceRange()
5082 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005083 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005084
Eli Friedman168fe152009-05-16 13:54:38 +00005085 if (getLangOptions().CPlusPlus) {
5086 // Pointee types must be the same: C++ [expr.add]
5087 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5088 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5089 << lex->getType() << rex->getType()
5090 << lex->getSourceRange() << rex->getSourceRange();
5091 return QualType();
5092 }
5093 } else {
5094 // Pointee types must be compatible C99 6.5.6p3
5095 if (!Context.typesAreCompatible(
5096 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5097 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5098 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5099 << lex->getType() << rex->getType()
5100 << lex->getSourceRange() << rex->getSourceRange();
5101 return QualType();
5102 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005103 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005104
Douglas Gregorac1fb652009-03-24 19:52:54 +00005105 if (ComplainAboutVoid)
5106 Diag(Loc, diag::ext_gnu_void_ptr)
5107 << lex->getSourceRange() << rex->getSourceRange();
5108 if (ComplainAboutFunc)
5109 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005110 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005111 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005112
5113 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005114 return Context.getPointerDiffType();
5115 }
5116 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005117
Chris Lattner326f7572008-11-18 01:30:42 +00005118 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005119}
5120
Chris Lattner2a3569b2008-04-07 05:30:13 +00005121// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005122QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005123 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005124 // C99 6.5.7p2: Each of the operands shall have integer type.
5125 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005126 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005127
Nate Begemane46ee9a2009-10-25 02:26:48 +00005128 // Vector shifts promote their scalar inputs to vector type.
5129 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5130 return CheckVectorOperands(Loc, lex, rex);
5131
Chris Lattner5c11c412007-12-12 05:47:28 +00005132 // Shifts don't perform usual arithmetic conversions, they just do integer
5133 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005134 QualType LHSTy = Context.isPromotableBitField(lex);
5135 if (LHSTy.isNull()) {
5136 LHSTy = lex->getType();
5137 if (LHSTy->isPromotableIntegerType())
5138 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005139 }
Chris Lattner3c133402007-12-13 07:28:16 +00005140 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005141 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005142
Chris Lattner5c11c412007-12-12 05:47:28 +00005143 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005144
Ryan Flynnf53fab82009-08-07 16:20:20 +00005145 // Sanity-check shift operands
5146 llvm::APSInt Right;
5147 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005148 if (!rex->isValueDependent() &&
5149 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005150 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005151 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5152 else {
5153 llvm::APInt LeftBits(Right.getBitWidth(),
5154 Context.getTypeSize(lex->getType()));
5155 if (Right.uge(LeftBits))
5156 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5157 }
5158 }
5159
Chris Lattner5c11c412007-12-12 05:47:28 +00005160 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005161 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005162}
5163
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005164// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005165QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005166 unsigned OpaqueOpc, bool isRelational) {
5167 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5168
Chris Lattner9a152e22009-12-05 05:40:13 +00005169 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005170 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005171 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005172
John McCall99ce6bf2009-11-06 08:49:08 +00005173 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5174 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005175
Chris Lattnerb620c342007-08-26 01:18:55 +00005176 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005177 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5178 UsualArithmeticConversions(lex, rex);
5179 else {
5180 UsualUnaryConversions(lex);
5181 UsualUnaryConversions(rex);
5182 }
Steve Naroff31090012007-07-16 21:54:35 +00005183 QualType lType = lex->getType();
5184 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005185
Mike Stumpf70bcf72009-05-07 18:43:07 +00005186 if (!lType->isFloatingType()
5187 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005188 // For non-floating point types, check for self-comparisons of the form
5189 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5190 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005191 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005192 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005193 Expr *LHSStripped = lex->IgnoreParens();
5194 Expr *RHSStripped = rex->IgnoreParens();
5195 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5196 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005197 if (DRL->getDecl() == DRR->getDecl() &&
5198 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005199 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005200
Chris Lattner222b8bd2009-03-08 19:39:53 +00005201 if (isa<CastExpr>(LHSStripped))
5202 LHSStripped = LHSStripped->IgnoreParenCasts();
5203 if (isa<CastExpr>(RHSStripped))
5204 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005205
Chris Lattner222b8bd2009-03-08 19:39:53 +00005206 // Warn about comparisons against a string constant (unless the other
5207 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005208 Expr *literalString = 0;
5209 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005210 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005211 !RHSStripped->isNullPointerConstant(Context,
5212 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005213 literalString = lex;
5214 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005215 } else if ((isa<StringLiteral>(RHSStripped) ||
5216 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005217 !LHSStripped->isNullPointerConstant(Context,
5218 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005219 literalString = rex;
5220 literalStringStripped = RHSStripped;
5221 }
5222
5223 if (literalString) {
5224 std::string resultComparison;
5225 switch (Opc) {
5226 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5227 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5228 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5229 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5230 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5231 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5232 default: assert(false && "Invalid comparison operator");
5233 }
5234 Diag(Loc, diag::warn_stringcompare)
5235 << isa<ObjCEncodeExpr>(literalStringStripped)
5236 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005237 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5238 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5239 "strcmp(")
5240 << CodeModificationHint::CreateInsertion(
5241 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005242 resultComparison);
5243 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005244 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005245
Douglas Gregorca63811b2008-11-19 03:25:36 +00005246 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005247 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005248
Chris Lattnerb620c342007-08-26 01:18:55 +00005249 if (isRelational) {
5250 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005251 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005252 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005253 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005254 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005255 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005256
Chris Lattnerb620c342007-08-26 01:18:55 +00005257 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005258 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005259 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005260
Douglas Gregor56751b52009-09-25 04:25:58 +00005261 bool LHSIsNull = lex->isNullPointerConstant(Context,
5262 Expr::NPC_ValueDependentIsNull);
5263 bool RHSIsNull = rex->isNullPointerConstant(Context,
5264 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005265
Chris Lattnerb620c342007-08-26 01:18:55 +00005266 // All of the following pointer related warnings are GCC extensions, except
5267 // when handling null pointer constants. One day, we can consider making them
5268 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005269 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005270 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005271 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005272 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005273 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005274
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005275 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005276 if (LCanPointeeTy == RCanPointeeTy)
5277 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005278 if (!isRelational &&
5279 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5280 // Valid unless comparison between non-null pointer and function pointer
5281 // This is a gcc extension compatibility comparison.
5282 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5283 && !LHSIsNull && !RHSIsNull) {
5284 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5285 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5286 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5287 return ResultTy;
5288 }
5289 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005290 // C++ [expr.rel]p2:
5291 // [...] Pointer conversions (4.10) and qualification
5292 // conversions (4.4) are performed on pointer operands (or on
5293 // a pointer operand and a null pointer constant) to bring
5294 // them to their composite pointer type. [...]
5295 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005296 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005297 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005298 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005299 if (T.isNull()) {
5300 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5301 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5302 return QualType();
5303 }
5304
Eli Friedman06ed2a52009-10-20 08:27:19 +00005305 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5306 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005307 return ResultTy;
5308 }
Eli Friedman16c209612009-08-23 00:27:47 +00005309 // C99 6.5.9p2 and C99 6.5.8p2
5310 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5311 RCanPointeeTy.getUnqualifiedType())) {
5312 // Valid unless a relational comparison of function pointers
5313 if (isRelational && LCanPointeeTy->isFunctionType()) {
5314 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5315 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5316 }
5317 } else if (!isRelational &&
5318 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5319 // Valid unless comparison between non-null pointer and function pointer
5320 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5321 && !LHSIsNull && !RHSIsNull) {
5322 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5323 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5324 }
5325 } else {
5326 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005327 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005328 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005329 }
Eli Friedman16c209612009-08-23 00:27:47 +00005330 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005331 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005332 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005333 }
Mike Stump11289f42009-09-09 15:08:12 +00005334
Sebastian Redl576fd422009-05-10 18:38:11 +00005335 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005336 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005337 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005338 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005339 (lType->isPointerType() ||
5340 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005341 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005342 return ResultTy;
5343 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005344 if (LHSIsNull &&
5345 (rType->isPointerType() ||
5346 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005347 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005348 return ResultTy;
5349 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005350
5351 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005352 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005353 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5354 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005355 // In addition, pointers to members can be compared, or a pointer to
5356 // member and a null pointer constant. Pointer to member conversions
5357 // (4.11) and qualification conversions (4.4) are performed to bring
5358 // them to a common type. If one operand is a null pointer constant,
5359 // the common type is the type of the other operand. Otherwise, the
5360 // common type is a pointer to member type similar (4.4) to the type
5361 // of one of the operands, with a cv-qualification signature (4.4)
5362 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005363 // types.
5364 QualType T = FindCompositePointerType(lex, rex);
5365 if (T.isNull()) {
5366 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5367 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5368 return QualType();
5369 }
Mike Stump11289f42009-09-09 15:08:12 +00005370
Eli Friedman06ed2a52009-10-20 08:27:19 +00005371 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5372 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005373 return ResultTy;
5374 }
Mike Stump11289f42009-09-09 15:08:12 +00005375
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005376 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005377 if (lType->isNullPtrType() && rType->isNullPtrType())
5378 return ResultTy;
5379 }
Mike Stump11289f42009-09-09 15:08:12 +00005380
Steve Naroff081c7422008-09-04 15:10:53 +00005381 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005382 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005383 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5384 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005385
Steve Naroff081c7422008-09-04 15:10:53 +00005386 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005387 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005388 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005389 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005390 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005391 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005392 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005393 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005394 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005395 if (!isRelational
5396 && ((lType->isBlockPointerType() && rType->isPointerType())
5397 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005398 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005399 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005400 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005401 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005402 ->getPointeeType()->isVoidType())))
5403 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5404 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005405 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005406 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005407 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005408 }
Steve Naroff081c7422008-09-04 15:10:53 +00005409
Steve Naroff7cae42b2009-07-10 23:34:53 +00005410 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005411 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005412 const PointerType *LPT = lType->getAs<PointerType>();
5413 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005414 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005415 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005416 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005417 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005418
Steve Naroff753567f2008-11-17 19:49:16 +00005419 if (!LPtrToVoid && !RPtrToVoid &&
5420 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005421 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005422 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005423 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005424 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005425 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005426 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005427 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005428 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005429 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5430 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005431 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005432 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005433 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005434 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005435 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005436 unsigned DiagID = 0;
5437 if (RHSIsNull) {
5438 if (isRelational)
5439 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5440 } else if (isRelational)
5441 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5442 else
5443 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005444
Chris Lattnerd99bd522009-08-23 00:03:44 +00005445 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005446 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005447 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005448 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005449 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005450 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005451 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005452 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005453 unsigned DiagID = 0;
5454 if (LHSIsNull) {
5455 if (isRelational)
5456 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5457 } else if (isRelational)
5458 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5459 else
5460 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005461
Chris Lattnerd99bd522009-08-23 00:03:44 +00005462 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005463 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005464 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005465 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005466 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005467 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005468 }
Steve Naroff4b191572008-09-04 16:56:14 +00005469 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005470 if (!isRelational && RHSIsNull
5471 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005472 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005473 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005474 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005475 if (!isRelational && LHSIsNull
5476 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005477 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005478 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005479 }
Chris Lattner326f7572008-11-18 01:30:42 +00005480 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005481}
5482
Nate Begeman191a6b12008-07-14 18:02:46 +00005483/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005484/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005485/// like a scalar comparison, a vector comparison produces a vector of integer
5486/// types.
5487QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005488 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005489 bool isRelational) {
5490 // Check to make sure we're operating on vectors of the same type and width,
5491 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005492 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005493 if (vType.isNull())
5494 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005495
Nate Begeman191a6b12008-07-14 18:02:46 +00005496 QualType lType = lex->getType();
5497 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005498
Nate Begeman191a6b12008-07-14 18:02:46 +00005499 // For non-floating point types, check for self-comparisons of the form
5500 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5501 // often indicate logic errors in the program.
5502 if (!lType->isFloatingType()) {
5503 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5504 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5505 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005506 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005507 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005508
Nate Begeman191a6b12008-07-14 18:02:46 +00005509 // Check for comparisons of floating point operands using != and ==.
5510 if (!isRelational && lType->isFloatingType()) {
5511 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005512 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005513 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005514
Nate Begeman191a6b12008-07-14 18:02:46 +00005515 // Return the type for the comparison, which is the same as vector type for
5516 // integer vectors, or an integer type of identical size and number of
5517 // elements for floating point vectors.
5518 if (lType->isIntegerType())
5519 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005520
John McCall9dd450b2009-09-21 23:43:11 +00005521 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005522 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005523 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005524 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005525 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005526 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5527
Mike Stump4e1f26a2009-02-19 03:04:26 +00005528 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005529 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005530 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5531}
5532
Steve Naroff218bc2b2007-05-04 21:54:46 +00005533inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005534 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005535 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005536 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005537
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005538 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005539
Steve Naroffdbd9e892007-07-17 00:58:39 +00005540 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005541 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005542 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005543}
5544
Steve Naroff218bc2b2007-05-04 21:54:46 +00005545inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005546 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005547 if (!Context.getLangOptions().CPlusPlus) {
5548 UsualUnaryConversions(lex);
5549 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005550
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005551 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5552 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005553
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005554 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005555 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005556
5557 // C++ [expr.log.and]p1
5558 // C++ [expr.log.or]p1
5559 // The operands are both implicitly converted to type bool (clause 4).
5560 StandardConversionSequence LHS;
5561 if (!IsStandardConversion(lex, Context.BoolTy,
5562 /*InOverloadResolution=*/false, LHS))
5563 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005564
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005565 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005566 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005567 return InvalidOperands(Loc, lex, rex);
5568
5569 StandardConversionSequence RHS;
5570 if (!IsStandardConversion(rex, Context.BoolTy,
5571 /*InOverloadResolution=*/false, RHS))
5572 return InvalidOperands(Loc, lex, rex);
5573
5574 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005575 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005576 return InvalidOperands(Loc, lex, rex);
5577
5578 // C++ [expr.log.and]p2
5579 // C++ [expr.log.or]p2
5580 // The result is a bool.
5581 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005582}
5583
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005584/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5585/// is a read-only property; return true if so. A readonly property expression
5586/// depends on various declarations and thus must be treated specially.
5587///
Mike Stump11289f42009-09-09 15:08:12 +00005588static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005589 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5590 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5591 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5592 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005593 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005594 BaseType->getAsObjCInterfacePointerType())
5595 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5596 if (S.isPropertyReadonly(PDecl, IFace))
5597 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005598 }
5599 }
5600 return false;
5601}
5602
Chris Lattner30bd3272008-11-18 01:22:49 +00005603/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5604/// emit an error and return true. If so, return false.
5605static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005606 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005607 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005608 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005609 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5610 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005611 if (IsLV == Expr::MLV_Valid)
5612 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005613
Chris Lattner30bd3272008-11-18 01:22:49 +00005614 unsigned Diag = 0;
5615 bool NeedType = false;
5616 switch (IsLV) { // C99 6.5.16p2
5617 default: assert(0 && "Unknown result from isModifiableLvalue!");
5618 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005619 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005620 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5621 NeedType = true;
5622 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005623 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005624 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5625 NeedType = true;
5626 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005627 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005628 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5629 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005630 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005631 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5632 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005633 case Expr::MLV_IncompleteType:
5634 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005635 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005636 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5637 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005638 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005639 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5640 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005641 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005642 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5643 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005644 case Expr::MLV_ReadonlyProperty:
5645 Diag = diag::error_readonly_property_assignment;
5646 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005647 case Expr::MLV_NoSetterProperty:
5648 Diag = diag::error_nosetter_property_assignment;
5649 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005650 case Expr::MLV_SubObjCPropertySetting:
5651 Diag = diag::error_no_subobject_property_setting;
5652 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005653 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005654
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005655 SourceRange Assign;
5656 if (Loc != OrigLoc)
5657 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005658 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005659 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005660 else
Mike Stump11289f42009-09-09 15:08:12 +00005661 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005662 return true;
5663}
5664
5665
5666
5667// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005668QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5669 SourceLocation Loc,
5670 QualType CompoundType) {
5671 // Verify that LHS is a modifiable lvalue, and emit error if not.
5672 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005673 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005674
5675 QualType LHSType = LHS->getType();
5676 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005677
Chris Lattner9bad62c2008-01-04 18:04:52 +00005678 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005679 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005680 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005681 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005682 // Special case of NSObject attributes on c-style pointer types.
5683 if (ConvTy == IncompatiblePointer &&
5684 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005685 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005686 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005687 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005688 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005689
Chris Lattnerea714382008-08-21 18:04:13 +00005690 // If the RHS is a unary plus or minus, check to see if they = and + are
5691 // right next to each other. If so, the user may have typo'd "x =+ 4"
5692 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005693 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005694 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5695 RHSCheck = ICE->getSubExpr();
5696 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5697 if ((UO->getOpcode() == UnaryOperator::Plus ||
5698 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005699 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005700 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005701 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5702 // And there is a space or other character before the subexpr of the
5703 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005704 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5705 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005706 Diag(Loc, diag::warn_not_compound_assign)
5707 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5708 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005709 }
Chris Lattnerea714382008-08-21 18:04:13 +00005710 }
5711 } else {
5712 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005713 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005714 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005715
Chris Lattner326f7572008-11-18 01:30:42 +00005716 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005717 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005718 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005719
Steve Naroff98cf3e92007-06-06 18:38:38 +00005720 // C99 6.5.16p3: The type of an assignment expression is the type of the
5721 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005722 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005723 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5724 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005725 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005726 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005727 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005728}
5729
Chris Lattner326f7572008-11-18 01:30:42 +00005730// C99 6.5.17
5731QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005732 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005733 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005734
5735 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5736 // incomplete in C++).
5737
Chris Lattner326f7572008-11-18 01:30:42 +00005738 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005739}
5740
Steve Naroff7a5af782007-07-13 16:58:59 +00005741/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5742/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005743QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5744 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005745 if (Op->isTypeDependent())
5746 return Context.DependentTy;
5747
Chris Lattner6b0cf142008-11-21 07:05:48 +00005748 QualType ResType = Op->getType();
5749 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005750
Sebastian Redle10c2c32008-12-20 09:35:34 +00005751 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5752 // Decrement of bool is not allowed.
5753 if (!isInc) {
5754 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5755 return QualType();
5756 }
5757 // Increment of bool sets it to true, but is deprecated.
5758 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5759 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005760 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005761 } else if (ResType->isAnyPointerType()) {
5762 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005763
Chris Lattner6b0cf142008-11-21 07:05:48 +00005764 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005765 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005766 if (getLangOptions().CPlusPlus) {
5767 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5768 << Op->getSourceRange();
5769 return QualType();
5770 }
5771
5772 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005773 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005774 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005775 if (getLangOptions().CPlusPlus) {
5776 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5777 << Op->getType() << Op->getSourceRange();
5778 return QualType();
5779 }
5780
5781 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005782 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005783 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005784 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005785 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005786 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005787 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005788 // Diagnose bad cases where we step over interface counts.
5789 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5790 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5791 << PointeeTy << Op->getSourceRange();
5792 return QualType();
5793 }
Eli Friedman090addd2010-01-03 00:20:48 +00005794 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005795 // C99 does not support ++/-- on complex types, we allow as an extension.
5796 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005797 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005798 } else {
5799 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005800 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005801 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005802 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005803 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005804 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005805 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005806 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005807 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005808}
5809
Anders Carlsson806700f2008-02-01 07:15:58 +00005810/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005811/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005812/// where the declaration is needed for type checking. We only need to
5813/// handle cases when the expression references a function designator
5814/// or is an lvalue. Here are some examples:
5815/// - &(x) => x
5816/// - &*****f => f for f a function designator.
5817/// - &s.xx => s
5818/// - &s.zz[1].yy -> s, if zz is an array
5819/// - *(x + 1) -> x, if x is an array
5820/// - &"123"[2] -> 0
5821/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005822static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005823 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005824 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005825 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005826 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005827 // If this is an arrow operator, the address is an offset from
5828 // the base's value, so the object the base refers to is
5829 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005830 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005831 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005832 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005833 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005834 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005835 // FIXME: This code shouldn't be necessary! We should catch the implicit
5836 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005837 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5838 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5839 if (ICE->getSubExpr()->getType()->isArrayType())
5840 return getPrimaryDecl(ICE->getSubExpr());
5841 }
5842 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005843 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005844 case Stmt::UnaryOperatorClass: {
5845 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005846
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005847 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005848 case UnaryOperator::Real:
5849 case UnaryOperator::Imag:
5850 case UnaryOperator::Extension:
5851 return getPrimaryDecl(UO->getSubExpr());
5852 default:
5853 return 0;
5854 }
5855 }
Steve Naroff47500512007-04-19 23:00:49 +00005856 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005857 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005858 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005859 // If the result of an implicit cast is an l-value, we care about
5860 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005861 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005862 default:
5863 return 0;
5864 }
5865}
5866
5867/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005868/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005869/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005870/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005871/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005872/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005873/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005874QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005875 // Make sure to ignore parentheses in subsequent checks
5876 op = op->IgnoreParens();
5877
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005878 if (op->isTypeDependent())
5879 return Context.DependentTy;
5880
Steve Naroff826e91a2008-01-13 17:10:08 +00005881 if (getLangOptions().C99) {
5882 // Implement C99-only parts of addressof rules.
5883 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5884 if (uOp->getOpcode() == UnaryOperator::Deref)
5885 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5886 // (assuming the deref expression is valid).
5887 return uOp->getSubExpr()->getType();
5888 }
5889 // Technically, there should be a check for array subscript
5890 // expressions here, but the result of one is always an lvalue anyway.
5891 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005892 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005893 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005894
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005895 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5896 if (lval == Expr::LV_MemberFunction && ME &&
5897 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5898 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5899 // &f where f is a member of the current object, or &o.f, or &p->f
5900 // All these are not allowed, and we need to catch them before the dcl
5901 // branch of the if, below.
5902 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5903 << dcl;
5904 // FIXME: Improve this diagnostic and provide a fixit.
5905
5906 // Now recover by acting as if the function had been accessed qualified.
5907 return Context.getMemberPointerType(op->getType(),
5908 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5909 .getTypePtr());
5910 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00005911 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005912 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005913 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005914 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005915 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5916 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005917 return QualType();
5918 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005919 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005920 // The operand cannot be a bit-field
5921 Diag(OpLoc, diag::err_typecheck_address_of)
5922 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005923 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005924 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5925 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005926 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005927 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005928 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005929 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005930 } else if (isa<ObjCPropertyRefExpr>(op)) {
5931 // cannot take address of a property expression.
5932 Diag(OpLoc, diag::err_typecheck_address_of)
5933 << "property expression" << op->getSourceRange();
5934 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005935 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5936 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005937 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5938 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005939 } else if (isa<UnresolvedLookupExpr>(op)) {
5940 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005941 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005942 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005943 // with the register storage-class specifier.
5944 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005945 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005946 Diag(OpLoc, diag::err_typecheck_address_of)
5947 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005948 return QualType();
5949 }
John McCalld14a8642009-11-21 08:51:07 +00005950 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005951 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005952 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005953 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005954 // Could be a pointer to member, though, if there is an explicit
5955 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005956 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005957 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005958 if (Ctx && Ctx->isRecord()) {
5959 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005960 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005961 diag::err_cannot_form_pointer_to_member_of_reference_type)
5962 << FD->getDeclName() << FD->getType();
5963 return QualType();
5964 }
Mike Stump11289f42009-09-09 15:08:12 +00005965
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005966 return Context.getMemberPointerType(op->getType(),
5967 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005968 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005969 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005970 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005971 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005972 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005973 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5974 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005975 return Context.getMemberPointerType(op->getType(),
5976 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5977 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005978 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005979 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005980
Eli Friedmance7f9002009-05-16 23:27:50 +00005981 if (lval == Expr::LV_IncompleteVoidType) {
5982 // Taking the address of a void variable is technically illegal, but we
5983 // allow it in cases which are otherwise valid.
5984 // Example: "extern void x; void* y = &x;".
5985 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5986 }
5987
Steve Naroff47500512007-04-19 23:00:49 +00005988 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005989 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005990}
5991
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005992QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005993 if (Op->isTypeDependent())
5994 return Context.DependentTy;
5995
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005996 UsualUnaryConversions(Op);
5997 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005998
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005999 // Note that per both C89 and C99, this is always legal, even if ptype is an
6000 // incomplete type or void. It would be possible to warn about dereferencing
6001 // a void pointer, but it's completely well-defined, and such a warning is
6002 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006003 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00006004 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006005
John McCall9dd450b2009-09-21 23:43:11 +00006006 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00006007 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006008
Chris Lattner29e812b2008-11-20 06:06:08 +00006009 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006010 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006011 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00006012}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006013
6014static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6015 tok::TokenKind Kind) {
6016 BinaryOperator::Opcode Opc;
6017 switch (Kind) {
6018 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006019 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6020 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006021 case tok::star: Opc = BinaryOperator::Mul; break;
6022 case tok::slash: Opc = BinaryOperator::Div; break;
6023 case tok::percent: Opc = BinaryOperator::Rem; break;
6024 case tok::plus: Opc = BinaryOperator::Add; break;
6025 case tok::minus: Opc = BinaryOperator::Sub; break;
6026 case tok::lessless: Opc = BinaryOperator::Shl; break;
6027 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6028 case tok::lessequal: Opc = BinaryOperator::LE; break;
6029 case tok::less: Opc = BinaryOperator::LT; break;
6030 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6031 case tok::greater: Opc = BinaryOperator::GT; break;
6032 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6033 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6034 case tok::amp: Opc = BinaryOperator::And; break;
6035 case tok::caret: Opc = BinaryOperator::Xor; break;
6036 case tok::pipe: Opc = BinaryOperator::Or; break;
6037 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6038 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6039 case tok::equal: Opc = BinaryOperator::Assign; break;
6040 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6041 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6042 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6043 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6044 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6045 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6046 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6047 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6048 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6049 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6050 case tok::comma: Opc = BinaryOperator::Comma; break;
6051 }
6052 return Opc;
6053}
6054
Steve Naroff35d85152007-05-07 00:24:15 +00006055static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6056 tok::TokenKind Kind) {
6057 UnaryOperator::Opcode Opc;
6058 switch (Kind) {
6059 default: assert(0 && "Unknown unary op!");
6060 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6061 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6062 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6063 case tok::star: Opc = UnaryOperator::Deref; break;
6064 case tok::plus: Opc = UnaryOperator::Plus; break;
6065 case tok::minus: Opc = UnaryOperator::Minus; break;
6066 case tok::tilde: Opc = UnaryOperator::Not; break;
6067 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006068 case tok::kw___real: Opc = UnaryOperator::Real; break;
6069 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006070 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006071 }
6072 return Opc;
6073}
6074
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006075/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6076/// operator @p Opc at location @c TokLoc. This routine only supports
6077/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006078Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6079 unsigned Op,
6080 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006081 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006082 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006083 // The following two variables are used for compound assignment operators
6084 QualType CompLHSTy; // Type of LHS after promotions for computation
6085 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006086
6087 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006088 case BinaryOperator::Assign:
6089 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6090 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006091 case BinaryOperator::PtrMemD:
6092 case BinaryOperator::PtrMemI:
6093 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6094 Opc == BinaryOperator::PtrMemI);
6095 break;
6096 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006097 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006098 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6099 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006100 break;
6101 case BinaryOperator::Rem:
6102 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6103 break;
6104 case BinaryOperator::Add:
6105 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6106 break;
6107 case BinaryOperator::Sub:
6108 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6109 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006110 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006111 case BinaryOperator::Shr:
6112 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6113 break;
6114 case BinaryOperator::LE:
6115 case BinaryOperator::LT:
6116 case BinaryOperator::GE:
6117 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006118 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006119 break;
6120 case BinaryOperator::EQ:
6121 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006122 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006123 break;
6124 case BinaryOperator::And:
6125 case BinaryOperator::Xor:
6126 case BinaryOperator::Or:
6127 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6128 break;
6129 case BinaryOperator::LAnd:
6130 case BinaryOperator::LOr:
6131 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6132 break;
6133 case BinaryOperator::MulAssign:
6134 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006135 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6136 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006137 CompLHSTy = CompResultTy;
6138 if (!CompResultTy.isNull())
6139 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006140 break;
6141 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006142 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6143 CompLHSTy = CompResultTy;
6144 if (!CompResultTy.isNull())
6145 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006146 break;
6147 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006148 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6149 if (!CompResultTy.isNull())
6150 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006151 break;
6152 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006153 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6154 if (!CompResultTy.isNull())
6155 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006156 break;
6157 case BinaryOperator::ShlAssign:
6158 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006159 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6160 CompLHSTy = CompResultTy;
6161 if (!CompResultTy.isNull())
6162 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006163 break;
6164 case BinaryOperator::AndAssign:
6165 case BinaryOperator::XorAssign:
6166 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006167 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6168 CompLHSTy = CompResultTy;
6169 if (!CompResultTy.isNull())
6170 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006171 break;
6172 case BinaryOperator::Comma:
6173 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6174 break;
6175 }
6176 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006177 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006178 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006179 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6180 else
6181 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006182 CompLHSTy, CompResultTy,
6183 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006184}
6185
Sebastian Redl44615072009-10-27 12:10:02 +00006186/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6187/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006188static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6189 const PartialDiagnostic &PD,
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006190 SourceRange ParenRange,
6191 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6192 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006193 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6194 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6195 // We can't display the parentheses, so just dig the
6196 // warning/error and return.
6197 Self.Diag(Loc, PD);
6198 return;
6199 }
6200
6201 Self.Diag(Loc, PD)
6202 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6203 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006204
6205 if (!SecondPD.getDiagID())
6206 return;
6207
6208 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6209 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6210 // We can't display the parentheses, so just dig the
6211 // warning/error and return.
6212 Self.Diag(Loc, SecondPD);
6213 return;
6214 }
6215
6216 Self.Diag(Loc, SecondPD)
6217 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6218 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006219}
6220
Sebastian Redl44615072009-10-27 12:10:02 +00006221/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6222/// operators are mixed in a way that suggests that the programmer forgot that
6223/// comparison operators have higher precedence. The most typical example of
6224/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006225static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6226 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006227 typedef BinaryOperator BinOp;
6228 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6229 rhsopc = static_cast<BinOp::Opcode>(-1);
6230 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006231 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006232 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006233 rhsopc = BO->getOpcode();
6234
6235 // Subs are not binary operators.
6236 if (lhsopc == -1 && rhsopc == -1)
6237 return;
6238
6239 // Bitwise operations are sometimes used as eager logical ops.
6240 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006241 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6242 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006243 return;
6244
Sebastian Redl44615072009-10-27 12:10:02 +00006245 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006246 SuggestParentheses(Self, OpLoc,
6247 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006248 << SourceRange(lhs->getLocStart(), OpLoc)
6249 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006250 lhs->getSourceRange(),
6251 PDiag(diag::note_precedence_bitwise_first)
6252 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006253 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6254 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006255 SuggestParentheses(Self, OpLoc,
6256 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006257 << SourceRange(OpLoc, rhs->getLocEnd())
6258 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006259 rhs->getSourceRange(),
6260 PDiag(diag::note_precedence_bitwise_first)
6261 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006262 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006263}
6264
6265/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6266/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6267/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6268static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6269 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006270 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006271 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6272}
6273
Steve Naroff218bc2b2007-05-04 21:54:46 +00006274// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006275Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6276 tok::TokenKind Kind,
6277 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006278 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006279 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006280
Steve Naroff83895f72007-09-16 03:34:24 +00006281 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6282 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006283
Sebastian Redl43028242009-10-26 15:24:15 +00006284 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6285 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6286
Douglas Gregor5287f092009-11-05 00:51:44 +00006287 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6288}
6289
6290Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6291 BinaryOperator::Opcode Opc,
6292 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006293 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006294 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006295 rhs->getType()->isOverloadableType())) {
6296 // Find all of the overloaded operators visible from this
6297 // point. We perform both an operator-name lookup from the local
6298 // scope and an argument-dependent lookup based on the types of
6299 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006300 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006301 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6302 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006303 if (S)
6304 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6305 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006306 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006307 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006308 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006309 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006310 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006311
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006312 // Build the (potentially-overloaded, potentially-dependent)
6313 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006314 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006315 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006316
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006317 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006318 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006319}
6320
Douglas Gregor084d8552009-03-13 23:49:33 +00006321Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006322 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006323 ExprArg InputArg) {
6324 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006325
Mike Stump87c57ac2009-05-16 07:39:55 +00006326 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006327 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006328 QualType resultType;
6329 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006330 case UnaryOperator::OffsetOf:
6331 assert(false && "Invalid unary operator");
6332 break;
6333
Steve Naroff35d85152007-05-07 00:24:15 +00006334 case UnaryOperator::PreInc:
6335 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006336 case UnaryOperator::PostInc:
6337 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006338 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006339 Opc == UnaryOperator::PreInc ||
6340 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006341 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006342 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006343 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006344 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006345 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006346 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006347 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006348 break;
6349 case UnaryOperator::Plus:
6350 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006351 UsualUnaryConversions(Input);
6352 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006353 if (resultType->isDependentType())
6354 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006355 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6356 break;
6357 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6358 resultType->isEnumeralType())
6359 break;
6360 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6361 Opc == UnaryOperator::Plus &&
6362 resultType->isPointerType())
6363 break;
6364
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006365 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6366 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006367 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006368 UsualUnaryConversions(Input);
6369 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006370 if (resultType->isDependentType())
6371 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006372 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6373 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6374 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006375 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006376 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006377 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006378 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6379 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006380 break;
6381 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006382 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006383 DefaultFunctionArrayConversion(Input);
6384 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006385 if (resultType->isDependentType())
6386 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006387 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006388 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6389 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006390 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006391 // In C++, it's bool. C++ 5.3.1p8
6392 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006393 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006394 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006395 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006396 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006397 break;
Chris Lattner86554282007-06-08 22:32:33 +00006398 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006399 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006400 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006401 }
6402 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006403 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006404
6405 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006406 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006407}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006408
Douglas Gregor5287f092009-11-05 00:51:44 +00006409Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6410 UnaryOperator::Opcode Opc,
6411 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006412 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006413 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6414 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006415 // Find all of the overloaded operators visible from this
6416 // point. We perform both an operator-name lookup from the local
6417 // scope and an argument-dependent lookup based on the types of
6418 // the arguments.
6419 FunctionSet Functions;
6420 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6421 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006422 if (S)
6423 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6424 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006425 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006426 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006427 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006428 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006429
Douglas Gregor084d8552009-03-13 23:49:33 +00006430 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6431 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006432
Douglas Gregor084d8552009-03-13 23:49:33 +00006433 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6434}
6435
Douglas Gregor5287f092009-11-05 00:51:44 +00006436// Unary Operators. 'Tok' is the token for the operator.
6437Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6438 tok::TokenKind Op, ExprArg input) {
6439 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6440}
6441
Steve Naroff66356bd2007-09-16 14:56:35 +00006442/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006443Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6444 SourceLocation LabLoc,
6445 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006446 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006447 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006448
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006449 // If we haven't seen this label yet, create a forward reference. It
6450 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006451 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006452 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006453
Chris Lattnereefa10e2007-05-28 06:56:27 +00006454 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006455 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6456 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006457}
6458
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006459Sema::OwningExprResult
6460Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6461 SourceLocation RPLoc) { // "({..})"
6462 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006463 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6464 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6465
Eli Friedman52cc0162009-01-24 23:09:00 +00006466 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006467 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006468 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006469
Chris Lattner366727f2007-07-24 16:58:17 +00006470 // FIXME: there are a variety of strange constraints to enforce here, for
6471 // example, it is not possible to goto into a stmt expression apparently.
6472 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006473
Chris Lattner366727f2007-07-24 16:58:17 +00006474 // If there are sub stmts in the compound stmt, take the type of the last one
6475 // as the type of the stmtexpr.
6476 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006477
Chris Lattner944d3062008-07-26 19:51:01 +00006478 if (!Compound->body_empty()) {
6479 Stmt *LastStmt = Compound->body_back();
6480 // If LastStmt is a label, skip down through into the body.
6481 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6482 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006483
Chris Lattner944d3062008-07-26 19:51:01 +00006484 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006485 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006486 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006487
Eli Friedmanba961a92009-03-23 00:24:07 +00006488 // FIXME: Check that expression type is complete/non-abstract; statement
6489 // expressions are not lvalues.
6490
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006491 substmt.release();
6492 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006493}
Steve Naroff78864672007-08-01 22:05:33 +00006494
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006495Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6496 SourceLocation BuiltinLoc,
6497 SourceLocation TypeLoc,
6498 TypeTy *argty,
6499 OffsetOfComponent *CompPtr,
6500 unsigned NumComponents,
6501 SourceLocation RPLoc) {
6502 // FIXME: This function leaks all expressions in the offset components on
6503 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006504 // FIXME: Preserve type source info.
6505 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006506 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006507
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006508 bool Dependent = ArgTy->isDependentType();
6509
Chris Lattnerf17bd422007-08-30 17:45:32 +00006510 // We must have at least one component that refers to the type, and the first
6511 // one is known to be a field designator. Verify that the ArgTy represents
6512 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006513 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006514 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006515
Eli Friedmanba961a92009-03-23 00:24:07 +00006516 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6517 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006518
Eli Friedman988a16b2009-02-27 06:44:11 +00006519 // Otherwise, create a null pointer as the base, and iteratively process
6520 // the offsetof designators.
6521 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6522 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006523 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006524 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006525
Chris Lattner78502cf2007-08-31 21:49:13 +00006526 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6527 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006528 // FIXME: This diagnostic isn't actually visible because the location is in
6529 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006530 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006531 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6532 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006534 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006535 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006536
John McCall9eff4e62009-11-04 03:03:43 +00006537 if (RequireCompleteType(TypeLoc, Res->getType(),
6538 diag::err_offsetof_incomplete_type))
6539 return ExprError();
6540
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006541 // FIXME: Dependent case loses a lot of information here. And probably
6542 // leaks like a sieve.
6543 for (unsigned i = 0; i != NumComponents; ++i) {
6544 const OffsetOfComponent &OC = CompPtr[i];
6545 if (OC.isBrackets) {
6546 // Offset of an array sub-field. TODO: Should we allow vector elements?
6547 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6548 if (!AT) {
6549 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006550 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6551 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006552 }
6553
6554 // FIXME: C++: Verify that operator[] isn't overloaded.
6555
Eli Friedman988a16b2009-02-27 06:44:11 +00006556 // Promote the array so it looks more like a normal array subscript
6557 // expression.
6558 DefaultFunctionArrayConversion(Res);
6559
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006560 // C99 6.5.2.1p1
6561 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006562 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006563 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006564 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006565 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006566 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006567
6568 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6569 OC.LocEnd);
6570 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006571 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006572
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006573 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006574 if (!RC) {
6575 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006576 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6577 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006578 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006579
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006580 // Get the decl corresponding to this.
6581 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006582 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006583 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6584 DiagRuntimeBehavior(BuiltinLoc,
6585 PDiag(diag::warn_offsetof_non_pod_type)
6586 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6587 << Res->getType()))
6588 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006589 }
Mike Stump11289f42009-09-09 15:08:12 +00006590
John McCall27b18f82009-11-17 02:14:36 +00006591 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6592 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006593
John McCall67c00872009-12-02 08:25:40 +00006594 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006595 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006596 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006597 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6598 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006599
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006600 // FIXME: C++: Verify that MemberDecl isn't a static field.
6601 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006602 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006603 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006604 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006605 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006606 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006607 // MemberDecl->getType() doesn't get the right qualifiers, but it
6608 // doesn't matter here.
6609 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6610 MemberDecl->getType().getNonReferenceType());
6611 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006612 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006613 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006614
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006615 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6616 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006617}
6618
6619
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006620Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6621 TypeTy *arg1,TypeTy *arg2,
6622 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006623 // FIXME: Preserve type source info.
6624 QualType argT1 = GetTypeFromParser(arg1);
6625 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006626
Steve Naroff78864672007-08-01 22:05:33 +00006627 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006628
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006629 if (getLangOptions().CPlusPlus) {
6630 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6631 << SourceRange(BuiltinLoc, RPLoc);
6632 return ExprError();
6633 }
6634
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006635 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6636 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006637}
6638
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006639Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6640 ExprArg cond,
6641 ExprArg expr1, ExprArg expr2,
6642 SourceLocation RPLoc) {
6643 Expr *CondExpr = static_cast<Expr*>(cond.get());
6644 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6645 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006646
Steve Naroff9efdabc2007-08-03 21:21:27 +00006647 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6648
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006649 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006650 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006651 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006652 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006653 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006654 } else {
6655 // The conditional expression is required to be a constant expression.
6656 llvm::APSInt condEval(32);
6657 SourceLocation ExpLoc;
6658 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006659 return ExprError(Diag(ExpLoc,
6660 diag::err_typecheck_choose_expr_requires_constant)
6661 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006662
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006663 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6664 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006665 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6666 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006667 }
6668
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006669 cond.release(); expr1.release(); expr2.release();
6670 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006671 resType, RPLoc,
6672 resType->isDependentType(),
6673 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006674}
6675
Steve Naroffc540d662008-09-03 18:15:37 +00006676//===----------------------------------------------------------------------===//
6677// Clang Extensions.
6678//===----------------------------------------------------------------------===//
6679
6680/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006681void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006682 // Analyze block parameters.
6683 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006684
Steve Naroffc540d662008-09-03 18:15:37 +00006685 // Add BSI to CurBlock.
6686 BSI->PrevBlockInfo = CurBlock;
6687 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006688
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006689 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006690 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006691 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006692 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006693 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6694 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006695
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006696 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006697 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006698 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006699}
6700
Mike Stump82f071f2009-02-04 22:31:32 +00006701void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006702 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006703
6704 if (ParamInfo.getNumTypeObjects() == 0
6705 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006706 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006707 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6708
Mike Stumpd456c482009-04-28 01:10:27 +00006709 if (T->isArrayType()) {
6710 Diag(ParamInfo.getSourceRange().getBegin(),
6711 diag::err_block_returns_array);
6712 return;
6713 }
6714
Mike Stump82f071f2009-02-04 22:31:32 +00006715 // The parameter list is optional, if there was none, assume ().
6716 if (!T->isFunctionType())
6717 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6718
6719 CurBlock->hasPrototype = true;
6720 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006721 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006722 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006723 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006724 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006725 // FIXME: remove the attribute.
6726 }
John McCall9dd450b2009-09-21 23:43:11 +00006727 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006728
Chris Lattner6de05082009-04-11 19:27:54 +00006729 // Do not allow returning a objc interface by-value.
6730 if (RetTy->isObjCInterfaceType()) {
6731 Diag(ParamInfo.getSourceRange().getBegin(),
6732 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6733 return;
6734 }
Mike Stump82f071f2009-02-04 22:31:32 +00006735 return;
6736 }
6737
Steve Naroffc540d662008-09-03 18:15:37 +00006738 // Analyze arguments to block.
6739 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6740 "Not a function declarator!");
6741 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006742
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006743 CurBlock->hasPrototype = FTI.hasPrototype;
6744 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006745
Steve Naroffc540d662008-09-03 18:15:37 +00006746 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6747 // no arguments, not a function that takes a single void argument.
6748 if (FTI.hasPrototype &&
6749 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006750 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6751 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006752 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006753 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006754 } else if (FTI.hasPrototype) {
6755 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006756 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006757 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006758 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006759 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006760 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006761 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006762 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006763 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6764 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6765 // If this has an identifier, add it to the scope stack.
6766 if ((*AI)->getIdentifier())
6767 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006768
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006769 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006770 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006771 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006772 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006773 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006774 // FIXME: remove the attribute.
6775 }
Mike Stump11289f42009-09-09 15:08:12 +00006776
Chris Lattner6de05082009-04-11 19:27:54 +00006777 // Analyze the return type.
6778 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006779 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006780
Chris Lattner6de05082009-04-11 19:27:54 +00006781 // Do not allow returning a objc interface by-value.
6782 if (RetTy->isObjCInterfaceType()) {
6783 Diag(ParamInfo.getSourceRange().getBegin(),
6784 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6785 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006786 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006787}
6788
6789/// ActOnBlockError - If there is an error parsing a block, this callback
6790/// is invoked to pop the information about the block from the action impl.
6791void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6792 // Ensure that CurBlock is deleted.
6793 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006794
Chris Lattner45542ea2009-04-19 05:28:12 +00006795 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6796
Steve Naroffc540d662008-09-03 18:15:37 +00006797 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006798 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006799 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006800 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006801}
6802
6803/// ActOnBlockStmtExpr - This is called when the body of a block statement
6804/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006805Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6806 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006807 // If blocks are disabled, emit an error.
6808 if (!LangOpts.Blocks)
6809 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006810
Steve Naroffc540d662008-09-03 18:15:37 +00006811 // Ensure that CurBlock is deleted.
6812 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006813
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006814 PopDeclContext();
6815
Steve Naroffc540d662008-09-03 18:15:37 +00006816 // Pop off CurBlock, handle nested blocks.
6817 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006818
Steve Naroffc540d662008-09-03 18:15:37 +00006819 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006820 if (!BSI->ReturnType.isNull())
6821 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006822
Steve Naroffc540d662008-09-03 18:15:37 +00006823 llvm::SmallVector<QualType, 8> ArgTypes;
6824 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6825 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006826
Mike Stump3bf1ab42009-07-28 22:04:01 +00006827 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006828 QualType BlockTy;
6829 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006830 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6831 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006832 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006833 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006834 BSI->isVariadic, 0, false, false, 0, 0,
6835 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006836
Eli Friedmanba961a92009-03-23 00:24:07 +00006837 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006838 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006839 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006840
Chris Lattner45542ea2009-04-19 05:28:12 +00006841 // If needed, diagnose invalid gotos and switches in the block.
6842 if (CurFunctionNeedsScopeChecking)
6843 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6844 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006845
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006846 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006847 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006848 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6849 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006850}
6851
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006852Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6853 ExprArg expr, TypeTy *type,
6854 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006855 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006856 Expr *E = static_cast<Expr*>(expr.get());
6857 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006858
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006859 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006860
6861 // Get the va_list type
6862 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006863 if (VaListType->isArrayType()) {
6864 // Deal with implicit array decay; for example, on x86-64,
6865 // va_list is an array, but it's supposed to decay to
6866 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006867 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006868 // Make sure the input expression also decays appropriately.
6869 UsualUnaryConversions(E);
6870 } else {
6871 // Otherwise, the va_list argument must be an l-value because
6872 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006873 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006874 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006875 return ExprError();
6876 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006877
Douglas Gregorad3150c2009-05-19 23:10:31 +00006878 if (!E->isTypeDependent() &&
6879 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006880 return ExprError(Diag(E->getLocStart(),
6881 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006882 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006883 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006884
Eli Friedmanba961a92009-03-23 00:24:07 +00006885 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006886 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006887
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006888 expr.release();
6889 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6890 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006891}
6892
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006893Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006894 // The type of __null will be int or long, depending on the size of
6895 // pointers on the target.
6896 QualType Ty;
6897 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6898 Ty = Context.IntTy;
6899 else
6900 Ty = Context.LongTy;
6901
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006902 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006903}
6904
Anders Carlssonace5d072009-11-10 04:46:30 +00006905static void
6906MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6907 QualType DstType,
6908 Expr *SrcExpr,
6909 CodeModificationHint &Hint) {
6910 if (!SemaRef.getLangOptions().ObjC1)
6911 return;
6912
6913 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6914 if (!PT)
6915 return;
6916
6917 // Check if the destination is of type 'id'.
6918 if (!PT->isObjCIdType()) {
6919 // Check if the destination is the 'NSString' interface.
6920 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6921 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6922 return;
6923 }
6924
6925 // Strip off any parens and casts.
6926 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6927 if (!SL || SL->isWide())
6928 return;
6929
6930 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6931}
6932
Chris Lattner9bad62c2008-01-04 18:04:52 +00006933bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6934 SourceLocation Loc,
6935 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006936 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00006937 // Decode the result (notice that AST's are still created for extensions).
6938 bool isInvalid = false;
6939 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006940 CodeModificationHint Hint;
6941
Chris Lattner9bad62c2008-01-04 18:04:52 +00006942 switch (ConvTy) {
6943 default: assert(0 && "Unknown conversion type");
6944 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006945 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006946 DiagKind = diag::ext_typecheck_convert_pointer_int;
6947 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006948 case IntToPointer:
6949 DiagKind = diag::ext_typecheck_convert_int_pointer;
6950 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006951 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006952 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006953 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6954 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006955 case IncompatiblePointerSign:
6956 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6957 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006958 case FunctionVoidPointer:
6959 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6960 break;
6961 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006962 // If the qualifiers lost were because we were applying the
6963 // (deprecated) C++ conversion from a string literal to a char*
6964 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6965 // Ideally, this check would be performed in
6966 // CheckPointerTypesForAssignment. However, that would require a
6967 // bit of refactoring (so that the second argument is an
6968 // expression, rather than a type), which should be done as part
6969 // of a larger effort to fix CheckPointerTypesForAssignment for
6970 // C++ semantics.
6971 if (getLangOptions().CPlusPlus &&
6972 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6973 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006974 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6975 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006976 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006977 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006978 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006979 case IntToBlockPointer:
6980 DiagKind = diag::err_int_to_block_pointer;
6981 break;
6982 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006983 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006984 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006985 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006986 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006987 // it can give a more specific diagnostic.
6988 DiagKind = diag::warn_incompatible_qualified_id;
6989 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006990 case IncompatibleVectors:
6991 DiagKind = diag::warn_incompatible_vectors;
6992 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006993 case Incompatible:
6994 DiagKind = diag::err_typecheck_convert_incompatible;
6995 isInvalid = true;
6996 break;
6997 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006998
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006999 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007000 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007001 return isInvalid;
7002}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007003
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007004bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007005 llvm::APSInt ICEResult;
7006 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7007 if (Result)
7008 *Result = ICEResult;
7009 return false;
7010 }
7011
Anders Carlssone54e8a12008-11-30 19:50:32 +00007012 Expr::EvalResult EvalResult;
7013
Mike Stump4e1f26a2009-02-19 03:04:26 +00007014 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007015 EvalResult.HasSideEffects) {
7016 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7017
7018 if (EvalResult.Diag) {
7019 // We only show the note if it's not the usual "invalid subexpression"
7020 // or if it's actually in a subexpression.
7021 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7022 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7023 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7024 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007025
Anders Carlssone54e8a12008-11-30 19:50:32 +00007026 return true;
7027 }
7028
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007029 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7030 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007031
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007032 if (EvalResult.Diag &&
7033 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7034 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007035
Anders Carlssone54e8a12008-11-30 19:50:32 +00007036 if (Result)
7037 *Result = EvalResult.Val.getInt();
7038 return false;
7039}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007040
Douglas Gregorff790f12009-11-26 00:44:06 +00007041void
Mike Stump11289f42009-09-09 15:08:12 +00007042Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007043 ExprEvalContexts.push_back(
7044 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007045}
7046
Mike Stump11289f42009-09-09 15:08:12 +00007047void
Douglas Gregorff790f12009-11-26 00:44:06 +00007048Sema::PopExpressionEvaluationContext() {
7049 // Pop the current expression evaluation context off the stack.
7050 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7051 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007052
Douglas Gregorfab31f42009-12-12 07:57:52 +00007053 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7054 if (Rec.PotentiallyReferenced) {
7055 // Mark any remaining declarations in the current position of the stack
7056 // as "referenced". If they were not meant to be referenced, semantic
7057 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7058 for (PotentiallyReferencedDecls::iterator
7059 I = Rec.PotentiallyReferenced->begin(),
7060 IEnd = Rec.PotentiallyReferenced->end();
7061 I != IEnd; ++I)
7062 MarkDeclarationReferenced(I->first, I->second);
7063 }
7064
7065 if (Rec.PotentiallyDiagnosed) {
7066 // Emit any pending diagnostics.
7067 for (PotentiallyEmittedDiagnostics::iterator
7068 I = Rec.PotentiallyDiagnosed->begin(),
7069 IEnd = Rec.PotentiallyDiagnosed->end();
7070 I != IEnd; ++I)
7071 Diag(I->first, I->second);
7072 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007073 }
7074
7075 // When are coming out of an unevaluated context, clear out any
7076 // temporaries that we may have created as part of the evaluation of
7077 // the expression in that context: they aren't relevant because they
7078 // will never be constructed.
7079 if (Rec.Context == Unevaluated &&
7080 ExprTemporaries.size() > Rec.NumTemporaries)
7081 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7082 ExprTemporaries.end());
7083
7084 // Destroy the popped expression evaluation record.
7085 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007086}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007087
7088/// \brief Note that the given declaration was referenced in the source code.
7089///
7090/// This routine should be invoke whenever a given declaration is referenced
7091/// in the source code, and where that reference occurred. If this declaration
7092/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7093/// C99 6.9p3), then the declaration will be marked as used.
7094///
7095/// \param Loc the location where the declaration was referenced.
7096///
7097/// \param D the declaration that has been referenced by the source code.
7098void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7099 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007100
Douglas Gregor77b50e12009-06-22 23:06:13 +00007101 if (D->isUsed())
7102 return;
Mike Stump11289f42009-09-09 15:08:12 +00007103
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007104 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7105 // template or not. The reason for this is that unevaluated expressions
7106 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7107 // -Wunused-parameters)
7108 if (isa<ParmVarDecl>(D) ||
7109 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007110 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007111
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007112 // Do not mark anything as "used" within a dependent context; wait for
7113 // an instantiation.
7114 if (CurContext->isDependentContext())
7115 return;
Mike Stump11289f42009-09-09 15:08:12 +00007116
Douglas Gregorff790f12009-11-26 00:44:06 +00007117 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007118 case Unevaluated:
7119 // We are in an expression that is not potentially evaluated; do nothing.
7120 return;
Mike Stump11289f42009-09-09 15:08:12 +00007121
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007122 case PotentiallyEvaluated:
7123 // We are in a potentially-evaluated expression, so this declaration is
7124 // "used"; handle this below.
7125 break;
Mike Stump11289f42009-09-09 15:08:12 +00007126
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007127 case PotentiallyPotentiallyEvaluated:
7128 // We are in an expression that may be potentially evaluated; queue this
7129 // declaration reference until we know whether the expression is
7130 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007131 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007132 return;
7133 }
Mike Stump11289f42009-09-09 15:08:12 +00007134
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007135 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007136 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007137 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007138 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7139 if (!Constructor->isUsed())
7140 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007141 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007142 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007143 if (!Constructor->isUsed())
7144 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7145 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007146
7147 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007148 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7149 if (Destructor->isImplicit() && !Destructor->isUsed())
7150 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007151
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007152 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7153 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7154 MethodDecl->getOverloadedOperator() == OO_Equal) {
7155 if (!MethodDecl->isUsed())
7156 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7157 }
7158 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007159 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007160 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007161 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007162 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007163 bool AlreadyInstantiated = false;
7164 if (FunctionTemplateSpecializationInfo *SpecInfo
7165 = Function->getTemplateSpecializationInfo()) {
7166 if (SpecInfo->getPointOfInstantiation().isInvalid())
7167 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007168 else if (SpecInfo->getTemplateSpecializationKind()
7169 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007170 AlreadyInstantiated = true;
7171 } else if (MemberSpecializationInfo *MSInfo
7172 = Function->getMemberSpecializationInfo()) {
7173 if (MSInfo->getPointOfInstantiation().isInvalid())
7174 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007175 else if (MSInfo->getTemplateSpecializationKind()
7176 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007177 AlreadyInstantiated = true;
7178 }
7179
7180 if (!AlreadyInstantiated)
7181 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7182 }
7183
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007184 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007185 Function->setUsed(true);
7186 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007187 }
Mike Stump11289f42009-09-09 15:08:12 +00007188
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007189 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007190 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007191 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007192 Var->getInstantiatedFromStaticDataMember()) {
7193 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7194 assert(MSInfo && "Missing member specialization information?");
7195 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7196 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7197 MSInfo->setPointOfInstantiation(Loc);
7198 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7199 }
7200 }
Mike Stump11289f42009-09-09 15:08:12 +00007201
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007202 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007203
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007204 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007205 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007206 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007207}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007208
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007209/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7210/// of the program being compiled.
7211///
7212/// This routine emits the given diagnostic when the code currently being
7213/// type-checked is "potentially evaluated", meaning that there is a
7214/// possibility that the code will actually be executable. Code in sizeof()
7215/// expressions, code used only during overload resolution, etc., are not
7216/// potentially evaluated. This routine will suppress such diagnostics or,
7217/// in the absolutely nutty case of potentially potentially evaluated
7218/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7219/// later.
7220///
7221/// This routine should be used for all diagnostics that describe the run-time
7222/// behavior of a program, such as passing a non-POD value through an ellipsis.
7223/// Failure to do so will likely result in spurious diagnostics or failures
7224/// during overload resolution or within sizeof/alignof/typeof/typeid.
7225bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7226 const PartialDiagnostic &PD) {
7227 switch (ExprEvalContexts.back().Context ) {
7228 case Unevaluated:
7229 // The argument will never be evaluated, so don't complain.
7230 break;
7231
7232 case PotentiallyEvaluated:
7233 Diag(Loc, PD);
7234 return true;
7235
7236 case PotentiallyPotentiallyEvaluated:
7237 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7238 break;
7239 }
7240
7241 return false;
7242}
7243
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007244bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7245 CallExpr *CE, FunctionDecl *FD) {
7246 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7247 return false;
7248
7249 PartialDiagnostic Note =
7250 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7251 << FD->getDeclName() : PDiag();
7252 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7253
7254 if (RequireCompleteType(Loc, ReturnType,
7255 FD ?
7256 PDiag(diag::err_call_function_incomplete_return)
7257 << CE->getSourceRange() << FD->getDeclName() :
7258 PDiag(diag::err_call_incomplete_return)
7259 << CE->getSourceRange(),
7260 std::make_pair(NoteLoc, Note)))
7261 return true;
7262
7263 return false;
7264}
7265
John McCalld5707ab2009-10-12 21:59:07 +00007266// Diagnose the common s/=/==/ typo. Note that adding parentheses
7267// will prevent this condition from triggering, which is what we want.
7268void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7269 SourceLocation Loc;
7270
John McCall0506e4a2009-11-11 02:41:58 +00007271 unsigned diagnostic = diag::warn_condition_is_assignment;
7272
John McCalld5707ab2009-10-12 21:59:07 +00007273 if (isa<BinaryOperator>(E)) {
7274 BinaryOperator *Op = cast<BinaryOperator>(E);
7275 if (Op->getOpcode() != BinaryOperator::Assign)
7276 return;
7277
John McCallb0e419e2009-11-12 00:06:05 +00007278 // Greylist some idioms by putting them into a warning subcategory.
7279 if (ObjCMessageExpr *ME
7280 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7281 Selector Sel = ME->getSelector();
7282
John McCallb0e419e2009-11-12 00:06:05 +00007283 // self = [<foo> init...]
7284 if (isSelfExpr(Op->getLHS())
7285 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7286 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7287
7288 // <foo> = [<bar> nextObject]
7289 else if (Sel.isUnarySelector() &&
7290 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7291 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7292 }
John McCall0506e4a2009-11-11 02:41:58 +00007293
John McCalld5707ab2009-10-12 21:59:07 +00007294 Loc = Op->getOperatorLoc();
7295 } else if (isa<CXXOperatorCallExpr>(E)) {
7296 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7297 if (Op->getOperator() != OO_Equal)
7298 return;
7299
7300 Loc = Op->getOperatorLoc();
7301 } else {
7302 // Not an assignment.
7303 return;
7304 }
7305
John McCalld5707ab2009-10-12 21:59:07 +00007306 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007307 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007308
John McCall0506e4a2009-11-11 02:41:58 +00007309 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007310 << E->getSourceRange()
7311 << CodeModificationHint::CreateInsertion(Open, "(")
7312 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007313 Diag(Loc, diag::note_condition_assign_to_comparison)
7314 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00007315}
7316
7317bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7318 DiagnoseAssignmentAsCondition(E);
7319
7320 if (!E->isTypeDependent()) {
7321 DefaultFunctionArrayConversion(E);
7322
7323 QualType T = E->getType();
7324
7325 if (getLangOptions().CPlusPlus) {
7326 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7327 return true;
7328 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7329 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7330 << T << E->getSourceRange();
7331 return true;
7332 }
7333 }
7334
7335 return false;
7336}