blob: f67a7a6bb9d9dc7cc6569014f16b709d1f439877 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor99a2e602009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000020#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000027#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000028#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000029#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000030#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
David Chisnall0f436562009-08-17 16:35:33 +000033
Douglas Gregor48f3bb92009-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 Lattner52338262009-10-25 22:31:57 +000043/// If IgnoreDeprecated is set to true, this should not want about deprecated
44/// decls.
45///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000046/// \returns true if there was an error (this declaration cannot be
47/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000048///
John McCall54abf7d2009-11-04 02:18:39 +000049bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000050 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000051 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000052 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000053 }
54
Chris Lattnerffb93682009-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 Gregor48f3bb92009-02-18 21:56:37 +000061 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-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 Gregor25d944a2009-02-24 04:26:15 +000068 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000069
Douglas Gregor48f3bb92009-02-18 21:56:37 +000070 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000071}
72
Fariborz Jahanian5b530052009-05-13 18:09:35 +000073/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000074/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-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 Stump1eb44332009-09-09 15:08:12 +000078 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000079 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000080 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000081 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000082 int sentinelPos = attr->getSentinel();
83 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000084
Mike Stump390b4cc2009-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 Jahanian88f1ba02009-05-13 23:20:50 +000087 unsigned int i = 0;
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000101 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000111 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000112 // block or function pointer call.
113 QualType Ty = V->getType();
114 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000115 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000116 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
117 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-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 Stumpac5fc7c2009-08-04 21:02:39 +0000131 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000132 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000133 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000134 return;
135
136 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000137 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000138 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-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 Jahanian236673e2009-05-14 18:00:00 +0000148 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000149 return;
150 }
151 while (i < NumArgs-1) {
152 ++i;
153 ++sentinel;
154 }
155 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000156 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
157 (!sentinelExpr->getType()->isPointerType() ||
158 !sentinelExpr->isNullPointerConstant(Context,
159 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000160 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 }
163 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000164}
165
Douglas Gregor4b2d3f72009-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 Lattnere7a2e912008-07-25 21:10:04 +0000171//===----------------------------------------------------------------------===//
172// Standard Promotions and Conversions
173//===----------------------------------------------------------------------===//
174
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000180 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000181 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000182 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-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 Kyrtzidisc39a3d72008-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 Carlsson112a0a82009-08-07 23:48:20 +0000197 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
198 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000199 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000200}
201
202/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000203/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-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 Stump1eb44332009-09-09 15:08:12 +0000210
Douglas Gregorfc24e442009-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 Friedman04e83572009-08-20 04:21:42 +0000224 QualType PTy = Context.isPromotableBitField(Expr);
225 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000226 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000227 return Expr;
228 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000229 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000230 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000231 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000232 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000233 }
234
Douglas Gregorfc24e442009-05-01 20:41:21 +0000235 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000236 return Expr;
237}
238
Chris Lattner05faf172008-07-25 22:25:12 +0000239/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000240/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-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 Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner05faf172008-07-25 22:25:12 +0000246 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000247 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000248 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000249 return ImpCastExprToType(Expr, Context.DoubleTy,
250 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattner05faf172008-07-25 22:25:12 +0000252 UsualUnaryConversions(Expr);
253}
254
Chris Lattner312531a2009-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 Carlssondce5e2c2009-01-16 16:48:51 +0000260 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Chris Lattner312531a2009-04-12 08:11:20 +0000262 if (Expr->getType()->isObjCInterfaceType()) {
Douglas Gregor75b699a2009-12-12 07:25:49 +0000263 switch (ExprEvalContexts.back().Context ) {
264 case Unevaluated:
265 // The argument will never be evaluated, so don't complain.
266 break;
267
268 case PotentiallyEvaluated:
269 Diag(Expr->getLocStart(),
270 diag::err_cannot_pass_objc_interface_to_vararg)
271 << Expr->getType() << CT;
272 return true;
273
274 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +0000275 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
276 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
277 << Expr->getType() << CT);
Douglas Gregor75b699a2009-12-12 07:25:49 +0000278 break;
279 }
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000280 }
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregor75b699a2009-12-12 07:25:49 +0000282 if (!Expr->getType()->isPODType()) {
283 switch (ExprEvalContexts.back().Context ) {
284 case Unevaluated:
285 // The argument will never be evaluated, so don't complain.
286 break;
287
288 case PotentiallyEvaluated:
289 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
290 << Expr->getType() << CT;
291 break;
292
293 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +0000294 ExprEvalContexts.back().addDiagnostic(Expr->getLocStart(),
295 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
296 << Expr->getType() << CT);
Douglas Gregor75b699a2009-12-12 07:25:49 +0000297 break;
298 }
299 }
Chris Lattner312531a2009-04-12 08:11:20 +0000300
301 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000302}
303
304
Chris Lattnere7a2e912008-07-25 21:10:04 +0000305/// UsualArithmeticConversions - Performs various conversions that are common to
306/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000307/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000308/// responsible for emitting appropriate error diagnostics.
309/// FIXME: verify the conversion rules for "complex int" are consistent with
310/// GCC.
311QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
312 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000313 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000314 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000315
316 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000317
Mike Stump1eb44332009-09-09 15:08:12 +0000318 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000319 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000320 QualType lhs =
321 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000322 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000323 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000324
325 // If both types are identical, no conversion is needed.
326 if (lhs == rhs)
327 return lhs;
328
329 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
330 // The caller can deal with this (e.g. pointer + int).
331 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
332 return lhs;
333
Douglas Gregor2d833e32009-05-02 00:36:19 +0000334 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000335 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000336 if (!LHSBitfieldPromoteTy.isNull())
337 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000338 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000339 if (!RHSBitfieldPromoteTy.isNull())
340 rhs = RHSBitfieldPromoteTy;
341
Eli Friedmana95d7572009-08-19 07:44:53 +0000342 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000343 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000344 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
345 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000346 return destType;
347}
348
Chris Lattnere7a2e912008-07-25 21:10:04 +0000349//===----------------------------------------------------------------------===//
350// Semantic Analysis for various Expression Types
351//===----------------------------------------------------------------------===//
352
353
Steve Narofff69936d2007-09-16 03:34:24 +0000354/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000355/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
356/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
357/// multiple tokens. However, the common case is that StringToks points to one
358/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000359///
360Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000361Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 assert(NumStringToks && "Must have at least one string!");
363
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000364 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000366 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000367
368 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
369 for (unsigned i = 0; i != NumStringToks; ++i)
370 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000371
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000372 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000373 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000374 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000375
376 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
377 if (getLangOptions().CPlusPlus)
378 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000379
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000380 // Get an array type for the string, according to C99 6.4.5. This includes
381 // the nul terminator character as well as the string length for pascal
382 // strings.
383 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000384 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000385 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000388 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000389 Literal.GetStringLength(),
390 Literal.AnyWide, StrTy,
391 &StringTokLocs[0],
392 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000393}
394
Chris Lattner639e2d32008-10-20 05:16:36 +0000395/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
396/// CurBlock to VD should cause it to be snapshotted (as we do for auto
397/// variables defined outside the block) or false if this is not needed (e.g.
398/// for values inside the block or for globals).
399///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000400/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
401/// up-to-date.
402///
Chris Lattner639e2d32008-10-20 05:16:36 +0000403static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
404 ValueDecl *VD) {
405 // If the value is defined inside the block, we couldn't snapshot it even if
406 // we wanted to.
407 if (CurBlock->TheDecl == VD->getDeclContext())
408 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner639e2d32008-10-20 05:16:36 +0000410 // If this is an enum constant or function, it is constant, don't snapshot.
411 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
412 return false;
413
414 // If this is a reference to an extern, static, or global variable, no need to
415 // snapshot it.
416 // FIXME: What about 'const' variables in C++?
417 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000418 if (!Var->hasLocalStorage())
419 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000421 // Blocks that have these can't be constant.
422 CurBlock->hasBlockDeclRefExprs = true;
423
424 // If we have nested blocks, the decl may be declared in an outer block (in
425 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
426 // be defined outside all of the current blocks (in which case the blocks do
427 // all get the bit). Walk the nesting chain.
428 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
429 NextBlock = NextBlock->PrevBlockInfo) {
430 // If we found the defining block for the variable, don't mark the block as
431 // having a reference outside it.
432 if (NextBlock->TheDecl == VD->getDeclContext())
433 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000435 // Otherwise, the DeclRef from the inner block causes the outer one to need
436 // a snapshot as well.
437 NextBlock->hasBlockDeclRefExprs = true;
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner639e2d32008-10-20 05:16:36 +0000440 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000441}
442
Chris Lattner639e2d32008-10-20 05:16:36 +0000443
444
Douglas Gregora2813ce2009-10-23 18:54:35 +0000445/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000446Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000447Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000448 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000449 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
450 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000451 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000452 << D->getDeclName();
453 return ExprError();
454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Anders Carlssone41590d2009-06-24 00:10:43 +0000456 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
457 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
458 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
459 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000461 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000462 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000463 << D->getIdentifier();
464 return ExprError();
465 }
466 }
467 }
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregore0762c92009-06-19 23:52:42 +0000470 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Douglas Gregora2813ce2009-10-23 18:54:35 +0000472 return Owned(DeclRefExpr::Create(Context,
473 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
474 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000475 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000476}
477
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000478/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
479/// variable corresponding to the anonymous union or struct whose type
480/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000481static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
482 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000483 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000484 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Mike Stump390b4cc2009-05-16 07:39:55 +0000486 // FIXME: Once Decls are directly linked together, this will be an O(1)
487 // operation rather than a slow walk through DeclContext's vector (which
488 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000489 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000490 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000491 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000492 D != DEnd; ++D) {
493 if (*D == Record) {
494 // The object for the anonymous struct/union directly
495 // follows its type in the list of declarations.
496 ++D;
497 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000498 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000499 return *D;
500 }
501 }
502
503 assert(false && "Missing object for anonymous record");
504 return 0;
505}
506
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000507/// \brief Given a field that represents a member of an anonymous
508/// struct/union, build the path from that field's context to the
509/// actual member.
510///
511/// Construct the sequence of field member references we'll have to
512/// perform to get to the field in the anonymous union/struct. The
513/// list of members is built from the field outward, so traverse it
514/// backwards to go from an object in the current context to the field
515/// we found.
516///
517/// \returns The variable from which the field access should begin,
518/// for an anonymous struct/union that is not a member of another
519/// class. Otherwise, returns NULL.
520VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
521 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000522 assert(Field->getDeclContext()->isRecord() &&
523 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
524 && "Field must be stored inside an anonymous struct or union");
525
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 VarDecl *BaseObject = 0;
528 DeclContext *Ctx = Field->getDeclContext();
529 do {
530 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000531 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000532 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000533 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000534 else {
535 BaseObject = cast<VarDecl>(AnonObject);
536 break;
537 }
538 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000539 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000540 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000541
542 return BaseObject;
543}
544
545Sema::OwningExprResult
546Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
547 FieldDecl *Field,
548 Expr *BaseObjectExpr,
549 SourceLocation OpLoc) {
550 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000551 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000552 AnonFields);
553
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 // Build the expression that refers to the base object, from
555 // which we will build a sequence of member references to each
556 // of the anonymous union objects and, eventually, the field we
557 // found via name lookup.
558 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000559 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000560 if (BaseObject) {
561 // BaseObject is an anonymous struct/union variable (and is,
562 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000563 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000564 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000567 BaseQuals
568 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 } else if (BaseObjectExpr) {
570 // The caller provided the base object expression. Determine
571 // whether its a pointer and whether it adds any qualifiers to the
572 // anonymous struct/union fields we're looking into.
573 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000574 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 BaseObjectIsPointer = true;
576 ObjectType = ObjectPtr->getPointeeType();
577 }
John McCall0953e762009-09-24 19:53:00 +0000578 BaseQuals
579 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 } else {
581 // We've found a member of an anonymous struct/union that is
582 // inside a non-anonymous struct/union, so in a well-formed
583 // program our base object expression is "this".
584 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
585 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000586 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587 = Context.getTagDeclType(
588 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
589 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000590 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000591 == Context.getCanonicalType(ThisType)) ||
592 IsDerivedFrom(ThisType, AnonFieldType)) {
593 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000594 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000595 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000596 BaseObjectIsPointer = true;
597 }
598 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000599 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
600 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000601 }
John McCall0953e762009-09-24 19:53:00 +0000602 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000603 }
604
Mike Stump1eb44332009-09-09 15:08:12 +0000605 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000606 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
607 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000608 }
609
610 // Build the implicit member references to the field of the
611 // anonymous struct/union.
612 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000613 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000614 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
615 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
616 FI != FIEnd; ++FI) {
617 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000618 Qualifiers MemberTypeQuals =
619 Context.getCanonicalType(MemberType).getQualifiers();
620
621 // CVR attributes from the base are picked up by members,
622 // except that 'mutable' members don't pick up 'const'.
623 if ((*FI)->isMutable())
624 ResultQuals.removeConst();
625
626 // GC attributes are never picked up by members.
627 ResultQuals.removeObjCGCAttr();
628
629 // TR 18037 does not allow fields to be declared with address spaces.
630 assert(!MemberTypeQuals.hasAddressSpace());
631
632 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
633 if (NewQuals != MemberTypeQuals)
634 MemberType = Context.getQualifiedType(MemberType, NewQuals);
635
Douglas Gregore0762c92009-06-19 23:52:42 +0000636 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000637 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000638 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000639 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
640 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000641 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000642 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000643 }
644
Sebastian Redlcd965b92009-01-18 18:53:16 +0000645 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000646}
647
John McCall129e2df2009-11-30 22:42:35 +0000648/// Decomposes the given name into a DeclarationName, its location, and
649/// possibly a list of template arguments.
650///
651/// If this produces template arguments, it is permitted to call
652/// DecomposeTemplateName.
653///
654/// This actually loses a lot of source location information for
655/// non-standard name kinds; we should consider preserving that in
656/// some way.
657static void DecomposeUnqualifiedId(Sema &SemaRef,
658 const UnqualifiedId &Id,
659 TemplateArgumentListInfo &Buffer,
660 DeclarationName &Name,
661 SourceLocation &NameLoc,
662 const TemplateArgumentListInfo *&TemplateArgs) {
663 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
664 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
665 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
666
667 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
668 Id.TemplateId->getTemplateArgs(),
669 Id.TemplateId->NumArgs);
670 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
671 TemplateArgsPtr.release();
672
673 TemplateName TName =
674 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
675
676 Name = SemaRef.Context.getNameForTemplate(TName);
677 NameLoc = Id.TemplateId->TemplateNameLoc;
678 TemplateArgs = &Buffer;
679 } else {
680 Name = SemaRef.GetNameFromUnqualifiedId(Id);
681 NameLoc = Id.StartLocation;
682 TemplateArgs = 0;
683 }
684}
685
686/// Decompose the given template name into a list of lookup results.
687///
688/// The unqualified ID must name a non-dependent template, which can
689/// be more easily tested by checking whether DecomposeUnqualifiedId
690/// found template arguments.
691static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
692 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
693 TemplateName TName =
694 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
695
John McCallf7a1a742009-11-24 19:00:30 +0000696 if (TemplateDecl *TD = TName.getAsTemplateDecl())
697 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000698 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
699 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
700 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000701 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000702
John McCallf7a1a742009-11-24 19:00:30 +0000703 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000704}
705
John McCall129e2df2009-11-30 22:42:35 +0000706static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
707 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
708 E = Record->bases_end(); I != E; ++I) {
709 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
710 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
711 if (!BaseRT) return false;
712
713 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
714 if (!BaseRecord->isDefinition() ||
715 !IsFullyFormedScope(SemaRef, BaseRecord))
716 return false;
717 }
718
719 return true;
720}
721
John McCalle1599ce2009-11-30 23:50:49 +0000722/// Determines whether we can lookup this id-expression now or whether
723/// we have to wait until template instantiation is complete.
724static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000725 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000726
John McCalle1599ce2009-11-30 23:50:49 +0000727 // If the qualifier scope isn't computable, it's definitely dependent.
728 if (!DC) return true;
729
730 // If the qualifier scope doesn't name a record, we can always look into it.
731 if (!isa<CXXRecordDecl>(DC)) return false;
732
733 // We can't look into record types unless they're fully-formed.
734 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
735
John McCallaa81e162009-12-01 22:10:20 +0000736 return false;
737}
John McCalle1599ce2009-11-30 23:50:49 +0000738
John McCallaa81e162009-12-01 22:10:20 +0000739/// Determines if the given class is provably not derived from all of
740/// the prospective base classes.
741static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
742 CXXRecordDecl *Record,
743 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000744 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000745 return false;
746
John McCallb1b42562009-12-01 22:28:41 +0000747 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
748 if (!RD) return false;
749 Record = cast<CXXRecordDecl>(RD);
750
John McCallaa81e162009-12-01 22:10:20 +0000751 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
752 E = Record->bases_end(); I != E; ++I) {
753 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
754 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
755 if (!BaseRT) return false;
756
757 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000758 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
759 return false;
760 }
761
762 return true;
763}
764
John McCall144238e2009-12-02 20:26:00 +0000765/// Determines if this is an instance member of a class.
766static bool IsInstanceMember(NamedDecl *D) {
John McCall3b4294e2009-12-16 12:17:52 +0000767 assert(D->isCXXClassMember() &&
John McCallaa81e162009-12-01 22:10:20 +0000768 "checking whether non-member is instance member");
769
770 if (isa<FieldDecl>(D)) return true;
771
772 if (isa<CXXMethodDecl>(D))
773 return !cast<CXXMethodDecl>(D)->isStatic();
774
775 if (isa<FunctionTemplateDecl>(D)) {
776 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
777 return !cast<CXXMethodDecl>(D)->isStatic();
778 }
779
780 return false;
781}
782
783enum IMAKind {
784 /// The reference is definitely not an instance member access.
785 IMA_Static,
786
787 /// The reference may be an implicit instance member access.
788 IMA_Mixed,
789
790 /// The reference may be to an instance member, but it is invalid if
791 /// so, because the context is not an instance method.
792 IMA_Mixed_StaticContext,
793
794 /// The reference may be to an instance member, but it is invalid if
795 /// so, because the context is from an unrelated class.
796 IMA_Mixed_Unrelated,
797
798 /// The reference is definitely an implicit instance member access.
799 IMA_Instance,
800
801 /// The reference may be to an unresolved using declaration.
802 IMA_Unresolved,
803
804 /// The reference may be to an unresolved using declaration and the
805 /// context is not an instance method.
806 IMA_Unresolved_StaticContext,
807
808 /// The reference is to a member of an anonymous structure in a
809 /// non-class context.
810 IMA_AnonymousMember,
811
812 /// All possible referrents are instance members and the current
813 /// context is not an instance method.
814 IMA_Error_StaticContext,
815
816 /// All possible referrents are instance members of an unrelated
817 /// class.
818 IMA_Error_Unrelated
819};
820
821/// The given lookup names class member(s) and is not being used for
822/// an address-of-member expression. Classify the type of access
823/// according to whether it's possible that this reference names an
824/// instance member. This is best-effort; it is okay to
825/// conservatively answer "yes", in which case some errors will simply
826/// not be caught until template-instantiation.
827static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
828 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000829 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000830
831 bool isStaticContext =
832 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
833 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
834
835 if (R.isUnresolvableResult())
836 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
837
838 // Collect all the declaring classes of instance members we find.
839 bool hasNonInstance = false;
840 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
841 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
842 NamedDecl *D = (*I)->getUnderlyingDecl();
843 if (IsInstanceMember(D)) {
844 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
845
846 // If this is a member of an anonymous record, move out to the
847 // innermost non-anonymous struct or union. If there isn't one,
848 // that's a special case.
849 while (R->isAnonymousStructOrUnion()) {
850 R = dyn_cast<CXXRecordDecl>(R->getParent());
851 if (!R) return IMA_AnonymousMember;
852 }
853 Classes.insert(R->getCanonicalDecl());
854 }
855 else
856 hasNonInstance = true;
857 }
858
859 // If we didn't find any instance members, it can't be an implicit
860 // member reference.
861 if (Classes.empty())
862 return IMA_Static;
863
864 // If the current context is not an instance method, it can't be
865 // an implicit member reference.
866 if (isStaticContext)
867 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
868
869 // If we can prove that the current context is unrelated to all the
870 // declaring classes, it can't be an implicit member reference (in
871 // which case it's an error if any of those members are selected).
872 if (IsProvablyNotDerivedFrom(SemaRef,
873 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
874 Classes))
875 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
876
877 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
878}
879
880/// Diagnose a reference to a field with no object available.
881static void DiagnoseInstanceReference(Sema &SemaRef,
882 const CXXScopeSpec &SS,
883 const LookupResult &R) {
884 SourceLocation Loc = R.getNameLoc();
885 SourceRange Range(Loc);
886 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
887
888 if (R.getAsSingle<FieldDecl>()) {
889 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
890 if (MD->isStatic()) {
891 // "invalid use of member 'x' in static member function"
892 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
893 << Range << R.getLookupName();
894 return;
895 }
896 }
897
898 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
899 << R.getLookupName() << Range;
900 return;
901 }
902
903 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000904}
905
John McCall578b69b2009-12-16 08:11:27 +0000906/// Diagnose an empty lookup.
907///
908/// \return false if new lookup candidates were found
909bool Sema::DiagnoseEmptyLookup(const CXXScopeSpec &SS,
910 LookupResult &R) {
911 DeclarationName Name = R.getLookupName();
912
913 // We don't know how to recover from bad qualified lookups.
914 if (!SS.isEmpty()) {
915 Diag(R.getNameLoc(), diag::err_no_member)
916 << Name << computeDeclContext(SS, false)
917 << SS.getRange();
918 return true;
919 }
920
921 unsigned diagnostic = diag::err_undeclared_var_use;
922 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
923 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
924 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
925 diagnostic = diag::err_undeclared_use;
926
927 // Fake an unqualified lookup. This is useful when (for example)
928 // the original lookup would not have found something because it was
929 // a dependent name.
930 for (DeclContext *DC = CurContext; DC; DC = DC->getParent()) {
931 if (isa<CXXRecordDecl>(DC)) {
932 LookupQualifiedName(R, DC);
933
934 if (!R.empty()) {
935 // Don't give errors about ambiguities in this lookup.
936 R.suppressDiagnostics();
937
938 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
939 bool isInstance = CurMethod &&
940 CurMethod->isInstance() &&
941 DC == CurMethod->getParent();
942
943 // Give a code modification hint to insert 'this->'.
944 // TODO: fixit for inserting 'Base<T>::' in the other cases.
945 // Actually quite difficult!
946 if (isInstance)
947 Diag(R.getNameLoc(), diagnostic) << Name
948 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
949 "this->");
950 else
951 Diag(R.getNameLoc(), diagnostic) << Name;
952
953 // Do we really want to note all of these?
954 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
955 Diag((*I)->getLocation(), diag::note_dependent_var_use);
956
957 // Tell the callee to try to recover.
958 return false;
959 }
960 }
961 }
962
963 // Give up, we can't recover.
964 Diag(R.getNameLoc(), diagnostic) << Name;
965 return true;
966}
967
John McCallf7a1a742009-11-24 19:00:30 +0000968Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
969 const CXXScopeSpec &SS,
970 UnqualifiedId &Id,
971 bool HasTrailingLParen,
972 bool isAddressOfOperand) {
973 assert(!(isAddressOfOperand && HasTrailingLParen) &&
974 "cannot be direct & operand and have a trailing lparen");
975
976 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000977 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000978
John McCall129e2df2009-11-30 22:42:35 +0000979 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000980
981 // Decompose the UnqualifiedId into the following data.
982 DeclarationName Name;
983 SourceLocation NameLoc;
984 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000985 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
986 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000987
Douglas Gregor10c42622008-11-18 15:03:34 +0000988 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000989
John McCallf7a1a742009-11-24 19:00:30 +0000990 // C++ [temp.dep.expr]p3:
991 // An id-expression is type-dependent if it contains:
992 // -- a nested-name-specifier that contains a class-name that
993 // names a dependent type.
994 // Determine whether this is a member of an unknown specialization;
995 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000996 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000997 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000998 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000999 TemplateArgs);
1000 }
John McCallba135432009-11-21 08:51:07 +00001001
John McCallf7a1a742009-11-24 19:00:30 +00001002 // Perform the required lookup.
1003 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1004 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001005 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001006 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001007 } else {
1008 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
John McCallf7a1a742009-11-24 19:00:30 +00001010 // If this reference is in an Objective-C method, then we need to do
1011 // some special Objective-C lookup, too.
1012 if (!SS.isSet() && II && getCurMethodDecl()) {
1013 OwningExprResult E(LookupInObjCMethod(R, S, II));
1014 if (E.isInvalid())
1015 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001016
John McCallf7a1a742009-11-24 19:00:30 +00001017 Expr *Ex = E.takeAs<Expr>();
1018 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001019 }
Chris Lattner8a934232008-03-31 00:36:02 +00001020 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001021
John McCallf7a1a742009-11-24 19:00:30 +00001022 if (R.isAmbiguous())
1023 return ExprError();
1024
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001025 // Determine whether this name might be a candidate for
1026 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001027 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001028
John McCallf7a1a742009-11-24 19:00:30 +00001029 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001031 // in C90, extension in C99, forbidden in C++).
1032 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1033 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1034 if (D) R.addDecl(D);
1035 }
1036
1037 // If this name wasn't predeclared and if this is not a function
1038 // call, diagnose the problem.
1039 if (R.empty()) {
John McCall578b69b2009-12-16 08:11:27 +00001040 if (DiagnoseEmptyLookup(SS, R))
1041 return ExprError();
1042
1043 assert(!R.empty() &&
1044 "DiagnoseEmptyLookup returned false but added no results");
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 }
1046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
John McCallf7a1a742009-11-24 19:00:30 +00001048 // This is guaranteed from this point on.
1049 assert(!R.empty() || ADL);
1050
1051 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001052 // Warn about constructs like:
1053 // if (void *X = foo()) { ... } else { X }.
1054 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregor751f9a42009-06-30 15:47:41 +00001056 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1057 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001058 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001059 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001060 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001061 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001062 << Var->getDeclName()
1063 << (Var->getType()->isPointerType()? 2 :
1064 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001065 break;
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001068 // Move to the parent of this scope.
1069 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001070 }
1071 }
John McCallf7a1a742009-11-24 19:00:30 +00001072 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001073 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1074 // C99 DR 316 says that, if a function type comes from a
1075 // function definition (without a prototype), that type is only
1076 // used for checking compatibility. Therefore, when referencing
1077 // the function, we pretend that we don't have the full function
1078 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001079 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001080 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001081
Douglas Gregor751f9a42009-06-30 15:47:41 +00001082 QualType T = Func->getType();
1083 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001084 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001085 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001086 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001087 }
1088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
John McCallaa81e162009-12-01 22:10:20 +00001090 // Check whether this might be a C++ implicit instance member access.
1091 // C++ [expr.prim.general]p6:
1092 // Within the definition of a non-static member function, an
1093 // identifier that names a non-static member is transformed to a
1094 // class member access expression.
1095 // But note that &SomeClass::foo is grammatically distinct, even
1096 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001097 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001098 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001099 if (!isAbstractMemberPointer)
1100 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001101 }
1102
John McCallf7a1a742009-11-24 19:00:30 +00001103 if (TemplateArgs)
1104 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001105
John McCallf7a1a742009-11-24 19:00:30 +00001106 return BuildDeclarationNameExpr(SS, R, ADL);
1107}
1108
John McCall3b4294e2009-12-16 12:17:52 +00001109/// Builds an expression which might be an implicit member expression.
1110Sema::OwningExprResult
1111Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1112 LookupResult &R,
1113 const TemplateArgumentListInfo *TemplateArgs) {
1114 switch (ClassifyImplicitMemberAccess(*this, R)) {
1115 case IMA_Instance:
1116 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1117
1118 case IMA_AnonymousMember:
1119 assert(R.isSingleResult());
1120 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1121 R.getAsSingle<FieldDecl>());
1122
1123 case IMA_Mixed:
1124 case IMA_Mixed_Unrelated:
1125 case IMA_Unresolved:
1126 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1127
1128 case IMA_Static:
1129 case IMA_Mixed_StaticContext:
1130 case IMA_Unresolved_StaticContext:
1131 if (TemplateArgs)
1132 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1133 return BuildDeclarationNameExpr(SS, R, false);
1134
1135 case IMA_Error_StaticContext:
1136 case IMA_Error_Unrelated:
1137 DiagnoseInstanceReference(*this, SS, R);
1138 return ExprError();
1139 }
1140
1141 llvm_unreachable("unexpected instance member access kind");
1142 return ExprError();
1143}
1144
John McCall129e2df2009-11-30 22:42:35 +00001145/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1146/// declaration name, generally during template instantiation.
1147/// There's a large number of things which don't need to be done along
1148/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001149Sema::OwningExprResult
1150Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1151 DeclarationName Name,
1152 SourceLocation NameLoc) {
1153 DeclContext *DC;
1154 if (!(DC = computeDeclContext(SS, false)) ||
1155 DC->isDependentContext() ||
1156 RequireCompleteDeclContext(SS))
1157 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1158
1159 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1160 LookupQualifiedName(R, DC);
1161
1162 if (R.isAmbiguous())
1163 return ExprError();
1164
1165 if (R.empty()) {
1166 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1167 return ExprError();
1168 }
1169
1170 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1171}
1172
1173/// LookupInObjCMethod - The parser has read a name in, and Sema has
1174/// detected that we're currently inside an ObjC method. Perform some
1175/// additional lookup.
1176///
1177/// Ideally, most of this would be done by lookup, but there's
1178/// actually quite a lot of extra work involved.
1179///
1180/// Returns a null sentinel to indicate trivial success.
1181Sema::OwningExprResult
1182Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1183 IdentifierInfo *II) {
1184 SourceLocation Loc = Lookup.getNameLoc();
1185
1186 // There are two cases to handle here. 1) scoped lookup could have failed,
1187 // in which case we should look for an ivar. 2) scoped lookup could have
1188 // found a decl, but that decl is outside the current instance method (i.e.
1189 // a global variable). In these two cases, we do a lookup for an ivar with
1190 // this name, if the lookup sucedes, we replace it our current decl.
1191
1192 // If we're in a class method, we don't normally want to look for
1193 // ivars. But if we don't find anything else, and there's an
1194 // ivar, that's an error.
1195 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1196
1197 bool LookForIvars;
1198 if (Lookup.empty())
1199 LookForIvars = true;
1200 else if (IsClassMethod)
1201 LookForIvars = false;
1202 else
1203 LookForIvars = (Lookup.isSingleResult() &&
1204 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1205
1206 if (LookForIvars) {
1207 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1208 ObjCInterfaceDecl *ClassDeclared;
1209 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1210 // Diagnose using an ivar in a class method.
1211 if (IsClassMethod)
1212 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1213 << IV->getDeclName());
1214
1215 // If we're referencing an invalid decl, just return this as a silent
1216 // error node. The error diagnostic was already emitted on the decl.
1217 if (IV->isInvalidDecl())
1218 return ExprError();
1219
1220 // Check if referencing a field with __attribute__((deprecated)).
1221 if (DiagnoseUseOfDecl(IV, Loc))
1222 return ExprError();
1223
1224 // Diagnose the use of an ivar outside of the declaring class.
1225 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1226 ClassDeclared != IFace)
1227 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1228
1229 // FIXME: This should use a new expr for a direct reference, don't
1230 // turn this into Self->ivar, just return a BareIVarExpr or something.
1231 IdentifierInfo &II = Context.Idents.get("self");
1232 UnqualifiedId SelfName;
1233 SelfName.setIdentifier(&II, SourceLocation());
1234 CXXScopeSpec SelfScopeSpec;
1235 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1236 SelfName, false, false);
1237 MarkDeclarationReferenced(Loc, IV);
1238 return Owned(new (Context)
1239 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1240 SelfExpr.takeAs<Expr>(), true, true));
1241 }
1242 } else if (getCurMethodDecl()->isInstanceMethod()) {
1243 // We should warn if a local variable hides an ivar.
1244 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1245 ObjCInterfaceDecl *ClassDeclared;
1246 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1247 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1248 IFace == ClassDeclared)
1249 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1250 }
1251 }
1252
1253 // Needed to implement property "super.method" notation.
1254 if (Lookup.empty() && II->isStr("super")) {
1255 QualType T;
1256
1257 if (getCurMethodDecl()->isInstanceMethod())
1258 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1259 getCurMethodDecl()->getClassInterface()));
1260 else
1261 T = Context.getObjCClassType();
1262 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1263 }
1264
1265 // Sentinel value saying that we didn't do anything special.
1266 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001267}
John McCallba135432009-11-21 08:51:07 +00001268
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001269/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001270bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001271Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1272 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001273 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001274 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001275 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001276 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001277 if (DestType->isDependentType() || From->getType()->isDependentType())
1278 return false;
1279 QualType FromRecordType = From->getType();
1280 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001281 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001282 DestType = Context.getPointerType(DestType);
1283 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001284 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001285 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1286 CheckDerivedToBaseConversion(FromRecordType,
1287 DestRecordType,
1288 From->getSourceRange().getBegin(),
1289 From->getSourceRange()))
1290 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001291 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1292 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001293 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001294 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001295}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001296
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001297/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001298static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001299 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001300 SourceLocation Loc, QualType Ty,
1301 const TemplateArgumentListInfo *TemplateArgs = 0) {
1302 NestedNameSpecifier *Qualifier = 0;
1303 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001304 if (SS.isSet()) {
1305 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1306 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCallf7a1a742009-11-24 19:00:30 +00001309 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1310 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001311}
1312
John McCallaa81e162009-12-01 22:10:20 +00001313/// Builds an implicit member access expression. The current context
1314/// is known to be an instance method, and the given unqualified lookup
1315/// set is known to contain only instance members, at least one of which
1316/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001317Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001318Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1319 LookupResult &R,
1320 const TemplateArgumentListInfo *TemplateArgs,
1321 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001322 assert(!R.empty() && !R.isAmbiguous());
1323
John McCallba135432009-11-21 08:51:07 +00001324 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001325
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001326 // We may have found a field within an anonymous union or struct
1327 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001328 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001329 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001330 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001331 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001332 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001333
John McCallaa81e162009-12-01 22:10:20 +00001334 // If this is known to be an instance access, go ahead and build a
1335 // 'this' expression now.
1336 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1337 Expr *This = 0; // null signifies implicit access
1338 if (IsKnownInstance) {
1339 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001340 }
1341
John McCallaa81e162009-12-01 22:10:20 +00001342 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1343 /*OpLoc*/ SourceLocation(),
1344 /*IsArrow*/ true,
1345 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001346}
1347
John McCallf7a1a742009-11-24 19:00:30 +00001348bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001349 const LookupResult &R,
1350 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001351 // Only when used directly as the postfix-expression of a call.
1352 if (!HasTrailingLParen)
1353 return false;
1354
1355 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001356 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001357 return false;
1358
1359 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001360 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001361 return false;
1362
1363 // Turn off ADL when we find certain kinds of declarations during
1364 // normal lookup:
1365 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1366 NamedDecl *D = *I;
1367
1368 // C++0x [basic.lookup.argdep]p3:
1369 // -- a declaration of a class member
1370 // Since using decls preserve this property, we check this on the
1371 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001372 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001373 return false;
1374
1375 // C++0x [basic.lookup.argdep]p3:
1376 // -- a block-scope function declaration that is not a
1377 // using-declaration
1378 // NOTE: we also trigger this for function templates (in fact, we
1379 // don't check the decl type at all, since all other decl types
1380 // turn off ADL anyway).
1381 if (isa<UsingShadowDecl>(D))
1382 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1383 else if (D->getDeclContext()->isFunctionOrMethod())
1384 return false;
1385
1386 // C++0x [basic.lookup.argdep]p3:
1387 // -- a declaration that is neither a function or a function
1388 // template
1389 // And also for builtin functions.
1390 if (isa<FunctionDecl>(D)) {
1391 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1392
1393 // But also builtin functions.
1394 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1395 return false;
1396 } else if (!isa<FunctionTemplateDecl>(D))
1397 return false;
1398 }
1399
1400 return true;
1401}
1402
1403
John McCallba135432009-11-21 08:51:07 +00001404/// Diagnoses obvious problems with the use of the given declaration
1405/// as an expression. This is only actually called for lookups that
1406/// were not overloaded, and it doesn't promise that the declaration
1407/// will in fact be used.
1408static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1409 if (isa<TypedefDecl>(D)) {
1410 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1411 return true;
1412 }
1413
1414 if (isa<ObjCInterfaceDecl>(D)) {
1415 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1416 return true;
1417 }
1418
1419 if (isa<NamespaceDecl>(D)) {
1420 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1421 return true;
1422 }
1423
1424 return false;
1425}
1426
1427Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001428Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001429 LookupResult &R,
1430 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001431 // If this is a single, fully-resolved result and we don't need ADL,
1432 // just build an ordinary singleton decl ref.
1433 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001434 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001435
1436 // We only need to check the declaration if there's exactly one
1437 // result, because in the overloaded case the results can only be
1438 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001439 if (R.isSingleResult() &&
1440 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001441 return ExprError();
1442
John McCallf7a1a742009-11-24 19:00:30 +00001443 bool Dependent
1444 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001445 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001446 = UnresolvedLookupExpr::Create(Context, Dependent,
1447 (NestedNameSpecifier*) SS.getScopeRep(),
1448 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001449 R.getLookupName(), R.getNameLoc(),
1450 NeedsADL, R.isOverloadedResult());
1451 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1452 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001453
1454 return Owned(ULE);
1455}
1456
1457
1458/// \brief Complete semantic analysis for a reference to the given declaration.
1459Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001460Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001461 SourceLocation Loc, NamedDecl *D) {
1462 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001463 assert(!isa<FunctionTemplateDecl>(D) &&
1464 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001465 DeclarationName Name = D->getDeclName();
1466
1467 if (CheckDeclInExpr(*this, Loc, D))
1468 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001469
Douglas Gregor9af2f522009-12-01 16:58:18 +00001470 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1471 // Specifically diagnose references to class templates that are missing
1472 // a template argument list.
1473 Diag(Loc, diag::err_template_decl_ref)
1474 << Template << SS.getRange();
1475 Diag(Template->getLocation(), diag::note_template_decl_here);
1476 return ExprError();
1477 }
1478
1479 // Make sure that we're referring to a value.
1480 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1481 if (!VD) {
1482 Diag(Loc, diag::err_ref_non_value)
1483 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001484 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001485 return ExprError();
1486 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001487
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001488 // Check whether this declaration can be used. Note that we suppress
1489 // this check when we're going to perform argument-dependent lookup
1490 // on this function name, because this might not be the function
1491 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001492 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001493 return ExprError();
1494
Steve Naroffdd972f22008-09-05 22:11:13 +00001495 // Only create DeclRefExpr's for valid Decl's.
1496 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001497 return ExprError();
1498
Chris Lattner639e2d32008-10-20 05:16:36 +00001499 // If the identifier reference is inside a block, and it refers to a value
1500 // that is outside the block, create a BlockDeclRefExpr instead of a
1501 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1502 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001503 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001504 // We do not do this for things like enum constants, global variables, etc,
1505 // as they do not get snapshotted.
1506 //
1507 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001508 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001509 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001510 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001511 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001512 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001513 // This is to record that a 'const' was actually synthesize and added.
1514 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001515 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Eli Friedman5fdeae12009-03-22 23:00:19 +00001517 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001518 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001519 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001520 }
1521 // If this reference is not in a block or if the referenced variable is
1522 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001523
John McCallf7a1a742009-11-24 19:00:30 +00001524 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001525}
1526
Sebastian Redlcd965b92009-01-18 18:53:16 +00001527Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1528 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001529 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001530
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001532 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001533 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1534 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1535 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001537
Chris Lattnerfa28b302008-01-12 08:14:25 +00001538 // Pre-defined identifiers are of type char[x], where x is the length of the
1539 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Anders Carlsson3a082d82009-09-08 18:24:21 +00001541 Decl *currentDecl = getCurFunctionOrMethodDecl();
1542 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001543 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001544 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001545 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001546
Anders Carlsson773f3972009-09-11 01:22:35 +00001547 QualType ResTy;
1548 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1549 ResTy = Context.DependentTy;
1550 } else {
1551 unsigned Length =
1552 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001553
Anders Carlsson773f3972009-09-11 01:22:35 +00001554 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001555 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001556 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1557 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001558 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001559}
1560
Sebastian Redlcd965b92009-01-18 18:53:16 +00001561Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 llvm::SmallString<16> CharBuffer;
1563 CharBuffer.resize(Tok.getLength());
1564 const char *ThisTokBegin = &CharBuffer[0];
1565 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001566
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1568 Tok.getLocation(), PP);
1569 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001570 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001571
1572 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1573
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001574 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1575 Literal.isWide(),
1576 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001577}
1578
Sebastian Redlcd965b92009-01-18 18:53:16 +00001579Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1580 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1582 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001583 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001584 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001585 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001586 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 }
Ted Kremenek28396602009-01-13 23:19:12 +00001588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001590 // Add padding so that NumericLiteralParser can overread by one character.
1591 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001593
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // Get the spelling of the token, which eliminates trigraphs, etc.
1595 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001596
Mike Stump1eb44332009-09-09 15:08:12 +00001597 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 Tok.getLocation(), PP);
1599 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001600 return ExprError();
1601
Chris Lattner5d661452007-08-26 03:42:43 +00001602 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001603
Chris Lattner5d661452007-08-26 03:42:43 +00001604 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001605 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001606 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001607 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001608 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001609 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001610 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001611 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001612
1613 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1614
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001615 // isExact will be set by GetFloatValue().
1616 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001617 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1618 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001619
Chris Lattner5d661452007-08-26 03:42:43 +00001620 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001621 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001622 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001623 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624
Neil Boothb9449512007-08-29 22:00:19 +00001625 // long long is a C99 feature.
1626 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001627 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001628 Diag(Tok.getLocation(), diag::ext_longlong);
1629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001631 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 if (Literal.GetIntegerValue(ResultVal)) {
1634 // If this value didn't fit into uintmax_t, warn and force to ull.
1635 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001636 Ty = Context.UnsignedLongLongTy;
1637 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001638 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 } else {
1640 // If this value fits into a ULL, try to figure out what else it fits into
1641 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001642
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1644 // be an unsigned int.
1645 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1646
1647 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001648 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001649 if (!Literal.isLong && !Literal.isLongLong) {
1650 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001651 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001652
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 // Does it fit in a unsigned int?
1654 if (ResultVal.isIntN(IntSize)) {
1655 // Does it fit in a signed int?
1656 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001657 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001659 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001660 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001663
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001665 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001666 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // Does it fit in a unsigned long?
1669 if (ResultVal.isIntN(LongSize)) {
1670 // Does it fit in a signed long?
1671 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001672 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001674 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001675 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001677 }
1678
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001680 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001681 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001682
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 // Does it fit in a unsigned long long?
1684 if (ResultVal.isIntN(LongLongSize)) {
1685 // Does it fit in a signed long long?
1686 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001687 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001689 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001690 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 }
1692 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 // If we still couldn't decide a type, we probably have something that
1695 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001696 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001698 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001699 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001701
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001702 if (ResultVal.getBitWidth() != Width)
1703 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001705 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001707
Chris Lattner5d661452007-08-26 03:42:43 +00001708 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1709 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001710 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001711 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001712
1713 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714}
1715
Sebastian Redlcd965b92009-01-18 18:53:16 +00001716Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1717 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001718 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001719 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001720 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001721}
1722
1723/// The UsualUnaryConversions() function is *not* called by this routine.
1724/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001725bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001726 SourceLocation OpLoc,
1727 const SourceRange &ExprRange,
1728 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001729 if (exprType->isDependentType())
1730 return false;
1731
Sebastian Redl5d484e82009-11-23 17:18:46 +00001732 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1733 // the result is the size of the referenced type."
1734 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1735 // result shall be the alignment of the referenced type."
1736 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1737 exprType = Ref->getPointeeType();
1738
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001740 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001741 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001742 if (isSizeof)
1743 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1744 return false;
1745 }
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Chris Lattner1efaa952009-04-24 00:30:45 +00001747 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001748 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001749 Diag(OpLoc, diag::ext_sizeof_void_type)
1750 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001751 return false;
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Chris Lattner1efaa952009-04-24 00:30:45 +00001754 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00001755 PDiag(diag::err_sizeof_alignof_incomplete_type)
1756 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001757 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Chris Lattner1efaa952009-04-24 00:30:45 +00001759 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001760 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001761 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001762 << exprType << isSizeof << ExprRange;
1763 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001764 }
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Chris Lattner1efaa952009-04-24 00:30:45 +00001766 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001767}
1768
Chris Lattner31e21e02009-01-24 20:17:12 +00001769bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1770 const SourceRange &ExprRange) {
1771 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001772
Mike Stump1eb44332009-09-09 15:08:12 +00001773 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001774 if (isa<DeclRefExpr>(E))
1775 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001776
1777 // Cannot know anything else if the expression is dependent.
1778 if (E->isTypeDependent())
1779 return false;
1780
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001781 if (E->getBitField()) {
1782 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1783 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001784 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001785
1786 // Alignment of a field access is always okay, so long as it isn't a
1787 // bit-field.
1788 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001789 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001790 return false;
1791
Chris Lattner31e21e02009-01-24 20:17:12 +00001792 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1793}
1794
Douglas Gregorba498172009-03-13 21:01:28 +00001795/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001796Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001797Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001798 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001799 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001800 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001801 return ExprError();
1802
John McCalla93c9342009-12-07 02:54:59 +00001803 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001804
Douglas Gregorba498172009-03-13 21:01:28 +00001805 if (!T->isDependentType() &&
1806 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1807 return ExprError();
1808
1809 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001810 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001811 Context.getSizeType(), OpLoc,
1812 R.getEnd()));
1813}
1814
1815/// \brief Build a sizeof or alignof expression given an expression
1816/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001817Action::OwningExprResult
1818Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001819 bool isSizeOf, SourceRange R) {
1820 // Verify that the operand is valid.
1821 bool isInvalid = false;
1822 if (E->isTypeDependent()) {
1823 // Delay type-checking for type-dependent expressions.
1824 } else if (!isSizeOf) {
1825 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001826 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001827 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1828 isInvalid = true;
1829 } else {
1830 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1831 }
1832
1833 if (isInvalid)
1834 return ExprError();
1835
1836 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1837 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1838 Context.getSizeType(), OpLoc,
1839 R.getEnd()));
1840}
1841
Sebastian Redl05189992008-11-11 17:56:53 +00001842/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1843/// the same for @c alignof and @c __alignof
1844/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001845Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001846Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1847 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001849 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001850
Sebastian Redl05189992008-11-11 17:56:53 +00001851 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001852 TypeSourceInfo *TInfo;
1853 (void) GetTypeFromParser(TyOrEx, &TInfo);
1854 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001855 }
Sebastian Redl05189992008-11-11 17:56:53 +00001856
Douglas Gregorba498172009-03-13 21:01:28 +00001857 Expr *ArgEx = (Expr *)TyOrEx;
1858 Action::OwningExprResult Result
1859 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1860
1861 if (Result.isInvalid())
1862 DeleteExpr(ArgEx);
1863
1864 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001865}
1866
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001867QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001868 if (V->isTypeDependent())
1869 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Chris Lattnercc26ed72007-08-26 05:39:26 +00001871 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001872 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001873 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Chris Lattnercc26ed72007-08-26 05:39:26 +00001875 // Otherwise they pass through real integer and floating point types here.
1876 if (V->getType()->isArithmeticType())
1877 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Chris Lattnercc26ed72007-08-26 05:39:26 +00001879 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001880 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1881 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001882 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001883}
1884
1885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886
Sebastian Redl0eb23302009-01-19 00:08:26 +00001887Action::OwningExprResult
1888Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1889 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 UnaryOperator::Opcode Opc;
1891 switch (Kind) {
1892 default: assert(0 && "Unknown unary op!");
1893 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1894 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1895 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001896
Eli Friedmane4216e92009-11-18 03:38:04 +00001897 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001898}
1899
Sebastian Redl0eb23302009-01-19 00:08:26 +00001900Action::OwningExprResult
1901Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1902 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001903 // Since this might be a postfix expression, get rid of ParenListExprs.
1904 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1905
Sebastian Redl0eb23302009-01-19 00:08:26 +00001906 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1907 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor337c6b92008-11-19 17:17:41 +00001909 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001910 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1911 Base.release();
1912 Idx.release();
1913 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1914 Context.DependentTy, RLoc));
1915 }
1916
Mike Stump1eb44332009-09-09 15:08:12 +00001917 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001918 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001919 LHSExp->getType()->isEnumeralType() ||
1920 RHSExp->getType()->isRecordType() ||
1921 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001922 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001923 }
1924
Sebastian Redlf322ed62009-10-29 20:17:01 +00001925 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1926}
1927
1928
1929Action::OwningExprResult
1930Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1931 ExprArg Idx, SourceLocation RLoc) {
1932 Expr *LHSExp = static_cast<Expr*>(Base.get());
1933 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1934
Chris Lattner12d9ff62007-07-16 00:14:47 +00001935 // Perform default conversions.
1936 DefaultFunctionArrayConversion(LHSExp);
1937 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001938
Chris Lattner12d9ff62007-07-16 00:14:47 +00001939 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001940
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001942 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001943 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001945 Expr *BaseExpr, *IndexExpr;
1946 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001947 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1948 BaseExpr = LHSExp;
1949 IndexExpr = RHSExp;
1950 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001951 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001952 BaseExpr = LHSExp;
1953 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001954 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001955 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001956 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001957 BaseExpr = RHSExp;
1958 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001959 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001960 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001961 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001962 BaseExpr = LHSExp;
1963 IndexExpr = RHSExp;
1964 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001965 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001966 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001967 // Handle the uncommon case of "123[Ptr]".
1968 BaseExpr = RHSExp;
1969 IndexExpr = LHSExp;
1970 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001971 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001972 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001973 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001974
Chris Lattner12d9ff62007-07-16 00:14:47 +00001975 // FIXME: need to deal with const...
1976 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001977 } else if (LHSTy->isArrayType()) {
1978 // If we see an array that wasn't promoted by
1979 // DefaultFunctionArrayConversion, it must be an array that
1980 // wasn't promoted because of the C90 rule that doesn't
1981 // allow promoting non-lvalue arrays. Warn, then
1982 // force the promotion here.
1983 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1984 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001985 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1986 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001987 LHSTy = LHSExp->getType();
1988
1989 BaseExpr = LHSExp;
1990 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001991 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001992 } else if (RHSTy->isArrayType()) {
1993 // Same as previous, except for 123[f().a] case
1994 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1995 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001996 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1997 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001998 RHSTy = RHSExp->getType();
1999
2000 BaseExpr = RHSExp;
2001 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002002 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002004 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2005 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002006 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002008 if (!(IndexExpr->getType()->isIntegerType() &&
2009 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002010 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2011 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002012
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002013 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002014 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2015 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002016 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2017
Douglas Gregore7450f52009-03-24 19:52:54 +00002018 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002019 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2020 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002021 // incomplete types are not object types.
2022 if (ResultType->isFunctionType()) {
2023 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2024 << ResultType << BaseExpr->getSourceRange();
2025 return ExprError();
2026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregore7450f52009-03-24 19:52:54 +00002028 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002029 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002030 PDiag(diag::err_subscript_incomplete_type)
2031 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002032 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Chris Lattner1efaa952009-04-24 00:30:45 +00002034 // Diagnose bad cases where we step over interface counts.
2035 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2036 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2037 << ResultType << BaseExpr->getSourceRange();
2038 return ExprError();
2039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Sebastian Redl0eb23302009-01-19 00:08:26 +00002041 Base.release();
2042 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002043 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002044 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002045}
2046
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002047QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002048CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002049 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002050 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002051 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2052 // see FIXME there.
2053 //
2054 // FIXME: This logic can be greatly simplified by splitting it along
2055 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002056 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002057
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002058 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002059 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002060
Mike Stumpeed9cac2009-02-19 03:04:26 +00002061 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002062 // special names that indicate a subset of exactly half the elements are
2063 // to be selected.
2064 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002065
Nate Begeman353417a2009-01-18 01:47:54 +00002066 // This flag determines whether or not CompName has an 's' char prefix,
2067 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002068 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002069
2070 // Check that we've found one of the special components, or that the component
2071 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002072 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002073 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2074 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002075 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002076 do
2077 compStr++;
2078 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002079 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002080 do
2081 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002082 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002083 }
Nate Begeman353417a2009-01-18 01:47:54 +00002084
Mike Stumpeed9cac2009-02-19 03:04:26 +00002085 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002086 // We didn't get to the end of the string. This means the component names
2087 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002088 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2089 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002090 return QualType();
2091 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002092
Nate Begeman353417a2009-01-18 01:47:54 +00002093 // Ensure no component accessor exceeds the width of the vector type it
2094 // operates on.
2095 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002096 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002097
2098 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002099 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002100
2101 while (*compStr) {
2102 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2103 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2104 << baseType << SourceRange(CompLoc);
2105 return QualType();
2106 }
2107 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002108 }
Nate Begeman8a997642008-05-09 06:41:27 +00002109
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002110 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002111 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002112 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002113 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002114 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002115 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002116 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002117 if (HexSwizzle)
2118 CompSize--;
2119
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002120 if (CompSize == 1)
2121 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002122
Nate Begeman213541a2008-04-18 23:10:10 +00002123 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002124 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002125 // diagostics look bad. We want extended vector types to appear built-in.
2126 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2127 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2128 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002129 }
2130 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002131}
2132
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002133static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002134 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002135 const Selector &Sel,
2136 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Anders Carlsson8f28f992009-08-26 18:25:21 +00002138 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002139 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002140 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002141 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002143 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2144 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002145 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002146 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002147 return D;
2148 }
2149 return 0;
2150}
2151
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002152static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002153 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002154 const Selector &Sel,
2155 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002156 // Check protocols on qualified interfaces.
2157 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002158 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002159 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002160 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002161 GDecl = PD;
2162 break;
2163 }
2164 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002165 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002166 GDecl = OMD;
2167 break;
2168 }
2169 }
2170 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002171 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002172 E = QIdTy->qual_end(); I != E; ++I) {
2173 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002174 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002175 if (GDecl)
2176 return GDecl;
2177 }
2178 }
2179 return GDecl;
2180}
Chris Lattner76a642f2009-02-15 22:43:40 +00002181
John McCall129e2df2009-11-30 22:42:35 +00002182Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002183Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2184 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002185 const CXXScopeSpec &SS,
2186 NamedDecl *FirstQualifierInScope,
2187 DeclarationName Name, SourceLocation NameLoc,
2188 const TemplateArgumentListInfo *TemplateArgs) {
2189 Expr *BaseExpr = Base.takeAs<Expr>();
2190
2191 // Even in dependent contexts, try to diagnose base expressions with
2192 // obviously wrong types, e.g.:
2193 //
2194 // T* t;
2195 // t.f;
2196 //
2197 // In Obj-C++, however, the above expression is valid, since it could be
2198 // accessing the 'f' property if T is an Obj-C interface. The extra check
2199 // allows this, while still reporting an error if T is a struct pointer.
2200 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002201 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002202 if (PT && (!getLangOptions().ObjC1 ||
2203 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002204 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002205 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002206 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002207 return ExprError();
2208 }
2209 }
2210
John McCallaa81e162009-12-01 22:10:20 +00002211 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002212
2213 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2214 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002215 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002216 IsArrow, OpLoc,
2217 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2218 SS.getRange(),
2219 FirstQualifierInScope,
2220 Name, NameLoc,
2221 TemplateArgs));
2222}
2223
2224/// We know that the given qualified member reference points only to
2225/// declarations which do not belong to the static type of the base
2226/// expression. Diagnose the problem.
2227static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2228 Expr *BaseExpr,
2229 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002230 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002231 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002232 // If this is an implicit member access, use a different set of
2233 // diagnostics.
2234 if (!BaseExpr)
2235 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002236
2237 // FIXME: this is an exceedingly lame diagnostic for some of the more
2238 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002239 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002240 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002241 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002242}
2243
2244// Check whether the declarations we found through a nested-name
2245// specifier in a member expression are actually members of the base
2246// type. The restriction here is:
2247//
2248// C++ [expr.ref]p2:
2249// ... In these cases, the id-expression shall name a
2250// member of the class or of one of its base classes.
2251//
2252// So it's perfectly legitimate for the nested-name specifier to name
2253// an unrelated class, and for us to find an overload set including
2254// decls from classes which are not superclasses, as long as the decl
2255// we actually pick through overload resolution is from a superclass.
2256bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2257 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002258 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002259 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002260 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2261 if (!BaseRT) {
2262 // We can't check this yet because the base type is still
2263 // dependent.
2264 assert(BaseType->isDependentType());
2265 return false;
2266 }
2267 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002268
2269 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002270 // If this is an implicit member reference and we find a
2271 // non-instance member, it's not an error.
2272 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2273 return false;
John McCall129e2df2009-11-30 22:42:35 +00002274
John McCallaa81e162009-12-01 22:10:20 +00002275 // Note that we use the DC of the decl, not the underlying decl.
2276 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2277 while (RecordD->isAnonymousStructOrUnion())
2278 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2279
2280 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2281 MemberRecord.insert(RecordD->getCanonicalDecl());
2282
2283 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2284 return false;
2285 }
2286
John McCall2f841ba2009-12-02 03:53:29 +00002287 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002288 return true;
2289}
2290
2291static bool
2292LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2293 SourceRange BaseRange, const RecordType *RTy,
2294 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2295 RecordDecl *RDecl = RTy->getDecl();
2296 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2297 PDiag(diag::err_typecheck_incomplete_tag)
2298 << BaseRange))
2299 return true;
2300
2301 DeclContext *DC = RDecl;
2302 if (SS.isSet()) {
2303 // If the member name was a qualified-id, look into the
2304 // nested-name-specifier.
2305 DC = SemaRef.computeDeclContext(SS, false);
2306
John McCall2f841ba2009-12-02 03:53:29 +00002307 if (SemaRef.RequireCompleteDeclContext(SS)) {
2308 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2309 << SS.getRange() << DC;
2310 return true;
2311 }
2312
John McCallaa81e162009-12-01 22:10:20 +00002313 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2314
2315 if (!isa<TypeDecl>(DC)) {
2316 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2317 << DC << SS.getRange();
2318 return true;
John McCall129e2df2009-11-30 22:42:35 +00002319 }
2320 }
2321
John McCallaa81e162009-12-01 22:10:20 +00002322 // The record definition is complete, now look up the member.
2323 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002324
2325 return false;
2326}
2327
2328Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002329Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002330 SourceLocation OpLoc, bool IsArrow,
2331 const CXXScopeSpec &SS,
2332 NamedDecl *FirstQualifierInScope,
2333 DeclarationName Name, SourceLocation NameLoc,
2334 const TemplateArgumentListInfo *TemplateArgs) {
2335 Expr *Base = BaseArg.takeAs<Expr>();
2336
John McCall2f841ba2009-12-02 03:53:29 +00002337 if (BaseType->isDependentType() ||
2338 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002339 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002340 IsArrow, OpLoc,
2341 SS, FirstQualifierInScope,
2342 Name, NameLoc,
2343 TemplateArgs);
2344
2345 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002346
John McCallaa81e162009-12-01 22:10:20 +00002347 // Implicit member accesses.
2348 if (!Base) {
2349 QualType RecordTy = BaseType;
2350 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2351 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2352 RecordTy->getAs<RecordType>(),
2353 OpLoc, SS))
2354 return ExprError();
2355
2356 // Explicit member accesses.
2357 } else {
2358 OwningExprResult Result =
2359 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2360 SS, FirstQualifierInScope,
2361 /*ObjCImpDecl*/ DeclPtrTy());
2362
2363 if (Result.isInvalid()) {
2364 Owned(Base);
2365 return ExprError();
2366 }
2367
2368 if (Result.get())
2369 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002370 }
2371
John McCallaa81e162009-12-01 22:10:20 +00002372 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2373 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002374}
2375
2376Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002377Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2378 SourceLocation OpLoc, bool IsArrow,
2379 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002380 LookupResult &R,
2381 const TemplateArgumentListInfo *TemplateArgs) {
2382 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002383 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002384 if (IsArrow) {
2385 assert(BaseType->isPointerType());
2386 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2387 }
2388
2389 NestedNameSpecifier *Qualifier =
2390 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2391 DeclarationName MemberName = R.getLookupName();
2392 SourceLocation MemberLoc = R.getNameLoc();
2393
2394 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002395 return ExprError();
2396
John McCall129e2df2009-11-30 22:42:35 +00002397 if (R.empty()) {
2398 // Rederive where we looked up.
2399 DeclContext *DC = (SS.isSet()
2400 ? computeDeclContext(SS, false)
2401 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002402
John McCall129e2df2009-11-30 22:42:35 +00002403 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002404 << MemberName << DC
2405 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002406 return ExprError();
2407 }
2408
John McCall2f841ba2009-12-02 03:53:29 +00002409 // Diagnose qualified lookups that find only declarations from a
2410 // non-base type. Note that it's okay for lookup to find
2411 // declarations from a non-base type as long as those aren't the
2412 // ones picked by overload resolution.
2413 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002414 return ExprError();
2415
2416 // Construct an unresolved result if we in fact got an unresolved
2417 // result.
2418 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002419 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002420 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002421 R.isUnresolvableResult() ||
2422 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002423
2424 UnresolvedMemberExpr *MemExpr
2425 = UnresolvedMemberExpr::Create(Context, Dependent,
2426 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002427 BaseExpr, BaseExprType,
2428 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002429 Qualifier, SS.getRange(),
2430 MemberName, MemberLoc,
2431 TemplateArgs);
2432 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2433 MemExpr->addDecl(*I);
2434
2435 return Owned(MemExpr);
2436 }
2437
2438 assert(R.isSingleResult());
2439 NamedDecl *MemberDecl = R.getFoundDecl();
2440
2441 // FIXME: diagnose the presence of template arguments now.
2442
2443 // If the decl being referenced had an error, return an error for this
2444 // sub-expr without emitting another error, in order to avoid cascading
2445 // error cases.
2446 if (MemberDecl->isInvalidDecl())
2447 return ExprError();
2448
John McCallaa81e162009-12-01 22:10:20 +00002449 // Handle the implicit-member-access case.
2450 if (!BaseExpr) {
2451 // If this is not an instance member, convert to a non-member access.
2452 if (!IsInstanceMember(MemberDecl))
2453 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2454
2455 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2456 }
2457
John McCall129e2df2009-11-30 22:42:35 +00002458 bool ShouldCheckUse = true;
2459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2460 // Don't diagnose the use of a virtual member function unless it's
2461 // explicitly qualified.
2462 if (MD->isVirtual() && !SS.isSet())
2463 ShouldCheckUse = false;
2464 }
2465
2466 // Check the use of this member.
2467 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2468 Owned(BaseExpr);
2469 return ExprError();
2470 }
2471
2472 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2473 // We may have found a field within an anonymous union or struct
2474 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002475 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2476 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002477 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2478 BaseExpr, OpLoc);
2479
2480 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2481 QualType MemberType = FD->getType();
2482 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2483 MemberType = Ref->getPointeeType();
2484 else {
2485 Qualifiers BaseQuals = BaseType.getQualifiers();
2486 BaseQuals.removeObjCGCAttr();
2487 if (FD->isMutable()) BaseQuals.removeConst();
2488
2489 Qualifiers MemberQuals
2490 = Context.getCanonicalType(MemberType).getQualifiers();
2491
2492 Qualifiers Combined = BaseQuals + MemberQuals;
2493 if (Combined != MemberQuals)
2494 MemberType = Context.getQualifiedType(MemberType, Combined);
2495 }
2496
2497 MarkDeclarationReferenced(MemberLoc, FD);
2498 if (PerformObjectMemberConversion(BaseExpr, FD))
2499 return ExprError();
2500 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2501 FD, MemberLoc, MemberType));
2502 }
2503
2504 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2505 MarkDeclarationReferenced(MemberLoc, Var);
2506 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2507 Var, MemberLoc,
2508 Var->getType().getNonReferenceType()));
2509 }
2510
2511 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2512 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2513 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2514 MemberFn, MemberLoc,
2515 MemberFn->getType()));
2516 }
2517
2518 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2519 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2520 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2521 Enum, MemberLoc, Enum->getType()));
2522 }
2523
2524 Owned(BaseExpr);
2525
2526 if (isa<TypeDecl>(MemberDecl))
2527 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2528 << MemberName << int(IsArrow));
2529
2530 // We found a declaration kind that we didn't expect. This is a
2531 // generic error message that tells the user that she can't refer
2532 // to this member with '.' or '->'.
2533 return ExprError(Diag(MemberLoc,
2534 diag::err_typecheck_member_reference_unknown)
2535 << MemberName << int(IsArrow));
2536}
2537
2538/// Look up the given member of the given non-type-dependent
2539/// expression. This can return in one of two ways:
2540/// * If it returns a sentinel null-but-valid result, the caller will
2541/// assume that lookup was performed and the results written into
2542/// the provided structure. It will take over from there.
2543/// * Otherwise, the returned expression will be produced in place of
2544/// an ordinary member expression.
2545///
2546/// The ObjCImpDecl bit is a gross hack that will need to be properly
2547/// fixed for ObjC++.
2548Sema::OwningExprResult
2549Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002550 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002551 const CXXScopeSpec &SS,
2552 NamedDecl *FirstQualifierInScope,
2553 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002554 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Steve Naroff3cc4af82007-12-16 21:42:28 +00002556 // Perform default conversions.
2557 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002558
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002559 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002560 assert(!BaseType->isDependentType());
2561
2562 DeclarationName MemberName = R.getLookupName();
2563 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002564
2565 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002566 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002567 // function. Suggest the addition of those parentheses, build the
2568 // call, and continue on.
2569 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2570 if (const FunctionProtoType *Fun
2571 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2572 QualType ResultTy = Fun->getResultType();
2573 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002574 ((!IsArrow && ResultTy->isRecordType()) ||
2575 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002576 ResultTy->getAs<PointerType>()->getPointeeType()
2577 ->isRecordType()))) {
2578 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2579 Diag(Loc, diag::err_member_reference_needs_call)
2580 << QualType(Fun, 0)
2581 << CodeModificationHint::CreateInsertion(Loc, "()");
2582
2583 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002584 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002585 MultiExprArg(*this, 0, 0), 0, Loc);
2586 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002587 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002588
2589 BaseExpr = NewBase.takeAs<Expr>();
2590 DefaultFunctionArrayConversion(BaseExpr);
2591 BaseType = BaseExpr->getType();
2592 }
2593 }
2594 }
2595
David Chisnall0f436562009-08-17 16:35:33 +00002596 // If this is an Objective-C pseudo-builtin and a definition is provided then
2597 // use that.
2598 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002599 if (IsArrow) {
2600 // Handle the following exceptional case PObj->isa.
2601 if (const ObjCObjectPointerType *OPT =
2602 BaseType->getAs<ObjCObjectPointerType>()) {
2603 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2604 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002605 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2606 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002607 }
2608 }
David Chisnall0f436562009-08-17 16:35:33 +00002609 // We have an 'id' type. Rather than fall through, we check if this
2610 // is a reference to 'isa'.
2611 if (BaseType != Context.ObjCIdRedefinitionType) {
2612 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002613 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002614 }
David Chisnall0f436562009-08-17 16:35:33 +00002615 }
John McCall129e2df2009-11-30 22:42:35 +00002616
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002617 // If this is an Objective-C pseudo-builtin and a definition is provided then
2618 // use that.
2619 if (Context.isObjCSelType(BaseType)) {
2620 // We have an 'SEL' type. Rather than fall through, we check if this
2621 // is a reference to 'sel_id'.
2622 if (BaseType != Context.ObjCSelRedefinitionType) {
2623 BaseType = Context.ObjCSelRedefinitionType;
2624 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2625 }
2626 }
John McCall129e2df2009-11-30 22:42:35 +00002627
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002628 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002629
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002630 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002631 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002632 // Also must look for a getter name which uses property syntax.
2633 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2634 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2635 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2636 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2637 ObjCMethodDecl *Getter;
2638 // FIXME: need to also look locally in the implementation.
2639 if ((Getter = IFace->lookupClassMethod(Sel))) {
2640 // Check the use of this method.
2641 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2642 return ExprError();
2643 }
2644 // If we found a getter then this may be a valid dot-reference, we
2645 // will look for the matching setter, in case it is needed.
2646 Selector SetterSel =
2647 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2648 PP.getSelectorTable(), Member);
2649 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2650 if (!Setter) {
2651 // If this reference is in an @implementation, also check for 'private'
2652 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002653 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002654 }
2655 // Look through local category implementations associated with the class.
2656 if (!Setter)
2657 Setter = IFace->getCategoryClassMethod(SetterSel);
2658
2659 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2660 return ExprError();
2661
2662 if (Getter || Setter) {
2663 QualType PType;
2664
2665 if (Getter)
2666 PType = Getter->getResultType();
2667 else
2668 // Get the expression type from Setter's incoming parameter.
2669 PType = (*(Setter->param_end() -1))->getType();
2670 // FIXME: we must check that the setter has property type.
2671 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2672 PType,
2673 Setter, MemberLoc, BaseExpr));
2674 }
2675 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2676 << MemberName << BaseType);
2677 }
2678 }
2679
2680 if (BaseType->isObjCClassType() &&
2681 BaseType != Context.ObjCClassRedefinitionType) {
2682 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002683 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002684 }
Mike Stump1eb44332009-09-09 15:08:12 +00002685
John McCall129e2df2009-11-30 22:42:35 +00002686 if (IsArrow) {
2687 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002688 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002689 else if (BaseType->isObjCObjectPointerType())
2690 ;
John McCall812c1542009-12-07 22:46:59 +00002691 else if (BaseType->isRecordType()) {
2692 // Recover from arrow accesses to records, e.g.:
2693 // struct MyRecord foo;
2694 // foo->bar
2695 // This is actually well-formed in C++ if MyRecord has an
2696 // overloaded operator->, but that should have been dealt with
2697 // by now.
2698 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2699 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2700 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2701 IsArrow = false;
2702 } else {
John McCall129e2df2009-11-30 22:42:35 +00002703 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2704 << BaseType << BaseExpr->getSourceRange();
2705 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002706 }
John McCall812c1542009-12-07 22:46:59 +00002707 } else {
2708 // Recover from dot accesses to pointers, e.g.:
2709 // type *foo;
2710 // foo.bar
2711 // This is actually well-formed in two cases:
2712 // - 'type' is an Objective C type
2713 // - 'bar' is a pseudo-destructor name which happens to refer to
2714 // the appropriate pointer type
2715 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2716 const PointerType *PT = BaseType->getAs<PointerType>();
2717 if (PT && PT->getPointeeType()->isRecordType()) {
2718 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2719 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2720 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2721 BaseType = PT->getPointeeType();
2722 IsArrow = true;
2723 }
2724 }
John McCall129e2df2009-11-30 22:42:35 +00002725 }
John McCall812c1542009-12-07 22:46:59 +00002726
John McCall129e2df2009-11-30 22:42:35 +00002727 // Handle field access to simple records. This also handles access
2728 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002729 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002730 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2731 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002732 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002733 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002734 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002735
Douglas Gregora71d8192009-09-04 17:36:40 +00002736 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2737 // into a record type was handled above, any destructor we see here is a
2738 // pseudo-destructor.
2739 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2740 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002741 // The left hand side of the dot operator shall be of scalar type. The
2742 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002743 // type.
2744 if (!BaseType->isScalarType())
2745 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2746 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Douglas Gregora71d8192009-09-04 17:36:40 +00002748 // [...] The type designated by the pseudo-destructor-name shall be the
2749 // same as the object type.
2750 if (!MemberName.getCXXNameType()->isDependentType() &&
2751 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2752 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2753 << BaseType << MemberName.getCXXNameType()
2754 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002755
2756 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002757 // the form
2758 //
Mike Stump1eb44332009-09-09 15:08:12 +00002759 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2760 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002761 // shall designate the same scalar type.
2762 //
2763 // FIXME: DPG can't see any way to trigger this particular clause, so it
2764 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Douglas Gregora71d8192009-09-04 17:36:40 +00002766 // FIXME: We've lost the precise spelling of the type by going through
2767 // DeclarationName. Can we do better?
2768 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002769 IsArrow, OpLoc,
2770 (NestedNameSpecifier *) SS.getScopeRep(),
2771 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002772 MemberName.getCXXNameType(),
2773 MemberLoc));
2774 }
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Chris Lattnera38e6b12008-07-21 04:59:05 +00002776 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2777 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002778 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2779 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002780 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002781 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002782 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002783 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002784 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2785
Steve Naroffc70e8d92009-07-16 00:25:06 +00002786 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2787 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002788 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Steve Naroffc70e8d92009-07-16 00:25:06 +00002790 if (IV) {
2791 // If the decl being referenced had an error, return an error for this
2792 // sub-expr without emitting another error, in order to avoid cascading
2793 // error cases.
2794 if (IV->isInvalidDecl())
2795 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002796
Steve Naroffc70e8d92009-07-16 00:25:06 +00002797 // Check whether we can reference this field.
2798 if (DiagnoseUseOfDecl(IV, MemberLoc))
2799 return ExprError();
2800 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2801 IV->getAccessControl() != ObjCIvarDecl::Package) {
2802 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2803 if (ObjCMethodDecl *MD = getCurMethodDecl())
2804 ClassOfMethodDecl = MD->getClassInterface();
2805 else if (ObjCImpDecl && getCurFunctionDecl()) {
2806 // Case of a c-function declared inside an objc implementation.
2807 // FIXME: For a c-style function nested inside an objc implementation
2808 // class, there is no implementation context available, so we pass
2809 // down the context as argument to this routine. Ideally, this context
2810 // need be passed down in the AST node and somehow calculated from the
2811 // AST for a function decl.
2812 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002813 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002814 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2815 ClassOfMethodDecl = IMPD->getClassInterface();
2816 else if (ObjCCategoryImplDecl* CatImplClass =
2817 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2818 ClassOfMethodDecl = CatImplClass->getClassInterface();
2819 }
Mike Stump1eb44332009-09-09 15:08:12 +00002820
2821 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2822 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002823 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002824 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002825 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002826 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2827 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002828 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002829 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002830 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002831
2832 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2833 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002834 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002835 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002836 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002837 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002838 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002839 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002840 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002841 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002842 if (!IsArrow && (BaseType->isObjCIdType() ||
2843 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002844 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002845 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Steve Naroff14108da2009-07-10 23:34:53 +00002847 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002848 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002849 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2850 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2851 // Check the use of this declaration
2852 if (DiagnoseUseOfDecl(PD, MemberLoc))
2853 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Steve Naroff14108da2009-07-10 23:34:53 +00002855 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2856 MemberLoc, BaseExpr));
2857 }
2858 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2859 // Check the use of this method.
2860 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2861 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Steve Naroff14108da2009-07-10 23:34:53 +00002863 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002864 OMD->getResultType(),
2865 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002866 NULL, 0));
2867 }
2868 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002869
Steve Naroff14108da2009-07-10 23:34:53 +00002870 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002871 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002872 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002873 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2874 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002875 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002876 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002877 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2878 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002879 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Daniel Dunbar2307d312008-09-03 01:05:41 +00002881 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002882 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002883 // Check whether we can reference this property.
2884 if (DiagnoseUseOfDecl(PD, MemberLoc))
2885 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002886 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002887 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002888 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002889 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2890 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002891 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002892 MemberLoc, BaseExpr));
2893 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002894 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002895 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2896 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002897 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002898 // Check whether we can reference this property.
2899 if (DiagnoseUseOfDecl(PD, MemberLoc))
2900 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002901
Steve Naroff6ece14c2009-01-21 00:14:39 +00002902 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002903 MemberLoc, BaseExpr));
2904 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002905 // If that failed, look for an "implicit" property by seeing if the nullary
2906 // selector is implemented.
2907
2908 // FIXME: The logic for looking up nullary and unary selectors should be
2909 // shared with the code in ActOnInstanceMessage.
2910
Anders Carlsson8f28f992009-08-26 18:25:21 +00002911 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002912 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002913
Daniel Dunbar2307d312008-09-03 01:05:41 +00002914 // If this reference is in an @implementation, check for 'private' methods.
2915 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002916 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002917
Steve Naroff7692ed62008-10-22 19:16:27 +00002918 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002919 if (!Getter)
2920 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002921 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002922 // Check if we can reference this property.
2923 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2924 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002925 }
2926 // If we found a getter then this may be a valid dot-reference, we
2927 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002928 Selector SetterSel =
2929 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002930 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002931 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002932 if (!Setter) {
2933 // If this reference is in an @implementation, also check for 'private'
2934 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002935 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002936 }
2937 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002938 if (!Setter)
2939 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002940
Steve Naroff1ca66942009-03-11 13:48:17 +00002941 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2942 return ExprError();
2943
2944 if (Getter || Setter) {
2945 QualType PType;
2946
2947 if (Getter)
2948 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002949 else
2950 // Get the expression type from Setter's incoming parameter.
2951 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002952 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002953 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002954 Setter, MemberLoc, BaseExpr));
2955 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002956 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002957 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002958 }
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Steve Narofff242b1b2009-07-24 17:54:45 +00002960 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002961 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002962 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002963 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002964 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002965 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00002966
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002967 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002968 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002969 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002970 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2971 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002972 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002973 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002974 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002975 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002976
Douglas Gregor214f31a2009-03-27 06:00:30 +00002977 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2978 << BaseType << BaseExpr->getSourceRange();
2979
Douglas Gregor214f31a2009-03-27 06:00:30 +00002980 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002981}
2982
John McCall129e2df2009-11-30 22:42:35 +00002983static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2984 SourceLocation NameLoc,
2985 Sema::ExprArg MemExpr) {
2986 Expr *E = (Expr *) MemExpr.get();
2987 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2988 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002989 << isa<CXXPseudoDestructorExpr>(E)
2990 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2991
John McCall129e2df2009-11-30 22:42:35 +00002992 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2993 move(MemExpr),
2994 /*LPLoc*/ ExpectedLParenLoc,
2995 Sema::MultiExprArg(SemaRef, 0, 0),
2996 /*CommaLocs*/ 0,
2997 /*RPLoc*/ ExpectedLParenLoc);
2998}
2999
3000/// The main callback when the parser finds something like
3001/// expression . [nested-name-specifier] identifier
3002/// expression -> [nested-name-specifier] identifier
3003/// where 'identifier' encompasses a fairly broad spectrum of
3004/// possibilities, including destructor and operator references.
3005///
3006/// \param OpKind either tok::arrow or tok::period
3007/// \param HasTrailingLParen whether the next token is '(', which
3008/// is used to diagnose mis-uses of special members that can
3009/// only be called
3010/// \param ObjCImpDecl the current ObjC @implementation decl;
3011/// this is an ugly hack around the fact that ObjC @implementations
3012/// aren't properly put in the context chain
3013Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3014 SourceLocation OpLoc,
3015 tok::TokenKind OpKind,
3016 const CXXScopeSpec &SS,
3017 UnqualifiedId &Id,
3018 DeclPtrTy ObjCImpDecl,
3019 bool HasTrailingLParen) {
3020 if (SS.isSet() && SS.isInvalid())
3021 return ExprError();
3022
3023 TemplateArgumentListInfo TemplateArgsBuffer;
3024
3025 // Decompose the name into its component parts.
3026 DeclarationName Name;
3027 SourceLocation NameLoc;
3028 const TemplateArgumentListInfo *TemplateArgs;
3029 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3030 Name, NameLoc, TemplateArgs);
3031
3032 bool IsArrow = (OpKind == tok::arrow);
3033
3034 NamedDecl *FirstQualifierInScope
3035 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3036 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3037
3038 // This is a postfix expression, so get rid of ParenListExprs.
3039 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3040
3041 Expr *Base = BaseArg.takeAs<Expr>();
3042 OwningExprResult Result(*this);
3043 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00003044 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003045 IsArrow, OpLoc,
3046 SS, FirstQualifierInScope,
3047 Name, NameLoc,
3048 TemplateArgs);
3049 } else {
3050 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3051 if (TemplateArgs) {
3052 // Re-use the lookup done for the template name.
3053 DecomposeTemplateName(R, Id);
3054 } else {
3055 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3056 SS, FirstQualifierInScope,
3057 ObjCImpDecl);
3058
3059 if (Result.isInvalid()) {
3060 Owned(Base);
3061 return ExprError();
3062 }
3063
3064 if (Result.get()) {
3065 // The only way a reference to a destructor can be used is to
3066 // immediately call it, which falls into this case. If the
3067 // next token is not a '(', produce a diagnostic and build the
3068 // call now.
3069 if (!HasTrailingLParen &&
3070 Id.getKind() == UnqualifiedId::IK_DestructorName)
3071 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3072
3073 return move(Result);
3074 }
3075 }
3076
John McCallaa81e162009-12-01 22:10:20 +00003077 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3078 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003079 }
3080
3081 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003082}
3083
Anders Carlsson56c5e332009-08-25 03:49:14 +00003084Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3085 FunctionDecl *FD,
3086 ParmVarDecl *Param) {
3087 if (Param->hasUnparsedDefaultArg()) {
3088 Diag (CallLoc,
3089 diag::err_use_of_default_argument_to_function_declared_later) <<
3090 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003091 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003092 diag::note_default_argument_declared_here);
3093 } else {
3094 if (Param->hasUninstantiatedDefaultArg()) {
3095 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3096
3097 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003098 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003099
Mike Stump1eb44332009-09-09 15:08:12 +00003100 InstantiatingTemplate Inst(*this, CallLoc, Param,
3101 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003102 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003103
John McCallce3ff2b2009-08-25 22:02:44 +00003104 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003105 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003106 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003107
3108 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00003109 /*FIXME:EqualLoc*/
3110 UninstExpr->getSourceRange().getBegin()))
3111 return ExprError();
3112 }
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Anders Carlsson56c5e332009-08-25 03:49:14 +00003114 // If the default expression creates temporaries, we need to
3115 // push them to the current stack of expression temporaries so they'll
3116 // be properly destroyed.
Anders Carlsson337cba42009-12-15 19:16:31 +00003117 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3118 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003119 }
3120
3121 // We already type-checked the argument, so we know it works.
3122 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3123}
3124
Douglas Gregor88a35142008-12-22 05:46:06 +00003125/// ConvertArgumentsForCall - Converts the arguments specified in
3126/// Args/NumArgs to the parameter types of the function FDecl with
3127/// function prototype Proto. Call is the call expression itself, and
3128/// Fn is the function expression. For a C++ member function, this
3129/// routine does not attempt to convert the object argument. Returns
3130/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003131bool
3132Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003133 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003134 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003135 Expr **Args, unsigned NumArgs,
3136 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003137 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003138 // assignment, to the types of the corresponding parameter, ...
3139 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003140 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003141
Douglas Gregor88a35142008-12-22 05:46:06 +00003142 // If too few arguments are available (and we don't have default
3143 // arguments for the remaining parameters), don't make the call.
3144 if (NumArgs < NumArgsInProto) {
3145 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3146 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3147 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003148 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003149 }
3150
3151 // If too many are passed and not variadic, error on the extras and drop
3152 // them.
3153 if (NumArgs > NumArgsInProto) {
3154 if (!Proto->isVariadic()) {
3155 Diag(Args[NumArgsInProto]->getLocStart(),
3156 diag::err_typecheck_call_too_many_args)
3157 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3158 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3159 Args[NumArgs-1]->getLocEnd());
3160 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003161 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003162 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003163 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003164 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003165 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003166 VariadicCallType CallType =
3167 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3168 if (Fn->getType()->isBlockPointerType())
3169 CallType = VariadicBlock; // Block
3170 else if (isa<MemberExpr>(Fn))
3171 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003172 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003173 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003174 if (Invalid)
3175 return true;
3176 unsigned TotalNumArgs = AllArgs.size();
3177 for (unsigned i = 0; i < TotalNumArgs; ++i)
3178 Call->setArg(i, AllArgs[i]);
3179
3180 return false;
3181}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003182
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003183bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3184 FunctionDecl *FDecl,
3185 const FunctionProtoType *Proto,
3186 unsigned FirstProtoArg,
3187 Expr **Args, unsigned NumArgs,
3188 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003189 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003190 unsigned NumArgsInProto = Proto->getNumArgs();
3191 unsigned NumArgsToCheck = NumArgs;
3192 bool Invalid = false;
3193 if (NumArgs != NumArgsInProto)
3194 // Use default arguments for missing arguments
3195 NumArgsToCheck = NumArgsInProto;
3196 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003197 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003198 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003199 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003200
Douglas Gregor88a35142008-12-22 05:46:06 +00003201 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003202 if (ArgIx < NumArgs) {
3203 Arg = Args[ArgIx++];
3204
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003205 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3206 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003207 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003208 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003209 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003210
Douglas Gregor61366e92008-12-24 00:01:03 +00003211 // Pass the argument.
Douglas Gregor68647482009-12-16 03:45:30 +00003212 if (PerformCopyInitialization(Arg, ProtoArgType, AA_Passing))
Douglas Gregor61366e92008-12-24 00:01:03 +00003213 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003214
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003215 if (!ProtoArgType->isReferenceType())
3216 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003217 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003218 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003219
Mike Stump1eb44332009-09-09 15:08:12 +00003220 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003221 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003222 if (ArgExpr.isInvalid())
3223 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003224
Anders Carlsson56c5e332009-08-25 03:49:14 +00003225 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003226 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003227 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003228 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003229
Douglas Gregor88a35142008-12-22 05:46:06 +00003230 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003231 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003232 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003233 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003234 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003235 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003236 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003237 }
3238 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003239 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003240}
3241
Steve Narofff69936d2007-09-16 03:34:24 +00003242/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003243/// This provides the location of the left/right parens and a list of comma
3244/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003245Action::OwningExprResult
3246Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3247 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003248 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003249 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003250
3251 // Since this might be a postfix expression, get rid of ParenListExprs.
3252 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003253
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003254 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003255 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003256 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003257
Douglas Gregor88a35142008-12-22 05:46:06 +00003258 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003259 // If this is a pseudo-destructor expression, build the call immediately.
3260 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3261 if (NumArgs > 0) {
3262 // Pseudo-destructor calls should not have any arguments.
3263 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3264 << CodeModificationHint::CreateRemoval(
3265 SourceRange(Args[0]->getLocStart(),
3266 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Douglas Gregora71d8192009-09-04 17:36:40 +00003268 for (unsigned I = 0; I != NumArgs; ++I)
3269 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Douglas Gregora71d8192009-09-04 17:36:40 +00003271 NumArgs = 0;
3272 }
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Douglas Gregora71d8192009-09-04 17:36:40 +00003274 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3275 RParenLoc));
3276 }
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Douglas Gregor17330012009-02-04 15:01:18 +00003278 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003279 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003280 // FIXME: Will need to cache the results of name lookup (including ADL) in
3281 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003282 bool Dependent = false;
3283 if (Fn->isTypeDependent())
3284 Dependent = true;
3285 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3286 Dependent = true;
3287
3288 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003289 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003290 Context.DependentTy, RParenLoc));
3291
3292 // Determine whether this is a call to an object (C++ [over.call.object]).
3293 if (Fn->getType()->isRecordType())
3294 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3295 CommaLocs, RParenLoc));
3296
John McCall129e2df2009-11-30 22:42:35 +00003297 Expr *NakedFn = Fn->IgnoreParens();
3298
3299 // Determine whether this is a call to an unresolved member function.
3300 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3301 // If lookup was unresolved but not dependent (i.e. didn't find
3302 // an unresolved using declaration), it has to be an overloaded
3303 // function set, which means it must contain either multiple
3304 // declarations (all methods or method templates) or a single
3305 // method template.
3306 assert((MemE->getNumDecls() > 1) ||
3307 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003308 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003309
John McCallaa81e162009-12-01 22:10:20 +00003310 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3311 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003312 }
3313
Douglas Gregorfa047642009-02-04 00:32:51 +00003314 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003315 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003316 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003317 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003318 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3319 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003320 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003321
3322 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003323 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003324 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3325 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003326 if (const FunctionProtoType *FPT =
3327 dyn_cast<FunctionProtoType>(BO->getType())) {
3328 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003329
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003330 ExprOwningPtr<CXXMemberCallExpr>
3331 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3332 NumArgs, ResultTy,
3333 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003334
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003335 if (CheckCallReturnType(FPT->getResultType(),
3336 BO->getRHS()->getSourceRange().getBegin(),
3337 TheCall.get(), 0))
3338 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003339
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003340 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3341 RParenLoc))
3342 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003343
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003344 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3345 }
3346 return ExprError(Diag(Fn->getLocStart(),
3347 diag::err_typecheck_call_not_function)
3348 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003349 }
3350 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003351 }
3352
Douglas Gregorfa047642009-02-04 00:32:51 +00003353 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003354 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003355 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003356
John McCall3b4294e2009-12-16 12:17:52 +00003357 Expr *NakedFn = Fn->IgnoreParenCasts();
3358 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3359 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3360 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3361 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003362 }
Chris Lattner04421082008-04-08 04:40:51 +00003363
John McCall3b4294e2009-12-16 12:17:52 +00003364 NamedDecl *NDecl = 0;
3365 if (isa<DeclRefExpr>(NakedFn))
3366 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3367
John McCallaa81e162009-12-01 22:10:20 +00003368 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3369}
3370
John McCall3b4294e2009-12-16 12:17:52 +00003371/// BuildResolvedCallExpr - Build a call to a resolved expression,
3372/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003373/// unary-convert to an expression of function-pointer or
3374/// block-pointer type.
3375///
3376/// \param NDecl the declaration being called, if available
3377Sema::OwningExprResult
3378Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3379 SourceLocation LParenLoc,
3380 Expr **Args, unsigned NumArgs,
3381 SourceLocation RParenLoc) {
3382 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3383
Chris Lattner04421082008-04-08 04:40:51 +00003384 // Promote the function operand.
3385 UsualUnaryConversions(Fn);
3386
Chris Lattner925e60d2007-12-28 05:29:59 +00003387 // Make the call expr early, before semantic checks. This guarantees cleanup
3388 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003389 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3390 Args, NumArgs,
3391 Context.BoolTy,
3392 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003393
Steve Naroffdd972f22008-09-05 22:11:13 +00003394 const FunctionType *FuncT;
3395 if (!Fn->getType()->isBlockPointerType()) {
3396 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3397 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003398 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003399 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003400 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3401 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003402 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003403 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003404 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003405 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003406 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003407 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003408 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3409 << Fn->getType() << Fn->getSourceRange());
3410
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003411 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003412 if (CheckCallReturnType(FuncT->getResultType(),
3413 Fn->getSourceRange().getBegin(), TheCall.get(),
3414 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003415 return ExprError();
3416
Chris Lattner925e60d2007-12-28 05:29:59 +00003417 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003418 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003419
Douglas Gregor72564e72009-02-26 23:50:07 +00003420 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003421 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003422 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003423 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003424 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003425 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003426
Douglas Gregor74734d52009-04-02 15:37:10 +00003427 if (FDecl) {
3428 // Check if we have too few/too many template arguments, based
3429 // on our knowledge of the function definition.
3430 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003431 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003432 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003433 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003434 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3435 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3436 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3437 }
3438 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003439 }
3440
Steve Naroffb291ab62007-08-28 23:30:39 +00003441 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003442 for (unsigned i = 0; i != NumArgs; i++) {
3443 Expr *Arg = Args[i];
3444 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003445 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3446 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003447 PDiag(diag::err_call_incomplete_argument)
3448 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003449 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003450 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003451 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003452 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003453
Douglas Gregor88a35142008-12-22 05:46:06 +00003454 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3455 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003456 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3457 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003458
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003459 // Check for sentinels
3460 if (NDecl)
3461 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Chris Lattner59907c42007-08-10 20:18:51 +00003463 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003464 if (FDecl) {
3465 if (CheckFunctionCall(FDecl, TheCall.get()))
3466 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003468 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003469 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3470 } else if (NDecl) {
3471 if (CheckBlockCall(NDecl, TheCall.get()))
3472 return ExprError();
3473 }
Chris Lattner59907c42007-08-10 20:18:51 +00003474
Anders Carlssonec74c592009-08-16 03:06:32 +00003475 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003476}
3477
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003478Action::OwningExprResult
3479Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3480 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003481 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor99a2e602009-12-16 01:38:02 +00003482
3483 TypeSourceInfo *TInfo = 0;
3484 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3485 if (!TInfo)
3486 TInfo = Context.getTrivialTypeSourceInfo(literalType, LParenLoc);
3487
Steve Naroffaff1edd2007-07-19 21:32:11 +00003488 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003489 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003490 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003491
Eli Friedman6223c222008-05-20 05:22:08 +00003492 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003493 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003494 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3495 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003496 } else if (!literalType->isDependentType() &&
3497 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003498 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003499 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003500 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003501 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003502
Douglas Gregor99a2e602009-12-16 01:38:02 +00003503 InitializedEntity Entity
3504 = InitializedEntity::InitializeTemporary(TInfo->getTypeLoc());
3505 InitializationKind Kind
3506 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3507 /*IsCStyleCast=*/true);
3508 if (CheckInitializerTypes(literalExpr, literalType, Entity, Kind))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003509 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003510
Chris Lattner371f2582008-12-04 23:50:19 +00003511 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003512 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003513 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003514 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003515 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003516 InitExpr.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003517
3518 // FIXME: Store the TInfo to preserve type information better.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003519 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003520 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003521}
3522
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003523Action::OwningExprResult
3524Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003525 SourceLocation RBraceLoc) {
3526 unsigned NumInit = initlist.size();
3527 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003528
Steve Naroff08d92e42007-09-15 18:49:24 +00003529 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003530 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003531
Mike Stumpeed9cac2009-02-19 03:04:26 +00003532 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003533 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003534 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003535 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003536}
3537
Anders Carlsson82debc72009-10-18 18:12:03 +00003538static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3539 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003540 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003541 return CastExpr::CK_NoOp;
3542
3543 if (SrcTy->hasPointerRepresentation()) {
3544 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003545 return DestTy->isObjCObjectPointerType() ?
3546 CastExpr::CK_AnyPointerToObjCPointerCast :
3547 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003548 if (DestTy->isIntegerType())
3549 return CastExpr::CK_PointerToIntegral;
3550 }
3551
3552 if (SrcTy->isIntegerType()) {
3553 if (DestTy->isIntegerType())
3554 return CastExpr::CK_IntegralCast;
3555 if (DestTy->hasPointerRepresentation())
3556 return CastExpr::CK_IntegralToPointer;
3557 if (DestTy->isRealFloatingType())
3558 return CastExpr::CK_IntegralToFloating;
3559 }
3560
3561 if (SrcTy->isRealFloatingType()) {
3562 if (DestTy->isRealFloatingType())
3563 return CastExpr::CK_FloatingCast;
3564 if (DestTy->isIntegerType())
3565 return CastExpr::CK_FloatingToIntegral;
3566 }
3567
3568 // FIXME: Assert here.
3569 // assert(false && "Unhandled cast combination!");
3570 return CastExpr::CK_Unknown;
3571}
3572
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003573/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003574bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003575 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003576 CXXMethodDecl *& ConversionDecl,
3577 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003578 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003579 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3580 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003581
Eli Friedman199ea952009-08-15 19:02:19 +00003582 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003583
3584 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3585 // type needs to be scalar.
3586 if (castType->isVoidType()) {
3587 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003588 Kind = CastExpr::CK_ToVoid;
3589 return false;
3590 }
3591
3592 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003593 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003594 (castType->isStructureType() || castType->isUnionType())) {
3595 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003596 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003597 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3598 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003599 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003600 return false;
3601 }
3602
3603 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003604 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003605 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003606 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003607 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003608 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003609 if (Context.hasSameUnqualifiedType(Field->getType(),
3610 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003611 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3612 << castExpr->getSourceRange();
3613 break;
3614 }
3615 }
3616 if (Field == FieldEnd)
3617 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3618 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003619 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003620 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003621 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003622
3623 // Reject any other conversions to non-scalar types.
3624 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3625 << castType << castExpr->getSourceRange();
3626 }
3627
3628 if (!castExpr->getType()->isScalarType() &&
3629 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003630 return Diag(castExpr->getLocStart(),
3631 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003632 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003633 }
3634
Anders Carlsson16a89042009-10-16 05:23:41 +00003635 if (castType->isExtVectorType())
3636 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3637
Anders Carlssonc3516322009-10-16 02:48:28 +00003638 if (castType->isVectorType())
3639 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3640 if (castExpr->getType()->isVectorType())
3641 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3642
3643 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003644 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003645
Anders Carlsson16a89042009-10-16 05:23:41 +00003646 if (isa<ObjCSelectorExpr>(castExpr))
3647 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3648
Anders Carlssonc3516322009-10-16 02:48:28 +00003649 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003650 QualType castExprType = castExpr->getType();
3651 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3652 return Diag(castExpr->getLocStart(),
3653 diag::err_cast_pointer_from_non_pointer_int)
3654 << castExprType << castExpr->getSourceRange();
3655 } else if (!castExpr->getType()->isArithmeticType()) {
3656 if (!castType->isIntegralType() && castType->isArithmeticType())
3657 return Diag(castExpr->getLocStart(),
3658 diag::err_cast_pointer_to_non_pointer_int)
3659 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003660 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003661
3662 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003663 return false;
3664}
3665
Anders Carlssonc3516322009-10-16 02:48:28 +00003666bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3667 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003668 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003669
Anders Carlssona64db8f2007-11-27 05:51:55 +00003670 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003671 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003672 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003673 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003674 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003675 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003676 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003677 } else
3678 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003679 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003680 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003681
Anders Carlssonc3516322009-10-16 02:48:28 +00003682 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003683 return false;
3684}
3685
Anders Carlsson16a89042009-10-16 05:23:41 +00003686bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3687 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003688 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003689
3690 QualType SrcTy = CastExpr->getType();
3691
Nate Begeman9b10da62009-06-27 22:05:55 +00003692 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3693 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003694 if (SrcTy->isVectorType()) {
3695 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3696 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3697 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003698 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003699 return false;
3700 }
3701
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003702 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003703 // conversion will take place first from scalar to elt type, and then
3704 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003705 if (SrcTy->isPointerType())
3706 return Diag(R.getBegin(),
3707 diag::err_invalid_conversion_between_vector_and_scalar)
3708 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003709
3710 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3711 ImpCastExprToType(CastExpr, DestElemTy,
3712 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003713
3714 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003715 return false;
3716}
3717
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003718Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003719Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003720 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003721 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003723 assert((Ty != 0) && (Op.get() != 0) &&
3724 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003725
Nate Begeman2ef13e52009-08-10 23:49:36 +00003726 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003727 //FIXME: Preserve type source info.
3728 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003729
Nate Begeman2ef13e52009-08-10 23:49:36 +00003730 // If the Expr being casted is a ParenListExpr, handle it specially.
3731 if (isa<ParenListExpr>(castExpr))
3732 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003733 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003734 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003735 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003736 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003737
3738 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003739 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003740 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003741
Anders Carlsson0aebc812009-09-09 21:33:21 +00003742 if (CastArg.isInvalid())
3743 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003744
Anders Carlsson0aebc812009-09-09 21:33:21 +00003745 castExpr = CastArg.takeAs<Expr>();
3746 } else {
3747 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003748 }
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003750 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003751 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003752 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003753}
3754
Nate Begeman2ef13e52009-08-10 23:49:36 +00003755/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3756/// of comma binary operators.
3757Action::OwningExprResult
3758Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3759 Expr *expr = EA.takeAs<Expr>();
3760 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3761 if (!E)
3762 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Nate Begeman2ef13e52009-08-10 23:49:36 +00003764 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003765
Nate Begeman2ef13e52009-08-10 23:49:36 +00003766 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3767 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3768 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Nate Begeman2ef13e52009-08-10 23:49:36 +00003770 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3771}
3772
3773Action::OwningExprResult
3774Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3775 SourceLocation RParenLoc, ExprArg Op,
3776 QualType Ty) {
3777 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003778
3779 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003780 // then handle it as such.
3781 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3782 if (PE->getNumExprs() == 0) {
3783 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3784 return ExprError();
3785 }
3786
3787 llvm::SmallVector<Expr *, 8> initExprs;
3788 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3789 initExprs.push_back(PE->getExpr(i));
3790
3791 // FIXME: This means that pretty-printing the final AST will produce curly
3792 // braces instead of the original commas.
3793 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003794 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003795 initExprs.size(), RParenLoc);
3796 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003797 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003798 Owned(E));
3799 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003800 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003801 // sequence of BinOp comma operators.
3802 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3803 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3804 }
3805}
3806
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003807Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003808 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003809 MultiExprArg Val,
3810 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003811 unsigned nexprs = Val.size();
3812 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003813 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3814 Expr *expr;
3815 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3816 expr = new (Context) ParenExpr(L, R, exprs[0]);
3817 else
3818 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003819 return Owned(expr);
3820}
3821
Sebastian Redl28507842009-02-26 14:39:58 +00003822/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3823/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003824/// C99 6.5.15
3825QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3826 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003827 // C++ is sufficiently different to merit its own checker.
3828 if (getLangOptions().CPlusPlus)
3829 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3830
John McCallb13c87f2009-11-05 09:23:39 +00003831 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3832
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003833 UsualUnaryConversions(Cond);
3834 UsualUnaryConversions(LHS);
3835 UsualUnaryConversions(RHS);
3836 QualType CondTy = Cond->getType();
3837 QualType LHSTy = LHS->getType();
3838 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003839
Reid Spencer5f016e22007-07-11 17:01:13 +00003840 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003841 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3842 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3843 << CondTy;
3844 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003845 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003846
Chris Lattner70d67a92008-01-06 22:42:25 +00003847 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003848 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3849 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003850
Chris Lattner70d67a92008-01-06 22:42:25 +00003851 // If both operands have arithmetic type, do the usual arithmetic conversions
3852 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003853 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3854 UsualArithmeticConversions(LHS, RHS);
3855 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003856 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003857
Chris Lattner70d67a92008-01-06 22:42:25 +00003858 // If both operands are the same structure or union type, the result is that
3859 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003860 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3861 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003862 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003863 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003864 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003865 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003866 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003867 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003868
Chris Lattner70d67a92008-01-06 22:42:25 +00003869 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003870 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003871 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3872 if (!LHSTy->isVoidType())
3873 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3874 << RHS->getSourceRange();
3875 if (!RHSTy->isVoidType())
3876 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3877 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003878 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3879 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003880 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003881 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003882 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3883 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003884 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003885 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003886 // promote the null to a pointer.
3887 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003888 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003889 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003890 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003891 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003892 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003893 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003894 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003895
3896 // All objective-c pointer type analysis is done here.
3897 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3898 QuestionLoc);
3899 if (!compositeType.isNull())
3900 return compositeType;
3901
3902
Steve Naroff7154a772009-07-01 14:36:47 +00003903 // Handle block pointer types.
3904 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3905 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3906 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3907 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003908 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3909 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003910 return destType;
3911 }
3912 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003913 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00003914 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003915 }
Steve Naroff7154a772009-07-01 14:36:47 +00003916 // We have 2 block pointer types.
3917 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3918 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003919 return LHSTy;
3920 }
Steve Naroff7154a772009-07-01 14:36:47 +00003921 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003922 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3923 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003924
Steve Naroff7154a772009-07-01 14:36:47 +00003925 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3926 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003927 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003928 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003929 // In this situation, we assume void* type. No especially good
3930 // reason, but this is what gcc does, and we do have to pick
3931 // to get a consistent AST.
3932 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003933 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3934 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003935 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003936 }
Steve Naroff7154a772009-07-01 14:36:47 +00003937 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003938 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3939 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003940 return LHSTy;
3941 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003942
Steve Naroff7154a772009-07-01 14:36:47 +00003943 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3944 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3945 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003946 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3947 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003948
3949 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3950 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3951 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003952 QualType destPointee
3953 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003954 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003955 // Add qualifiers if necessary.
3956 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3957 // Promote to void*.
3958 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003959 return destType;
3960 }
3961 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003962 QualType destPointee
3963 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003964 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003965 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003966 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003967 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003968 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003969 return destType;
3970 }
3971
3972 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3973 // Two identical pointer types are always compatible.
3974 return LHSTy;
3975 }
3976 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3977 rhptee.getUnqualifiedType())) {
3978 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3979 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3980 // In this situation, we assume void* type. No especially good
3981 // reason, but this is what gcc does, and we do have to pick
3982 // to get a consistent AST.
3983 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003984 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3985 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003986 return incompatTy;
3987 }
3988 // The pointer types are compatible.
3989 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3990 // differently qualified versions of compatible types, the result type is
3991 // a pointer to an appropriately qualified version of the *composite*
3992 // type.
3993 // FIXME: Need to calculate the composite type.
3994 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003995 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3996 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003997 return LHSTy;
3998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Steve Naroff7154a772009-07-01 14:36:47 +00004000 // GCC compatibility: soften pointer/integer mismatch.
4001 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4002 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4003 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004004 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004005 return RHSTy;
4006 }
4007 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4008 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4009 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004010 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004011 return LHSTy;
4012 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004013
Chris Lattner70d67a92008-01-06 22:42:25 +00004014 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004015 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4016 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004017 return QualType();
4018}
4019
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004020/// FindCompositeObjCPointerType - Helper method to find composite type of
4021/// two objective-c pointer types of the two input expressions.
4022QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4023 SourceLocation QuestionLoc) {
4024 QualType LHSTy = LHS->getType();
4025 QualType RHSTy = RHS->getType();
4026
4027 // Handle things like Class and struct objc_class*. Here we case the result
4028 // to the pseudo-builtin, because that will be implicitly cast back to the
4029 // redefinition type if an attempt is made to access its fields.
4030 if (LHSTy->isObjCClassType() &&
4031 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4032 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4033 return LHSTy;
4034 }
4035 if (RHSTy->isObjCClassType() &&
4036 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4037 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4038 return RHSTy;
4039 }
4040 // And the same for struct objc_object* / id
4041 if (LHSTy->isObjCIdType() &&
4042 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4043 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4044 return LHSTy;
4045 }
4046 if (RHSTy->isObjCIdType() &&
4047 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4048 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4049 return RHSTy;
4050 }
4051 // And the same for struct objc_selector* / SEL
4052 if (Context.isObjCSelType(LHSTy) &&
4053 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4054 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4055 return LHSTy;
4056 }
4057 if (Context.isObjCSelType(RHSTy) &&
4058 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4059 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4060 return RHSTy;
4061 }
4062 // Check constraints for Objective-C object pointers types.
4063 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4064
4065 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4066 // Two identical object pointer types are always compatible.
4067 return LHSTy;
4068 }
4069 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4070 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4071 QualType compositeType = LHSTy;
4072
4073 // If both operands are interfaces and either operand can be
4074 // assigned to the other, use that type as the composite
4075 // type. This allows
4076 // xxx ? (A*) a : (B*) b
4077 // where B is a subclass of A.
4078 //
4079 // Additionally, as for assignment, if either type is 'id'
4080 // allow silent coercion. Finally, if the types are
4081 // incompatible then make sure to use 'id' as the composite
4082 // type so the result is acceptable for sending messages to.
4083
4084 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4085 // It could return the composite type.
4086 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4087 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4088 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4089 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4090 } else if ((LHSTy->isObjCQualifiedIdType() ||
4091 RHSTy->isObjCQualifiedIdType()) &&
4092 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4093 // Need to handle "id<xx>" explicitly.
4094 // GCC allows qualified id and any Objective-C type to devolve to
4095 // id. Currently localizing to here until clear this should be
4096 // part of ObjCQualifiedIdTypesAreCompatible.
4097 compositeType = Context.getObjCIdType();
4098 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4099 compositeType = Context.getObjCIdType();
4100 } else if (!(compositeType =
4101 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4102 ;
4103 else {
4104 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4105 << LHSTy << RHSTy
4106 << LHS->getSourceRange() << RHS->getSourceRange();
4107 QualType incompatTy = Context.getObjCIdType();
4108 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4109 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4110 return incompatTy;
4111 }
4112 // The object pointer types are compatible.
4113 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4114 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4115 return compositeType;
4116 }
4117 // Check Objective-C object pointer types and 'void *'
4118 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4119 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4120 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4121 QualType destPointee
4122 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4123 QualType destType = Context.getPointerType(destPointee);
4124 // Add qualifiers if necessary.
4125 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4126 // Promote to void*.
4127 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4128 return destType;
4129 }
4130 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4131 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4132 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4133 QualType destPointee
4134 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4135 QualType destType = Context.getPointerType(destPointee);
4136 // Add qualifiers if necessary.
4137 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4138 // Promote to void*.
4139 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4140 return destType;
4141 }
4142 return QualType();
4143}
4144
Steve Narofff69936d2007-09-16 03:34:24 +00004145/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004146/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004147Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4148 SourceLocation ColonLoc,
4149 ExprArg Cond, ExprArg LHS,
4150 ExprArg RHS) {
4151 Expr *CondExpr = (Expr *) Cond.get();
4152 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004153
4154 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4155 // was the condition.
4156 bool isLHSNull = LHSExpr == 0;
4157 if (isLHSNull)
4158 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004159
4160 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004161 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004162 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004163 return ExprError();
4164
4165 Cond.release();
4166 LHS.release();
4167 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004168 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004169 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004170 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004171}
4172
Reid Spencer5f016e22007-07-11 17:01:13 +00004173// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004174// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004175// routine is it effectively iqnores the qualifiers on the top level pointee.
4176// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4177// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004178Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004179Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4180 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004181
David Chisnall0f436562009-08-17 16:35:33 +00004182 if ((lhsType->isObjCClassType() &&
4183 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4184 (rhsType->isObjCClassType() &&
4185 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4186 return Compatible;
4187 }
4188
Reid Spencer5f016e22007-07-11 17:01:13 +00004189 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004190 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4191 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004192
Reid Spencer5f016e22007-07-11 17:01:13 +00004193 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004194 lhptee = Context.getCanonicalType(lhptee);
4195 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004196
Chris Lattner5cf216b2008-01-04 18:04:52 +00004197 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004198
4199 // C99 6.5.16.1p1: This following citation is common to constraints
4200 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4201 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004202 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004203 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004204 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004205
Mike Stumpeed9cac2009-02-19 03:04:26 +00004206 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4207 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004208 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004209 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004210 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004211 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004212
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004213 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004214 assert(rhptee->isFunctionType());
4215 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004216 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004217
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004218 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004219 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004220 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004221
4222 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004223 assert(lhptee->isFunctionType());
4224 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004225 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004226 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004227 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004228 lhptee = lhptee.getUnqualifiedType();
4229 rhptee = rhptee.getUnqualifiedType();
4230 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4231 // Check if the pointee types are compatible ignoring the sign.
4232 // We explicitly check for char so that we catch "char" vs
4233 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004234 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004235 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004236 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004237 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004238
4239 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004240 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004241 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004242 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004243
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004244 if (lhptee == rhptee) {
4245 // Types are compatible ignoring the sign. Qualifier incompatibility
4246 // takes priority over sign incompatibility because the sign
4247 // warning can be disabled.
4248 if (ConvTy != Compatible)
4249 return ConvTy;
4250 return IncompatiblePointerSign;
4251 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004252
4253 // If we are a multi-level pointer, it's possible that our issue is simply
4254 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4255 // the eventual target type is the same and the pointers have the same
4256 // level of indirection, this must be the issue.
4257 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4258 do {
4259 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4260 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4261
4262 lhptee = Context.getCanonicalType(lhptee);
4263 rhptee = Context.getCanonicalType(rhptee);
4264 } while (lhptee->isPointerType() && rhptee->isPointerType());
4265
Douglas Gregora4923eb2009-11-16 21:35:15 +00004266 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004267 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004268 }
4269
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004270 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004271 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004272 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004273 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004274}
4275
Steve Naroff1c7d0672008-09-04 15:10:53 +00004276/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4277/// block pointer types are compatible or whether a block and normal pointer
4278/// are compatible. It is more restrict than comparing two function pointer
4279// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004280Sema::AssignConvertType
4281Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004282 QualType rhsType) {
4283 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004284
Steve Naroff1c7d0672008-09-04 15:10:53 +00004285 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004286 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4287 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004288
Steve Naroff1c7d0672008-09-04 15:10:53 +00004289 // make sure we operate on the canonical type
4290 lhptee = Context.getCanonicalType(lhptee);
4291 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004292
Steve Naroff1c7d0672008-09-04 15:10:53 +00004293 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004294
Steve Naroff1c7d0672008-09-04 15:10:53 +00004295 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004296 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004297 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004298
Eli Friedman26784c12009-06-08 05:08:54 +00004299 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004300 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004301 return ConvTy;
4302}
4303
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004304/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4305/// for assignment compatibility.
4306Sema::AssignConvertType
4307Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4308 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4309 return Compatible;
4310 QualType lhptee =
4311 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4312 QualType rhptee =
4313 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4314 // make sure we operate on the canonical type
4315 lhptee = Context.getCanonicalType(lhptee);
4316 rhptee = Context.getCanonicalType(rhptee);
4317 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4318 return CompatiblePointerDiscardsQualifiers;
4319
4320 if (Context.typesAreCompatible(lhsType, rhsType))
4321 return Compatible;
4322 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4323 return IncompatibleObjCQualifiedId;
4324 return IncompatiblePointer;
4325}
4326
Mike Stumpeed9cac2009-02-19 03:04:26 +00004327/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4328/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004329/// pointers. Here are some objectionable examples that GCC considers warnings:
4330///
4331/// int a, *pint;
4332/// short *pshort;
4333/// struct foo *pfoo;
4334///
4335/// pint = pshort; // warning: assignment from incompatible pointer type
4336/// a = pint; // warning: assignment makes integer from pointer without a cast
4337/// pint = a; // warning: assignment makes pointer from integer without a cast
4338/// pint = pfoo; // warning: assignment from incompatible pointer type
4339///
4340/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004341/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004342///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004343Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004344Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004345 // Get canonical types. We're not formatting these types, just comparing
4346 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004347 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4348 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004349
4350 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004351 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004352
David Chisnall0f436562009-08-17 16:35:33 +00004353 if ((lhsType->isObjCClassType() &&
4354 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4355 (rhsType->isObjCClassType() &&
4356 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4357 return Compatible;
4358 }
4359
Douglas Gregor9d293df2008-10-28 00:22:11 +00004360 // If the left-hand side is a reference type, then we are in a
4361 // (rare!) case where we've allowed the use of references in C,
4362 // e.g., as a parameter type in a built-in function. In this case,
4363 // just make sure that the type referenced is compatible with the
4364 // right-hand side type. The caller is responsible for adjusting
4365 // lhsType so that the resulting expression does not have reference
4366 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004367 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004368 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004369 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004370 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004371 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004372 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4373 // to the same ExtVector type.
4374 if (lhsType->isExtVectorType()) {
4375 if (rhsType->isExtVectorType())
4376 return lhsType == rhsType ? Compatible : Incompatible;
4377 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4378 return Compatible;
4379 }
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Nate Begemanbe2341d2008-07-14 18:02:46 +00004381 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004382 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004383 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004384 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004385 if (getLangOptions().LaxVectorConversions &&
4386 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004387 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004388 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004389 }
4390 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004391 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004392
Chris Lattnere8b3e962008-01-04 23:32:24 +00004393 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004394 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004395
Chris Lattner78eca282008-04-07 06:49:41 +00004396 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004397 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004398 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004399
Chris Lattner78eca282008-04-07 06:49:41 +00004400 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004401 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004402
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004403 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004404 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004405 if (lhsType->isVoidPointerType()) // an exception to the rule.
4406 return Compatible;
4407 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004408 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004409 if (rhsType->getAs<BlockPointerType>()) {
4410 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004411 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004412
4413 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004414 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004415 return Compatible;
4416 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004417 return Incompatible;
4418 }
4419
4420 if (isa<BlockPointerType>(lhsType)) {
4421 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004422 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004423
Steve Naroffb4406862008-09-29 18:10:17 +00004424 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004425 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004426 return Compatible;
4427
Steve Naroff1c7d0672008-09-04 15:10:53 +00004428 if (rhsType->isBlockPointerType())
4429 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004430
Ted Kremenek6217b802009-07-29 21:53:49 +00004431 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004432 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004433 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004434 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004435 return Incompatible;
4436 }
4437
Steve Naroff14108da2009-07-10 23:34:53 +00004438 if (isa<ObjCObjectPointerType>(lhsType)) {
4439 if (rhsType->isIntegerType())
4440 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004442 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004443 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004444 if (rhsType->isVoidPointerType()) // an exception to the rule.
4445 return Compatible;
4446 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004447 }
4448 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004449 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004450 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004451 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004452 if (RHSPT->getPointeeType()->isVoidType())
4453 return Compatible;
4454 }
4455 // Treat block pointers as objects.
4456 if (rhsType->isBlockPointerType())
4457 return Compatible;
4458 return Incompatible;
4459 }
Chris Lattner78eca282008-04-07 06:49:41 +00004460 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004461 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004462 if (lhsType == Context.BoolTy)
4463 return Compatible;
4464
4465 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004466 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004467
Mike Stumpeed9cac2009-02-19 03:04:26 +00004468 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004469 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004470
4471 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004472 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004473 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004474 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004475 }
Steve Naroff14108da2009-07-10 23:34:53 +00004476 if (isa<ObjCObjectPointerType>(rhsType)) {
4477 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4478 if (lhsType == Context.BoolTy)
4479 return Compatible;
4480
4481 if (lhsType->isIntegerType())
4482 return PointerToInt;
4483
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004484 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004485 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004486 if (lhsType->isVoidPointerType()) // an exception to the rule.
4487 return Compatible;
4488 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004489 }
4490 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004491 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004492 return Compatible;
4493 return Incompatible;
4494 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004495
Chris Lattnerfc144e22008-01-04 23:18:45 +00004496 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004497 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004498 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004499 }
4500 return Incompatible;
4501}
4502
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004503/// \brief Constructs a transparent union from an expression that is
4504/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004505static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004506 QualType UnionType, FieldDecl *Field) {
4507 // Build an initializer list that designates the appropriate member
4508 // of the transparent union.
4509 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4510 &E, 1,
4511 SourceLocation());
4512 Initializer->setType(UnionType);
4513 Initializer->setInitializedFieldInUnion(Field);
4514
4515 // Build a compound literal constructing a value of the transparent
4516 // union type from this initializer list.
4517 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4518 false);
4519}
4520
4521Sema::AssignConvertType
4522Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4523 QualType FromType = rExpr->getType();
4524
Mike Stump1eb44332009-09-09 15:08:12 +00004525 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004526 // transparent_union GCC extension.
4527 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004528 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004529 return Incompatible;
4530
4531 // The field to initialize within the transparent union.
4532 RecordDecl *UD = UT->getDecl();
4533 FieldDecl *InitField = 0;
4534 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004535 for (RecordDecl::field_iterator it = UD->field_begin(),
4536 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004537 it != itend; ++it) {
4538 if (it->getType()->isPointerType()) {
4539 // If the transparent union contains a pointer type, we allow:
4540 // 1) void pointer
4541 // 2) null pointer constant
4542 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004543 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004544 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004545 InitField = *it;
4546 break;
4547 }
Mike Stump1eb44332009-09-09 15:08:12 +00004548
Douglas Gregorce940492009-09-25 04:25:58 +00004549 if (rExpr->isNullPointerConstant(Context,
4550 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004551 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004552 InitField = *it;
4553 break;
4554 }
4555 }
4556
4557 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4558 == Compatible) {
4559 InitField = *it;
4560 break;
4561 }
4562 }
4563
4564 if (!InitField)
4565 return Incompatible;
4566
4567 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4568 return Compatible;
4569}
4570
Chris Lattner5cf216b2008-01-04 18:04:52 +00004571Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004572Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004573 if (getLangOptions().CPlusPlus) {
4574 if (!lhsType->isRecordType()) {
4575 // C++ 5.17p3: If the left operand is not of class type, the
4576 // expression is implicitly converted (C++ 4) to the
4577 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004578 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004579 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004580 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004581 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004582 }
4583
4584 // FIXME: Currently, we fall through and treat C++ classes like C
4585 // structures.
4586 }
4587
Steve Naroff529a4ad2007-11-27 17:58:44 +00004588 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4589 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004590 if ((lhsType->isPointerType() ||
4591 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004592 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004593 && rExpr->isNullPointerConstant(Context,
4594 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004595 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004596 return Compatible;
4597 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004598
Chris Lattner943140e2007-10-16 02:55:40 +00004599 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004600 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004601 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004602 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004603 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004604 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004605 if (!lhsType->isReferenceType())
4606 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004607
Chris Lattner5cf216b2008-01-04 18:04:52 +00004608 Sema::AssignConvertType result =
4609 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004610
Steve Narofff1120de2007-08-24 22:33:52 +00004611 // C99 6.5.16.1p2: The value of the right operand is converted to the
4612 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004613 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4614 // so that we can use references in built-in functions even in C.
4615 // The getNonReferenceType() call makes sure that the resulting expression
4616 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004617 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004618 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4619 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004620 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004621}
4622
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004623QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004624 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004625 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004626 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004627 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004628}
4629
Mike Stumpeed9cac2009-02-19 03:04:26 +00004630inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004631 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004632 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004633 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004634 QualType lhsType =
4635 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4636 QualType rhsType =
4637 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004638
Nate Begemanbe2341d2008-07-14 18:02:46 +00004639 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004640 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004641 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004642
Nate Begemanbe2341d2008-07-14 18:02:46 +00004643 // Handle the case of a vector & extvector type of the same size and element
4644 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004645 if (getLangOptions().LaxVectorConversions) {
4646 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004647 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4648 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004649 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004650 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004651 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004652 }
4653 }
4654 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004655
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004656 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4657 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4658 bool swapped = false;
4659 if (rhsType->isExtVectorType()) {
4660 swapped = true;
4661 std::swap(rex, lex);
4662 std::swap(rhsType, lhsType);
4663 }
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Nate Begemandde25982009-06-28 19:12:57 +00004665 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004666 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004667 QualType EltTy = LV->getElementType();
4668 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4669 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004670 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004671 if (swapped) std::swap(rex, lex);
4672 return lhsType;
4673 }
4674 }
4675 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4676 rhsType->isRealFloatingType()) {
4677 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004678 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004679 if (swapped) std::swap(rex, lex);
4680 return lhsType;
4681 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004682 }
4683 }
Mike Stump1eb44332009-09-09 15:08:12 +00004684
Nate Begemandde25982009-06-28 19:12:57 +00004685 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004686 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004687 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004688 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004689 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004690}
4691
Reid Spencer5f016e22007-07-11 17:01:13 +00004692inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004693 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004694 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004695 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004696
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004697 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004698
Steve Naroffa4332e22007-07-17 00:58:39 +00004699 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004700 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004701 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004702}
4703
4704inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004705 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004706 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4707 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4708 return CheckVectorOperands(Loc, lex, rex);
4709 return InvalidOperands(Loc, lex, rex);
4710 }
Steve Naroff90045e82007-07-13 23:32:42 +00004711
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004712 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004713
Steve Naroffa4332e22007-07-17 00:58:39 +00004714 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004715 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004716 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004717}
4718
4719inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004720 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004721 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4722 QualType compType = CheckVectorOperands(Loc, lex, rex);
4723 if (CompLHSTy) *CompLHSTy = compType;
4724 return compType;
4725 }
Steve Naroff49b45262007-07-13 16:58:59 +00004726
Eli Friedmanab3a8522009-03-28 01:22:36 +00004727 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004728
Reid Spencer5f016e22007-07-11 17:01:13 +00004729 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004730 if (lex->getType()->isArithmeticType() &&
4731 rex->getType()->isArithmeticType()) {
4732 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004733 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004734 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004735
Eli Friedmand72d16e2008-05-18 18:08:51 +00004736 // Put any potential pointer into PExp
4737 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004738 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004739 std::swap(PExp, IExp);
4740
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004741 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Eli Friedmand72d16e2008-05-18 18:08:51 +00004743 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004744 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Chris Lattnerb5f15622009-04-24 23:50:08 +00004746 // Check for arithmetic on pointers to incomplete types.
4747 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004748 if (getLangOptions().CPlusPlus) {
4749 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004750 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004751 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004752 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004753
4754 // GNU extension: arithmetic on pointer to void
4755 Diag(Loc, diag::ext_gnu_void_ptr)
4756 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004757 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004758 if (getLangOptions().CPlusPlus) {
4759 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4760 << lex->getType() << lex->getSourceRange();
4761 return QualType();
4762 }
4763
4764 // GNU extension: arithmetic on pointer to function
4765 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4766 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004767 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004768 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004769 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004770 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004771 PExp->getType()->isObjCObjectPointerType()) &&
4772 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004773 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4774 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004775 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004776 return QualType();
4777 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004778 // Diagnose bad cases where we step over interface counts.
4779 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4780 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4781 << PointeeTy << PExp->getSourceRange();
4782 return QualType();
4783 }
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Eli Friedmanab3a8522009-03-28 01:22:36 +00004785 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004786 QualType LHSTy = Context.isPromotableBitField(lex);
4787 if (LHSTy.isNull()) {
4788 LHSTy = lex->getType();
4789 if (LHSTy->isPromotableIntegerType())
4790 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004791 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004792 *CompLHSTy = LHSTy;
4793 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004794 return PExp->getType();
4795 }
4796 }
4797
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004798 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004799}
4800
Chris Lattnereca7be62008-04-07 05:30:13 +00004801// C99 6.5.6
4802QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004803 SourceLocation Loc, QualType* CompLHSTy) {
4804 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4805 QualType compType = CheckVectorOperands(Loc, lex, rex);
4806 if (CompLHSTy) *CompLHSTy = compType;
4807 return compType;
4808 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004809
Eli Friedmanab3a8522009-03-28 01:22:36 +00004810 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004811
Chris Lattner6e4ab612007-12-09 21:53:25 +00004812 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004813
Chris Lattner6e4ab612007-12-09 21:53:25 +00004814 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004815 if (lex->getType()->isArithmeticType()
4816 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004817 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004818 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004819 }
Mike Stump1eb44332009-09-09 15:08:12 +00004820
Chris Lattner6e4ab612007-12-09 21:53:25 +00004821 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004822 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004823 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004824
Douglas Gregore7450f52009-03-24 19:52:54 +00004825 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004826
Douglas Gregore7450f52009-03-24 19:52:54 +00004827 bool ComplainAboutVoid = false;
4828 Expr *ComplainAboutFunc = 0;
4829 if (lpointee->isVoidType()) {
4830 if (getLangOptions().CPlusPlus) {
4831 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4832 << lex->getSourceRange() << rex->getSourceRange();
4833 return QualType();
4834 }
4835
4836 // GNU C extension: arithmetic on pointer to void
4837 ComplainAboutVoid = true;
4838 } else if (lpointee->isFunctionType()) {
4839 if (getLangOptions().CPlusPlus) {
4840 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004841 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004842 return QualType();
4843 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004844
4845 // GNU C extension: arithmetic on pointer to function
4846 ComplainAboutFunc = lex;
4847 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004848 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004849 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004850 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004851 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004852 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004853
Chris Lattnerb5f15622009-04-24 23:50:08 +00004854 // Diagnose bad cases where we step over interface counts.
4855 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4856 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4857 << lpointee << lex->getSourceRange();
4858 return QualType();
4859 }
Mike Stump1eb44332009-09-09 15:08:12 +00004860
Chris Lattner6e4ab612007-12-09 21:53:25 +00004861 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004862 if (rex->getType()->isIntegerType()) {
4863 if (ComplainAboutVoid)
4864 Diag(Loc, diag::ext_gnu_void_ptr)
4865 << lex->getSourceRange() << rex->getSourceRange();
4866 if (ComplainAboutFunc)
4867 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004868 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004869 << ComplainAboutFunc->getSourceRange();
4870
Eli Friedmanab3a8522009-03-28 01:22:36 +00004871 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004872 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004873 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004874
Chris Lattner6e4ab612007-12-09 21:53:25 +00004875 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004876 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004877 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004878
Douglas Gregore7450f52009-03-24 19:52:54 +00004879 // RHS must be a completely-type object type.
4880 // Handle the GNU void* extension.
4881 if (rpointee->isVoidType()) {
4882 if (getLangOptions().CPlusPlus) {
4883 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4884 << lex->getSourceRange() << rex->getSourceRange();
4885 return QualType();
4886 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004887
Douglas Gregore7450f52009-03-24 19:52:54 +00004888 ComplainAboutVoid = true;
4889 } else if (rpointee->isFunctionType()) {
4890 if (getLangOptions().CPlusPlus) {
4891 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004892 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004893 return QualType();
4894 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004895
4896 // GNU extension: arithmetic on pointer to function
4897 if (!ComplainAboutFunc)
4898 ComplainAboutFunc = rex;
4899 } else if (!rpointee->isDependentType() &&
4900 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004901 PDiag(diag::err_typecheck_sub_ptr_object)
4902 << rex->getSourceRange()
4903 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004904 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004905
Eli Friedman88d936b2009-05-16 13:54:38 +00004906 if (getLangOptions().CPlusPlus) {
4907 // Pointee types must be the same: C++ [expr.add]
4908 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4909 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4910 << lex->getType() << rex->getType()
4911 << lex->getSourceRange() << rex->getSourceRange();
4912 return QualType();
4913 }
4914 } else {
4915 // Pointee types must be compatible C99 6.5.6p3
4916 if (!Context.typesAreCompatible(
4917 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4918 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4919 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4920 << lex->getType() << rex->getType()
4921 << lex->getSourceRange() << rex->getSourceRange();
4922 return QualType();
4923 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004924 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004925
Douglas Gregore7450f52009-03-24 19:52:54 +00004926 if (ComplainAboutVoid)
4927 Diag(Loc, diag::ext_gnu_void_ptr)
4928 << lex->getSourceRange() << rex->getSourceRange();
4929 if (ComplainAboutFunc)
4930 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004931 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004932 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004933
4934 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004935 return Context.getPointerDiffType();
4936 }
4937 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004938
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004939 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004940}
4941
Chris Lattnereca7be62008-04-07 05:30:13 +00004942// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004943QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004944 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004945 // C99 6.5.7p2: Each of the operands shall have integer type.
4946 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004947 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004948
Nate Begeman2207d792009-10-25 02:26:48 +00004949 // Vector shifts promote their scalar inputs to vector type.
4950 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4951 return CheckVectorOperands(Loc, lex, rex);
4952
Chris Lattnerca5eede2007-12-12 05:47:28 +00004953 // Shifts don't perform usual arithmetic conversions, they just do integer
4954 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004955 QualType LHSTy = Context.isPromotableBitField(lex);
4956 if (LHSTy.isNull()) {
4957 LHSTy = lex->getType();
4958 if (LHSTy->isPromotableIntegerType())
4959 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004960 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004961 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004962 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004963
Chris Lattnerca5eede2007-12-12 05:47:28 +00004964 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004965
Ryan Flynnd0439682009-08-07 16:20:20 +00004966 // Sanity-check shift operands
4967 llvm::APSInt Right;
4968 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004969 if (!rex->isValueDependent() &&
4970 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004971 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004972 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4973 else {
4974 llvm::APInt LeftBits(Right.getBitWidth(),
4975 Context.getTypeSize(lex->getType()));
4976 if (Right.uge(LeftBits))
4977 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4978 }
4979 }
4980
Chris Lattnerca5eede2007-12-12 05:47:28 +00004981 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004982 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004983}
4984
John McCall5dbad3d2009-11-06 08:49:08 +00004985/// \brief Implements -Wsign-compare.
4986///
4987/// \param lex the left-hand expression
4988/// \param rex the right-hand expression
4989/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004990/// \param Equality whether this is an "equality-like" join, which
4991/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004992void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004993 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004994 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004995 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004996 return;
4997
John McCall45aa4552009-11-05 00:40:04 +00004998 QualType lt = lex->getType(), rt = rex->getType();
4999
5000 // Only warn if both operands are integral.
5001 if (!lt->isIntegerType() || !rt->isIntegerType())
5002 return;
5003
Sebastian Redl732429c2009-11-05 21:09:23 +00005004 // If either expression is value-dependent, don't warn. We'll get another
5005 // chance at instantiation time.
5006 if (lex->isValueDependent() || rex->isValueDependent())
5007 return;
5008
John McCall45aa4552009-11-05 00:40:04 +00005009 // The rule is that the signed operand becomes unsigned, so isolate the
5010 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00005011 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00005012 if (lt->isSignedIntegerType()) {
5013 if (rt->isSignedIntegerType()) return;
5014 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00005015 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00005016 } else {
5017 if (!rt->isSignedIntegerType()) return;
5018 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00005019 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00005020 }
5021
John McCall5dbad3d2009-11-06 08:49:08 +00005022 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00005023 // then (1) the result type will be signed and (2) the unsigned
5024 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00005025 // of the comparison will be exact.
5026 if (Context.getIntWidth(signedOperand->getType()) >
5027 Context.getIntWidth(unsignedOperand->getType()))
5028 return;
5029
John McCall45aa4552009-11-05 00:40:04 +00005030 // If the value is a non-negative integer constant, then the
5031 // signed->unsigned conversion won't change it.
5032 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00005033 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00005034 assert(value.isSigned() && "result of signed expression not signed");
5035
5036 if (value.isNonNegative())
5037 return;
5038 }
5039
John McCall5dbad3d2009-11-06 08:49:08 +00005040 if (Equality) {
5041 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00005042 // constant which cannot collide with a overflowed signed operand,
5043 // then reinterpreting the signed operand as unsigned will not
5044 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00005045 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5046 assert(!value.isSigned() && "result of unsigned expression is signed");
5047
5048 // 2's complement: test the top bit.
5049 if (value.isNonNegative())
5050 return;
5051 }
5052 }
5053
John McCallb13c87f2009-11-05 09:23:39 +00005054 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00005055 << lex->getType() << rex->getType()
5056 << lex->getSourceRange() << rex->getSourceRange();
5057}
5058
Douglas Gregor0c6db942009-05-04 06:07:12 +00005059// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005060QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005061 unsigned OpaqueOpc, bool isRelational) {
5062 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5063
Chris Lattner02dd4b12009-12-05 05:40:13 +00005064 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005065 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005066 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005067
John McCall5dbad3d2009-11-06 08:49:08 +00005068 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5069 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005070
Chris Lattnera5937dd2007-08-26 01:18:55 +00005071 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005072 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5073 UsualArithmeticConversions(lex, rex);
5074 else {
5075 UsualUnaryConversions(lex);
5076 UsualUnaryConversions(rex);
5077 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005078 QualType lType = lex->getType();
5079 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005080
Mike Stumpaf199f32009-05-07 18:43:07 +00005081 if (!lType->isFloatingType()
5082 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005083 // For non-floating point types, check for self-comparisons of the form
5084 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5085 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005086 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005087 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005088 Expr *LHSStripped = lex->IgnoreParens();
5089 Expr *RHSStripped = rex->IgnoreParens();
5090 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5091 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005092 if (DRL->getDecl() == DRR->getDecl() &&
5093 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005094 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005095
Chris Lattner55660a72009-03-08 19:39:53 +00005096 if (isa<CastExpr>(LHSStripped))
5097 LHSStripped = LHSStripped->IgnoreParenCasts();
5098 if (isa<CastExpr>(RHSStripped))
5099 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005100
Chris Lattner55660a72009-03-08 19:39:53 +00005101 // Warn about comparisons against a string constant (unless the other
5102 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005103 Expr *literalString = 0;
5104 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005105 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005106 !RHSStripped->isNullPointerConstant(Context,
5107 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005108 literalString = lex;
5109 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005110 } else if ((isa<StringLiteral>(RHSStripped) ||
5111 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005112 !LHSStripped->isNullPointerConstant(Context,
5113 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005114 literalString = rex;
5115 literalStringStripped = RHSStripped;
5116 }
5117
5118 if (literalString) {
5119 std::string resultComparison;
5120 switch (Opc) {
5121 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5122 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5123 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5124 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5125 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5126 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5127 default: assert(false && "Invalid comparison operator");
5128 }
5129 Diag(Loc, diag::warn_stringcompare)
5130 << isa<ObjCEncodeExpr>(literalStringStripped)
5131 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005132 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5133 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5134 "strcmp(")
5135 << CodeModificationHint::CreateInsertion(
5136 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005137 resultComparison);
5138 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005139 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005140
Douglas Gregor447b69e2008-11-19 03:25:36 +00005141 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005142 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005143
Chris Lattnera5937dd2007-08-26 01:18:55 +00005144 if (isRelational) {
5145 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005146 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005147 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005148 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005149 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005150 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005151
Chris Lattnera5937dd2007-08-26 01:18:55 +00005152 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005153 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005154 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005155
Douglas Gregorce940492009-09-25 04:25:58 +00005156 bool LHSIsNull = lex->isNullPointerConstant(Context,
5157 Expr::NPC_ValueDependentIsNull);
5158 bool RHSIsNull = rex->isNullPointerConstant(Context,
5159 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005160
Chris Lattnera5937dd2007-08-26 01:18:55 +00005161 // All of the following pointer related warnings are GCC extensions, except
5162 // when handling null pointer constants. One day, we can consider making them
5163 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005164 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005165 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005166 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005167 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005168 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005169
Douglas Gregor0c6db942009-05-04 06:07:12 +00005170 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005171 if (LCanPointeeTy == RCanPointeeTy)
5172 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005173 if (!isRelational &&
5174 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5175 // Valid unless comparison between non-null pointer and function pointer
5176 // This is a gcc extension compatibility comparison.
5177 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5178 && !LHSIsNull && !RHSIsNull) {
5179 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5180 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5181 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5182 return ResultTy;
5183 }
5184 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005185 // C++ [expr.rel]p2:
5186 // [...] Pointer conversions (4.10) and qualification
5187 // conversions (4.4) are performed on pointer operands (or on
5188 // a pointer operand and a null pointer constant) to bring
5189 // them to their composite pointer type. [...]
5190 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005191 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005192 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005193 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005194 if (T.isNull()) {
5195 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5196 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5197 return QualType();
5198 }
5199
Eli Friedman73c39ab2009-10-20 08:27:19 +00005200 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5201 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005202 return ResultTy;
5203 }
Eli Friedman3075e762009-08-23 00:27:47 +00005204 // C99 6.5.9p2 and C99 6.5.8p2
5205 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5206 RCanPointeeTy.getUnqualifiedType())) {
5207 // Valid unless a relational comparison of function pointers
5208 if (isRelational && LCanPointeeTy->isFunctionType()) {
5209 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5210 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5211 }
5212 } else if (!isRelational &&
5213 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5214 // Valid unless comparison between non-null pointer and function pointer
5215 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5216 && !LHSIsNull && !RHSIsNull) {
5217 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5218 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5219 }
5220 } else {
5221 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005222 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005223 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005224 }
Eli Friedman3075e762009-08-23 00:27:47 +00005225 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005226 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005227 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005228 }
Mike Stump1eb44332009-09-09 15:08:12 +00005229
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005230 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005231 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005232 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005233 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005234 (lType->isPointerType() ||
5235 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005236 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005237 return ResultTy;
5238 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005239 if (LHSIsNull &&
5240 (rType->isPointerType() ||
5241 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005242 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005243 return ResultTy;
5244 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005245
5246 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005247 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005248 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5249 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005250 // In addition, pointers to members can be compared, or a pointer to
5251 // member and a null pointer constant. Pointer to member conversions
5252 // (4.11) and qualification conversions (4.4) are performed to bring
5253 // them to a common type. If one operand is a null pointer constant,
5254 // the common type is the type of the other operand. Otherwise, the
5255 // common type is a pointer to member type similar (4.4) to the type
5256 // of one of the operands, with a cv-qualification signature (4.4)
5257 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005258 // types.
5259 QualType T = FindCompositePointerType(lex, rex);
5260 if (T.isNull()) {
5261 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5262 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5263 return QualType();
5264 }
Mike Stump1eb44332009-09-09 15:08:12 +00005265
Eli Friedman73c39ab2009-10-20 08:27:19 +00005266 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5267 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005268 return ResultTy;
5269 }
Mike Stump1eb44332009-09-09 15:08:12 +00005270
Douglas Gregor20b3e992009-08-24 17:42:35 +00005271 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005272 if (lType->isNullPtrType() && rType->isNullPtrType())
5273 return ResultTy;
5274 }
Mike Stump1eb44332009-09-09 15:08:12 +00005275
Steve Naroff1c7d0672008-09-04 15:10:53 +00005276 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005277 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005278 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5279 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005280
Steve Naroff1c7d0672008-09-04 15:10:53 +00005281 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005282 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005283 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005284 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005285 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005286 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005287 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005288 }
Steve Naroff59f53942008-09-28 01:11:11 +00005289 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005290 if (!isRelational
5291 && ((lType->isBlockPointerType() && rType->isPointerType())
5292 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005293 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005294 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005295 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005296 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005297 ->getPointeeType()->isVoidType())))
5298 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5299 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005300 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005301 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005302 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005303 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005304
Steve Naroff14108da2009-07-10 23:34:53 +00005305 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005306 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005307 const PointerType *LPT = lType->getAs<PointerType>();
5308 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005309 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005310 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005311 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005312 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005313
Steve Naroffa8069f12008-11-17 19:49:16 +00005314 if (!LPtrToVoid && !RPtrToVoid &&
5315 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005316 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005317 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005318 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005319 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005320 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005321 }
Steve Naroff14108da2009-07-10 23:34:53 +00005322 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005323 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005324 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5325 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005326 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005327 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005328 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005329 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005330 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005331 unsigned DiagID = 0;
5332 if (RHSIsNull) {
5333 if (isRelational)
5334 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5335 } else if (isRelational)
5336 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5337 else
5338 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005340 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005341 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005342 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005343 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005344 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005345 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005346 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005347 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005348 unsigned DiagID = 0;
5349 if (LHSIsNull) {
5350 if (isRelational)
5351 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5352 } else if (isRelational)
5353 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5354 else
5355 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005356
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005357 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005358 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005359 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005360 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005361 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005362 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005363 }
Steve Naroff39218df2008-09-04 16:56:14 +00005364 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005365 if (!isRelational && RHSIsNull
5366 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005367 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005368 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005369 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005370 if (!isRelational && LHSIsNull
5371 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005372 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005373 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005374 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005375 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005376}
5377
Nate Begemanbe2341d2008-07-14 18:02:46 +00005378/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005379/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005380/// like a scalar comparison, a vector comparison produces a vector of integer
5381/// types.
5382QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005383 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005384 bool isRelational) {
5385 // Check to make sure we're operating on vectors of the same type and width,
5386 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005387 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005388 if (vType.isNull())
5389 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005390
Nate Begemanbe2341d2008-07-14 18:02:46 +00005391 QualType lType = lex->getType();
5392 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005393
Nate Begemanbe2341d2008-07-14 18:02:46 +00005394 // For non-floating point types, check for self-comparisons of the form
5395 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5396 // often indicate logic errors in the program.
5397 if (!lType->isFloatingType()) {
5398 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5399 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5400 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005401 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005402 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005403
Nate Begemanbe2341d2008-07-14 18:02:46 +00005404 // Check for comparisons of floating point operands using != and ==.
5405 if (!isRelational && lType->isFloatingType()) {
5406 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005407 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005408 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005409
Nate Begemanbe2341d2008-07-14 18:02:46 +00005410 // Return the type for the comparison, which is the same as vector type for
5411 // integer vectors, or an integer type of identical size and number of
5412 // elements for floating point vectors.
5413 if (lType->isIntegerType())
5414 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005415
John McCall183700f2009-09-21 23:43:11 +00005416 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005417 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005418 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005419 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005420 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005421 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5422
Mike Stumpeed9cac2009-02-19 03:04:26 +00005423 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005424 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005425 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5426}
5427
Reid Spencer5f016e22007-07-11 17:01:13 +00005428inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005429 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005430 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005431 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005432
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005433 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
Steve Naroffa4332e22007-07-17 00:58:39 +00005435 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005436 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005437 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005438}
5439
5440inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005441 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005442 if (!Context.getLangOptions().CPlusPlus) {
5443 UsualUnaryConversions(lex);
5444 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005445
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005446 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5447 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005448
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005449 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005450 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005451
5452 // C++ [expr.log.and]p1
5453 // C++ [expr.log.or]p1
5454 // The operands are both implicitly converted to type bool (clause 4).
5455 StandardConversionSequence LHS;
5456 if (!IsStandardConversion(lex, Context.BoolTy,
5457 /*InOverloadResolution=*/false, LHS))
5458 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005459
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005460 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005461 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005462 return InvalidOperands(Loc, lex, rex);
5463
5464 StandardConversionSequence RHS;
5465 if (!IsStandardConversion(rex, Context.BoolTy,
5466 /*InOverloadResolution=*/false, RHS))
5467 return InvalidOperands(Loc, lex, rex);
5468
5469 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005470 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005471 return InvalidOperands(Loc, lex, rex);
5472
5473 // C++ [expr.log.and]p2
5474 // C++ [expr.log.or]p2
5475 // The result is a bool.
5476 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005477}
5478
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005479/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5480/// is a read-only property; return true if so. A readonly property expression
5481/// depends on various declarations and thus must be treated specially.
5482///
Mike Stump1eb44332009-09-09 15:08:12 +00005483static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005484 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5485 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5486 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5487 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005488 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005489 BaseType->getAsObjCInterfacePointerType())
5490 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5491 if (S.isPropertyReadonly(PDecl, IFace))
5492 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005493 }
5494 }
5495 return false;
5496}
5497
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005498/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5499/// emit an error and return true. If so, return false.
5500static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005501 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005502 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005503 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005504 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5505 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005506 if (IsLV == Expr::MLV_Valid)
5507 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005508
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005509 unsigned Diag = 0;
5510 bool NeedType = false;
5511 switch (IsLV) { // C99 6.5.16p2
5512 default: assert(0 && "Unknown result from isModifiableLvalue!");
5513 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005514 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005515 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5516 NeedType = true;
5517 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005518 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005519 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5520 NeedType = true;
5521 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005522 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005523 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5524 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005525 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005526 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5527 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005528 case Expr::MLV_IncompleteType:
5529 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005530 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005531 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5532 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005533 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005534 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5535 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005536 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005537 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5538 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005539 case Expr::MLV_ReadonlyProperty:
5540 Diag = diag::error_readonly_property_assignment;
5541 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005542 case Expr::MLV_NoSetterProperty:
5543 Diag = diag::error_nosetter_property_assignment;
5544 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005545 case Expr::MLV_SubObjCPropertySetting:
5546 Diag = diag::error_no_subobject_property_setting;
5547 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005548 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005549
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005550 SourceRange Assign;
5551 if (Loc != OrigLoc)
5552 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005553 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005554 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005555 else
Mike Stump1eb44332009-09-09 15:08:12 +00005556 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005557 return true;
5558}
5559
5560
5561
5562// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005563QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5564 SourceLocation Loc,
5565 QualType CompoundType) {
5566 // Verify that LHS is a modifiable lvalue, and emit error if not.
5567 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005568 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005569
5570 QualType LHSType = LHS->getType();
5571 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005572
Chris Lattner5cf216b2008-01-04 18:04:52 +00005573 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005574 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005575 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005576 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005577 // Special case of NSObject attributes on c-style pointer types.
5578 if (ConvTy == IncompatiblePointer &&
5579 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005580 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005581 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005582 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005583 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005584
Chris Lattner2c156472008-08-21 18:04:13 +00005585 // If the RHS is a unary plus or minus, check to see if they = and + are
5586 // right next to each other. If so, the user may have typo'd "x =+ 4"
5587 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005588 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005589 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5590 RHSCheck = ICE->getSubExpr();
5591 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5592 if ((UO->getOpcode() == UnaryOperator::Plus ||
5593 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005594 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005595 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005596 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5597 // And there is a space or other character before the subexpr of the
5598 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005599 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5600 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005601 Diag(Loc, diag::warn_not_compound_assign)
5602 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5603 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005604 }
Chris Lattner2c156472008-08-21 18:04:13 +00005605 }
5606 } else {
5607 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005608 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005609 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005610
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005611 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005612 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005613 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005614
Reid Spencer5f016e22007-07-11 17:01:13 +00005615 // C99 6.5.16p3: The type of an assignment expression is the type of the
5616 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005617 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005618 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5619 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005620 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005621 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005622 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005623}
5624
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005625// C99 6.5.17
5626QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005627 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005628 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005629
5630 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5631 // incomplete in C++).
5632
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005633 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005634}
5635
Steve Naroff49b45262007-07-13 16:58:59 +00005636/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5637/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005638QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5639 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005640 if (Op->isTypeDependent())
5641 return Context.DependentTy;
5642
Chris Lattner3528d352008-11-21 07:05:48 +00005643 QualType ResType = Op->getType();
5644 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005645
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005646 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5647 // Decrement of bool is not allowed.
5648 if (!isInc) {
5649 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5650 return QualType();
5651 }
5652 // Increment of bool sets it to true, but is deprecated.
5653 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5654 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005655 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005656 } else if (ResType->isAnyPointerType()) {
5657 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005658
Chris Lattner3528d352008-11-21 07:05:48 +00005659 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005660 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005661 if (getLangOptions().CPlusPlus) {
5662 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5663 << Op->getSourceRange();
5664 return QualType();
5665 }
5666
5667 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005668 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005669 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005670 if (getLangOptions().CPlusPlus) {
5671 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5672 << Op->getType() << Op->getSourceRange();
5673 return QualType();
5674 }
5675
5676 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005677 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005678 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005679 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005680 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005681 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005682 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005683 // Diagnose bad cases where we step over interface counts.
5684 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5685 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5686 << PointeeTy << Op->getSourceRange();
5687 return QualType();
5688 }
Chris Lattner3528d352008-11-21 07:05:48 +00005689 } else if (ResType->isComplexType()) {
5690 // C99 does not support ++/-- on complex types, we allow as an extension.
5691 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005692 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005693 } else {
5694 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005695 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005696 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005697 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005698 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005699 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005700 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005701 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005702 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005703}
5704
Anders Carlsson369dee42008-02-01 07:15:58 +00005705/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005706/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005707/// where the declaration is needed for type checking. We only need to
5708/// handle cases when the expression references a function designator
5709/// or is an lvalue. Here are some examples:
5710/// - &(x) => x
5711/// - &*****f => f for f a function designator.
5712/// - &s.xx => s
5713/// - &s.zz[1].yy -> s, if zz is an array
5714/// - *(x + 1) -> x, if x is an array
5715/// - &"123"[2] -> 0
5716/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005717static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005718 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005719 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005720 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005721 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005722 // If this is an arrow operator, the address is an offset from
5723 // the base's value, so the object the base refers to is
5724 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005725 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005726 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005727 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005728 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005729 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005730 // FIXME: This code shouldn't be necessary! We should catch the implicit
5731 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005732 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5733 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5734 if (ICE->getSubExpr()->getType()->isArrayType())
5735 return getPrimaryDecl(ICE->getSubExpr());
5736 }
5737 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005738 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005739 case Stmt::UnaryOperatorClass: {
5740 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005741
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005742 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005743 case UnaryOperator::Real:
5744 case UnaryOperator::Imag:
5745 case UnaryOperator::Extension:
5746 return getPrimaryDecl(UO->getSubExpr());
5747 default:
5748 return 0;
5749 }
5750 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005751 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005752 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005753 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005754 // If the result of an implicit cast is an l-value, we care about
5755 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005756 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005757 default:
5758 return 0;
5759 }
5760}
5761
5762/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005763/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005764/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005765/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005766/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005767/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005768/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005769QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005770 // Make sure to ignore parentheses in subsequent checks
5771 op = op->IgnoreParens();
5772
Douglas Gregor9103bb22008-12-17 22:52:20 +00005773 if (op->isTypeDependent())
5774 return Context.DependentTy;
5775
Steve Naroff08f19672008-01-13 17:10:08 +00005776 if (getLangOptions().C99) {
5777 // Implement C99-only parts of addressof rules.
5778 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5779 if (uOp->getOpcode() == UnaryOperator::Deref)
5780 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5781 // (assuming the deref expression is valid).
5782 return uOp->getSubExpr()->getType();
5783 }
5784 // Technically, there should be a check for array subscript
5785 // expressions here, but the result of one is always an lvalue anyway.
5786 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005787 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005788 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005789
Eli Friedman441cf102009-05-16 23:27:50 +00005790 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5791 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005792 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005793 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005794 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005795 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5796 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005797 return QualType();
5798 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005799 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005800 // The operand cannot be a bit-field
5801 Diag(OpLoc, diag::err_typecheck_address_of)
5802 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005803 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005804 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5805 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005806 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005807 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005808 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005809 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005810 } else if (isa<ObjCPropertyRefExpr>(op)) {
5811 // cannot take address of a property expression.
5812 Diag(OpLoc, diag::err_typecheck_address_of)
5813 << "property expression" << op->getSourceRange();
5814 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005815 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5816 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005817 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5818 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005819 } else if (isa<UnresolvedLookupExpr>(op)) {
5820 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005821 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005822 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005823 // with the register storage-class specifier.
5824 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5825 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005826 Diag(OpLoc, diag::err_typecheck_address_of)
5827 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005828 return QualType();
5829 }
John McCallba135432009-11-21 08:51:07 +00005830 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005831 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005832 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005833 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005834 // Could be a pointer to member, though, if there is an explicit
5835 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005836 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005837 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005838 if (Ctx && Ctx->isRecord()) {
5839 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005840 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005841 diag::err_cannot_form_pointer_to_member_of_reference_type)
5842 << FD->getDeclName() << FD->getType();
5843 return QualType();
5844 }
Mike Stump1eb44332009-09-09 15:08:12 +00005845
Sebastian Redlebc07d52009-02-03 20:19:35 +00005846 return Context.getMemberPointerType(op->getType(),
5847 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005848 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005849 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005850 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005851 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005852 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005853 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5854 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005855 return Context.getMemberPointerType(op->getType(),
5856 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5857 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005858 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005859 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005860
Eli Friedman441cf102009-05-16 23:27:50 +00005861 if (lval == Expr::LV_IncompleteVoidType) {
5862 // Taking the address of a void variable is technically illegal, but we
5863 // allow it in cases which are otherwise valid.
5864 // Example: "extern void x; void* y = &x;".
5865 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5866 }
5867
Reid Spencer5f016e22007-07-11 17:01:13 +00005868 // If the operand has type "type", the result has type "pointer to type".
5869 return Context.getPointerType(op->getType());
5870}
5871
Chris Lattner22caddc2008-11-23 09:13:29 +00005872QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005873 if (Op->isTypeDependent())
5874 return Context.DependentTy;
5875
Chris Lattner22caddc2008-11-23 09:13:29 +00005876 UsualUnaryConversions(Op);
5877 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005878
Chris Lattner22caddc2008-11-23 09:13:29 +00005879 // Note that per both C89 and C99, this is always legal, even if ptype is an
5880 // incomplete type or void. It would be possible to warn about dereferencing
5881 // a void pointer, but it's completely well-defined, and such a warning is
5882 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005883 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005884 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005885
John McCall183700f2009-09-21 23:43:11 +00005886 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005887 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005888
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005889 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005890 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005891 return QualType();
5892}
5893
5894static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5895 tok::TokenKind Kind) {
5896 BinaryOperator::Opcode Opc;
5897 switch (Kind) {
5898 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005899 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5900 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005901 case tok::star: Opc = BinaryOperator::Mul; break;
5902 case tok::slash: Opc = BinaryOperator::Div; break;
5903 case tok::percent: Opc = BinaryOperator::Rem; break;
5904 case tok::plus: Opc = BinaryOperator::Add; break;
5905 case tok::minus: Opc = BinaryOperator::Sub; break;
5906 case tok::lessless: Opc = BinaryOperator::Shl; break;
5907 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5908 case tok::lessequal: Opc = BinaryOperator::LE; break;
5909 case tok::less: Opc = BinaryOperator::LT; break;
5910 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5911 case tok::greater: Opc = BinaryOperator::GT; break;
5912 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5913 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5914 case tok::amp: Opc = BinaryOperator::And; break;
5915 case tok::caret: Opc = BinaryOperator::Xor; break;
5916 case tok::pipe: Opc = BinaryOperator::Or; break;
5917 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5918 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5919 case tok::equal: Opc = BinaryOperator::Assign; break;
5920 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5921 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5922 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5923 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5924 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5925 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5926 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5927 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5928 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5929 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5930 case tok::comma: Opc = BinaryOperator::Comma; break;
5931 }
5932 return Opc;
5933}
5934
5935static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5936 tok::TokenKind Kind) {
5937 UnaryOperator::Opcode Opc;
5938 switch (Kind) {
5939 default: assert(0 && "Unknown unary op!");
5940 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5941 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5942 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5943 case tok::star: Opc = UnaryOperator::Deref; break;
5944 case tok::plus: Opc = UnaryOperator::Plus; break;
5945 case tok::minus: Opc = UnaryOperator::Minus; break;
5946 case tok::tilde: Opc = UnaryOperator::Not; break;
5947 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005948 case tok::kw___real: Opc = UnaryOperator::Real; break;
5949 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5950 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5951 }
5952 return Opc;
5953}
5954
Douglas Gregoreaebc752008-11-06 23:29:22 +00005955/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5956/// operator @p Opc at location @c TokLoc. This routine only supports
5957/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005958Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5959 unsigned Op,
5960 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005961 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005962 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005963 // The following two variables are used for compound assignment operators
5964 QualType CompLHSTy; // Type of LHS after promotions for computation
5965 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005966
5967 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005968 case BinaryOperator::Assign:
5969 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5970 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005971 case BinaryOperator::PtrMemD:
5972 case BinaryOperator::PtrMemI:
5973 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5974 Opc == BinaryOperator::PtrMemI);
5975 break;
5976 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005977 case BinaryOperator::Div:
5978 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5979 break;
5980 case BinaryOperator::Rem:
5981 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5982 break;
5983 case BinaryOperator::Add:
5984 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5985 break;
5986 case BinaryOperator::Sub:
5987 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5988 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005989 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005990 case BinaryOperator::Shr:
5991 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5992 break;
5993 case BinaryOperator::LE:
5994 case BinaryOperator::LT:
5995 case BinaryOperator::GE:
5996 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005997 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005998 break;
5999 case BinaryOperator::EQ:
6000 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006001 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006002 break;
6003 case BinaryOperator::And:
6004 case BinaryOperator::Xor:
6005 case BinaryOperator::Or:
6006 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6007 break;
6008 case BinaryOperator::LAnd:
6009 case BinaryOperator::LOr:
6010 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6011 break;
6012 case BinaryOperator::MulAssign:
6013 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006014 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6015 CompLHSTy = CompResultTy;
6016 if (!CompResultTy.isNull())
6017 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006018 break;
6019 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006020 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6021 CompLHSTy = CompResultTy;
6022 if (!CompResultTy.isNull())
6023 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006024 break;
6025 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006026 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6027 if (!CompResultTy.isNull())
6028 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006029 break;
6030 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006031 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6032 if (!CompResultTy.isNull())
6033 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006034 break;
6035 case BinaryOperator::ShlAssign:
6036 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006037 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6038 CompLHSTy = CompResultTy;
6039 if (!CompResultTy.isNull())
6040 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006041 break;
6042 case BinaryOperator::AndAssign:
6043 case BinaryOperator::XorAssign:
6044 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006045 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6046 CompLHSTy = CompResultTy;
6047 if (!CompResultTy.isNull())
6048 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006049 break;
6050 case BinaryOperator::Comma:
6051 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6052 break;
6053 }
6054 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006055 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006056 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006057 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6058 else
6059 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006060 CompLHSTy, CompResultTy,
6061 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006062}
6063
Sebastian Redlaee3c932009-10-27 12:10:02 +00006064/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6065/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006066static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6067 const PartialDiagnostic &PD,
6068 SourceRange ParenRange)
6069{
6070 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6071 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6072 // We can't display the parentheses, so just dig the
6073 // warning/error and return.
6074 Self.Diag(Loc, PD);
6075 return;
6076 }
6077
6078 Self.Diag(Loc, PD)
6079 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6080 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6081}
6082
Sebastian Redlaee3c932009-10-27 12:10:02 +00006083/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6084/// operators are mixed in a way that suggests that the programmer forgot that
6085/// comparison operators have higher precedence. The most typical example of
6086/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006087static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6088 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006089 typedef BinaryOperator BinOp;
6090 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6091 rhsopc = static_cast<BinOp::Opcode>(-1);
6092 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006093 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006094 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006095 rhsopc = BO->getOpcode();
6096
6097 // Subs are not binary operators.
6098 if (lhsopc == -1 && rhsopc == -1)
6099 return;
6100
6101 // Bitwise operations are sometimes used as eager logical ops.
6102 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006103 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6104 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006105 return;
6106
Sebastian Redlaee3c932009-10-27 12:10:02 +00006107 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006108 SuggestParentheses(Self, OpLoc,
6109 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006110 << SourceRange(lhs->getLocStart(), OpLoc)
6111 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6112 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6113 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006114 SuggestParentheses(Self, OpLoc,
6115 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006116 << SourceRange(OpLoc, rhs->getLocEnd())
6117 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6118 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006119}
6120
6121/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6122/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6123/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6124static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6125 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006126 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006127 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6128}
6129
Reid Spencer5f016e22007-07-11 17:01:13 +00006130// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006131Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6132 tok::TokenKind Kind,
6133 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006134 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006135 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006136
Steve Narofff69936d2007-09-16 03:34:24 +00006137 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6138 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006139
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006140 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6141 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6142
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006143 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6144}
6145
6146Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6147 BinaryOperator::Opcode Opc,
6148 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006149 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006150 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006151 rhs->getType()->isOverloadableType())) {
6152 // Find all of the overloaded operators visible from this
6153 // point. We perform both an operator-name lookup from the local
6154 // scope and an argument-dependent lookup based on the types of
6155 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006156 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006157 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6158 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006159 if (S)
6160 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6161 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006162 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006163 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006164 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006165 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006166 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006167
Douglas Gregor063daf62009-03-13 18:40:31 +00006168 // Build the (potentially-overloaded, potentially-dependent)
6169 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006170 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006171 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006172
Douglas Gregoreaebc752008-11-06 23:29:22 +00006173 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006174 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006175}
6176
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006177Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006178 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006179 ExprArg InputArg) {
6180 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006181
Mike Stump390b4cc2009-05-16 07:39:55 +00006182 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006183 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006184 QualType resultType;
6185 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006186 case UnaryOperator::OffsetOf:
6187 assert(false && "Invalid unary operator");
6188 break;
6189
Reid Spencer5f016e22007-07-11 17:01:13 +00006190 case UnaryOperator::PreInc:
6191 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006192 case UnaryOperator::PostInc:
6193 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006194 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006195 Opc == UnaryOperator::PreInc ||
6196 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006197 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006198 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006199 resultType = CheckAddressOfOperand(Input, OpLoc);
6200 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006201 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006202 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006203 resultType = CheckIndirectionOperand(Input, OpLoc);
6204 break;
6205 case UnaryOperator::Plus:
6206 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006207 UsualUnaryConversions(Input);
6208 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006209 if (resultType->isDependentType())
6210 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006211 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6212 break;
6213 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6214 resultType->isEnumeralType())
6215 break;
6216 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6217 Opc == UnaryOperator::Plus &&
6218 resultType->isPointerType())
6219 break;
6220
Sebastian Redl0eb23302009-01-19 00:08:26 +00006221 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6222 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006223 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006224 UsualUnaryConversions(Input);
6225 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006226 if (resultType->isDependentType())
6227 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006228 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6229 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6230 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006231 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006232 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006233 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006234 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6235 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006236 break;
6237 case UnaryOperator::LNot: // logical negation
6238 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006239 DefaultFunctionArrayConversion(Input);
6240 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006241 if (resultType->isDependentType())
6242 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006243 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006244 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6245 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006246 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006247 // In C++, it's bool. C++ 5.3.1p8
6248 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006249 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006250 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006251 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006252 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006253 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006254 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006255 resultType = Input->getType();
6256 break;
6257 }
6258 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006259 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006260
6261 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006262 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006263}
6264
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006265Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6266 UnaryOperator::Opcode Opc,
6267 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006268 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006269 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6270 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006271 // Find all of the overloaded operators visible from this
6272 // point. We perform both an operator-name lookup from the local
6273 // scope and an argument-dependent lookup based on the types of
6274 // the arguments.
6275 FunctionSet Functions;
6276 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6277 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006278 if (S)
6279 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6280 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006281 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006282 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006283 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006284 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006285
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006286 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6287 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006288
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006289 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6290}
6291
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006292// Unary Operators. 'Tok' is the token for the operator.
6293Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6294 tok::TokenKind Op, ExprArg input) {
6295 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6296}
6297
Steve Naroff1b273c42007-09-16 14:56:35 +00006298/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006299Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6300 SourceLocation LabLoc,
6301 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006302 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006303 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006304
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006305 // If we haven't seen this label yet, create a forward reference. It
6306 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006307 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006308 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006309
Reid Spencer5f016e22007-07-11 17:01:13 +00006310 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006311 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6312 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006313}
6314
Sebastian Redlf53597f2009-03-15 17:47:39 +00006315Sema::OwningExprResult
6316Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6317 SourceLocation RPLoc) { // "({..})"
6318 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006319 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6320 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6321
Eli Friedmandca2b732009-01-24 23:09:00 +00006322 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006323 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006324 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006325
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006326 // FIXME: there are a variety of strange constraints to enforce here, for
6327 // example, it is not possible to goto into a stmt expression apparently.
6328 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006329
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006330 // If there are sub stmts in the compound stmt, take the type of the last one
6331 // as the type of the stmtexpr.
6332 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006333
Chris Lattner611b2ec2008-07-26 19:51:01 +00006334 if (!Compound->body_empty()) {
6335 Stmt *LastStmt = Compound->body_back();
6336 // If LastStmt is a label, skip down through into the body.
6337 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6338 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006339
Chris Lattner611b2ec2008-07-26 19:51:01 +00006340 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006341 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006342 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006343
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006344 // FIXME: Check that expression type is complete/non-abstract; statement
6345 // expressions are not lvalues.
6346
Sebastian Redlf53597f2009-03-15 17:47:39 +00006347 substmt.release();
6348 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006349}
Steve Naroffd34e9152007-08-01 22:05:33 +00006350
Sebastian Redlf53597f2009-03-15 17:47:39 +00006351Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6352 SourceLocation BuiltinLoc,
6353 SourceLocation TypeLoc,
6354 TypeTy *argty,
6355 OffsetOfComponent *CompPtr,
6356 unsigned NumComponents,
6357 SourceLocation RPLoc) {
6358 // FIXME: This function leaks all expressions in the offset components on
6359 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006360 // FIXME: Preserve type source info.
6361 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006362 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006363
Sebastian Redl28507842009-02-26 14:39:58 +00006364 bool Dependent = ArgTy->isDependentType();
6365
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006366 // We must have at least one component that refers to the type, and the first
6367 // one is known to be a field designator. Verify that the ArgTy represents
6368 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006369 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006370 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006371
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006372 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6373 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006374
Eli Friedman35183ac2009-02-27 06:44:11 +00006375 // Otherwise, create a null pointer as the base, and iteratively process
6376 // the offsetof designators.
6377 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6378 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006379 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006380 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006381
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006382 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6383 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006384 // FIXME: This diagnostic isn't actually visible because the location is in
6385 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006386 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006387 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6388 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006389
Sebastian Redl28507842009-02-26 14:39:58 +00006390 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006391 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006392
John McCalld00f2002009-11-04 03:03:43 +00006393 if (RequireCompleteType(TypeLoc, Res->getType(),
6394 diag::err_offsetof_incomplete_type))
6395 return ExprError();
6396
Sebastian Redl28507842009-02-26 14:39:58 +00006397 // FIXME: Dependent case loses a lot of information here. And probably
6398 // leaks like a sieve.
6399 for (unsigned i = 0; i != NumComponents; ++i) {
6400 const OffsetOfComponent &OC = CompPtr[i];
6401 if (OC.isBrackets) {
6402 // Offset of an array sub-field. TODO: Should we allow vector elements?
6403 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6404 if (!AT) {
6405 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006406 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6407 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006408 }
6409
6410 // FIXME: C++: Verify that operator[] isn't overloaded.
6411
Eli Friedman35183ac2009-02-27 06:44:11 +00006412 // Promote the array so it looks more like a normal array subscript
6413 // expression.
6414 DefaultFunctionArrayConversion(Res);
6415
Sebastian Redl28507842009-02-26 14:39:58 +00006416 // C99 6.5.2.1p1
6417 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006418 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006419 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006420 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006421 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006422 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006423
6424 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6425 OC.LocEnd);
6426 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006427 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006428
Ted Kremenek6217b802009-07-29 21:53:49 +00006429 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006430 if (!RC) {
6431 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006432 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6433 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006434 }
Chris Lattner704fe352007-08-30 17:59:59 +00006435
Sebastian Redl28507842009-02-26 14:39:58 +00006436 // Get the decl corresponding to this.
6437 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006438 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006439 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Douglas Gregor75b699a2009-12-12 07:25:49 +00006440 switch (ExprEvalContexts.back().Context ) {
6441 case Unevaluated:
6442 // The argument will never be evaluated, so don't complain.
6443 break;
6444
6445 case PotentiallyEvaluated:
6446 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6447 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6448 << Res->getType());
6449 DidWarnAboutNonPOD = true;
6450 break;
6451
6452 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +00006453 ExprEvalContexts.back().addDiagnostic(BuiltinLoc,
6454 PDiag(diag::warn_offsetof_non_pod_type)
6455 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6456 << Res->getType());
Douglas Gregor75b699a2009-12-12 07:25:49 +00006457 DidWarnAboutNonPOD = true;
6458 break;
6459 }
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006460 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006461 }
Mike Stump1eb44332009-09-09 15:08:12 +00006462
John McCalla24dc2e2009-11-17 02:14:36 +00006463 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6464 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006465
John McCall1bcee0a2009-12-02 08:25:40 +00006466 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006467 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006468 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006469 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6470 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006471
Sebastian Redl28507842009-02-26 14:39:58 +00006472 // FIXME: C++: Verify that MemberDecl isn't a static field.
6473 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006474 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006475 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006476 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006477 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006478 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006479 // MemberDecl->getType() doesn't get the right qualifiers, but it
6480 // doesn't matter here.
6481 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6482 MemberDecl->getType().getNonReferenceType());
6483 }
Sebastian Redl28507842009-02-26 14:39:58 +00006484 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006485 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006486
Sebastian Redlf53597f2009-03-15 17:47:39 +00006487 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6488 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006489}
6490
6491
Sebastian Redlf53597f2009-03-15 17:47:39 +00006492Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6493 TypeTy *arg1,TypeTy *arg2,
6494 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006495 // FIXME: Preserve type source info.
6496 QualType argT1 = GetTypeFromParser(arg1);
6497 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006498
Steve Naroffd34e9152007-08-01 22:05:33 +00006499 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006500
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006501 if (getLangOptions().CPlusPlus) {
6502 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6503 << SourceRange(BuiltinLoc, RPLoc);
6504 return ExprError();
6505 }
6506
Sebastian Redlf53597f2009-03-15 17:47:39 +00006507 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6508 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006509}
6510
Sebastian Redlf53597f2009-03-15 17:47:39 +00006511Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6512 ExprArg cond,
6513 ExprArg expr1, ExprArg expr2,
6514 SourceLocation RPLoc) {
6515 Expr *CondExpr = static_cast<Expr*>(cond.get());
6516 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6517 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006518
Steve Naroffd04fdd52007-08-03 21:21:27 +00006519 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6520
Sebastian Redl28507842009-02-26 14:39:58 +00006521 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006522 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006523 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006524 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006525 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006526 } else {
6527 // The conditional expression is required to be a constant expression.
6528 llvm::APSInt condEval(32);
6529 SourceLocation ExpLoc;
6530 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006531 return ExprError(Diag(ExpLoc,
6532 diag::err_typecheck_choose_expr_requires_constant)
6533 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006534
Sebastian Redl28507842009-02-26 14:39:58 +00006535 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6536 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006537 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6538 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006539 }
6540
Sebastian Redlf53597f2009-03-15 17:47:39 +00006541 cond.release(); expr1.release(); expr2.release();
6542 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006543 resType, RPLoc,
6544 resType->isDependentType(),
6545 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006546}
6547
Steve Naroff4eb206b2008-09-03 18:15:37 +00006548//===----------------------------------------------------------------------===//
6549// Clang Extensions.
6550//===----------------------------------------------------------------------===//
6551
6552/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006553void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006554 // Analyze block parameters.
6555 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006556
Steve Naroff4eb206b2008-09-03 18:15:37 +00006557 // Add BSI to CurBlock.
6558 BSI->PrevBlockInfo = CurBlock;
6559 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006560
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006561 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006562 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006563 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006564 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006565 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6566 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006567
Steve Naroff090276f2008-10-10 01:28:17 +00006568 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006569 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006570 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006571}
6572
Mike Stump98eb8a72009-02-04 22:31:32 +00006573void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006574 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006575
6576 if (ParamInfo.getNumTypeObjects() == 0
6577 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006578 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006579 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6580
Mike Stump4eeab842009-04-28 01:10:27 +00006581 if (T->isArrayType()) {
6582 Diag(ParamInfo.getSourceRange().getBegin(),
6583 diag::err_block_returns_array);
6584 return;
6585 }
6586
Mike Stump98eb8a72009-02-04 22:31:32 +00006587 // The parameter list is optional, if there was none, assume ().
6588 if (!T->isFunctionType())
6589 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6590
6591 CurBlock->hasPrototype = true;
6592 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006593 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006594 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006595 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006596 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006597 // FIXME: remove the attribute.
6598 }
John McCall183700f2009-09-21 23:43:11 +00006599 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006600
Chris Lattner9097af12009-04-11 19:27:54 +00006601 // Do not allow returning a objc interface by-value.
6602 if (RetTy->isObjCInterfaceType()) {
6603 Diag(ParamInfo.getSourceRange().getBegin(),
6604 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6605 return;
6606 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006607 return;
6608 }
6609
Steve Naroff4eb206b2008-09-03 18:15:37 +00006610 // Analyze arguments to block.
6611 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6612 "Not a function declarator!");
6613 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006614
Steve Naroff090276f2008-10-10 01:28:17 +00006615 CurBlock->hasPrototype = FTI.hasPrototype;
6616 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006617
Steve Naroff4eb206b2008-09-03 18:15:37 +00006618 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6619 // no arguments, not a function that takes a single void argument.
6620 if (FTI.hasPrototype &&
6621 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006622 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6623 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006624 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006625 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006626 } else if (FTI.hasPrototype) {
6627 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006628 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006629 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006630 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006631 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006632 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006633 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006634 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006635 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6636 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6637 // If this has an identifier, add it to the scope stack.
6638 if ((*AI)->getIdentifier())
6639 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006640
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006641 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006642 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006643 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006644 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006645 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006646 // FIXME: remove the attribute.
6647 }
Mike Stump1eb44332009-09-09 15:08:12 +00006648
Chris Lattner9097af12009-04-11 19:27:54 +00006649 // Analyze the return type.
6650 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006651 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006652
Chris Lattner9097af12009-04-11 19:27:54 +00006653 // Do not allow returning a objc interface by-value.
6654 if (RetTy->isObjCInterfaceType()) {
6655 Diag(ParamInfo.getSourceRange().getBegin(),
6656 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6657 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006658 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006659}
6660
6661/// ActOnBlockError - If there is an error parsing a block, this callback
6662/// is invoked to pop the information about the block from the action impl.
6663void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6664 // Ensure that CurBlock is deleted.
6665 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006666
Chris Lattner17a78302009-04-19 05:28:12 +00006667 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6668
Steve Naroff4eb206b2008-09-03 18:15:37 +00006669 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006670 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006671 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006672 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006673}
6674
6675/// ActOnBlockStmtExpr - This is called when the body of a block statement
6676/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006677Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6678 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006679 // If blocks are disabled, emit an error.
6680 if (!LangOpts.Blocks)
6681 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006682
Steve Naroff4eb206b2008-09-03 18:15:37 +00006683 // Ensure that CurBlock is deleted.
6684 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006685
Steve Naroff090276f2008-10-10 01:28:17 +00006686 PopDeclContext();
6687
Steve Naroff4eb206b2008-09-03 18:15:37 +00006688 // Pop off CurBlock, handle nested blocks.
6689 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006690
Steve Naroff4eb206b2008-09-03 18:15:37 +00006691 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006692 if (!BSI->ReturnType.isNull())
6693 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006694
Steve Naroff4eb206b2008-09-03 18:15:37 +00006695 llvm::SmallVector<QualType, 8> ArgTypes;
6696 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6697 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006698
Mike Stump56925862009-07-28 22:04:01 +00006699 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006700 QualType BlockTy;
6701 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006702 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6703 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006704 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006705 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006706 BSI->isVariadic, 0, false, false, 0, 0,
6707 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006708
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006709 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006710 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006711 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006712
Chris Lattner17a78302009-04-19 05:28:12 +00006713 // If needed, diagnose invalid gotos and switches in the block.
6714 if (CurFunctionNeedsScopeChecking)
6715 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6716 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006717
Anders Carlssone9146f22009-05-01 19:49:17 +00006718 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006719 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006720 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6721 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006722}
6723
Sebastian Redlf53597f2009-03-15 17:47:39 +00006724Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6725 ExprArg expr, TypeTy *type,
6726 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006727 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006728 Expr *E = static_cast<Expr*>(expr.get());
6729 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006730
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006731 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006732
6733 // Get the va_list type
6734 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006735 if (VaListType->isArrayType()) {
6736 // Deal with implicit array decay; for example, on x86-64,
6737 // va_list is an array, but it's supposed to decay to
6738 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006739 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006740 // Make sure the input expression also decays appropriately.
6741 UsualUnaryConversions(E);
6742 } else {
6743 // Otherwise, the va_list argument must be an l-value because
6744 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006745 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006746 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006747 return ExprError();
6748 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006749
Douglas Gregordd027302009-05-19 23:10:31 +00006750 if (!E->isTypeDependent() &&
6751 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006752 return ExprError(Diag(E->getLocStart(),
6753 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006754 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006755 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006756
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006757 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006758 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006759
Sebastian Redlf53597f2009-03-15 17:47:39 +00006760 expr.release();
6761 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6762 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006763}
6764
Sebastian Redlf53597f2009-03-15 17:47:39 +00006765Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006766 // The type of __null will be int or long, depending on the size of
6767 // pointers on the target.
6768 QualType Ty;
6769 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6770 Ty = Context.IntTy;
6771 else
6772 Ty = Context.LongTy;
6773
Sebastian Redlf53597f2009-03-15 17:47:39 +00006774 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006775}
6776
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006777static void
6778MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6779 QualType DstType,
6780 Expr *SrcExpr,
6781 CodeModificationHint &Hint) {
6782 if (!SemaRef.getLangOptions().ObjC1)
6783 return;
6784
6785 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6786 if (!PT)
6787 return;
6788
6789 // Check if the destination is of type 'id'.
6790 if (!PT->isObjCIdType()) {
6791 // Check if the destination is the 'NSString' interface.
6792 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6793 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6794 return;
6795 }
6796
6797 // Strip off any parens and casts.
6798 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6799 if (!SL || SL->isWide())
6800 return;
6801
6802 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6803}
6804
Chris Lattner5cf216b2008-01-04 18:04:52 +00006805bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6806 SourceLocation Loc,
6807 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00006808 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00006809 // Decode the result (notice that AST's are still created for extensions).
6810 bool isInvalid = false;
6811 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006812 CodeModificationHint Hint;
6813
Chris Lattner5cf216b2008-01-04 18:04:52 +00006814 switch (ConvTy) {
6815 default: assert(0 && "Unknown conversion type");
6816 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006817 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006818 DiagKind = diag::ext_typecheck_convert_pointer_int;
6819 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006820 case IntToPointer:
6821 DiagKind = diag::ext_typecheck_convert_int_pointer;
6822 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006823 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006824 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006825 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6826 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006827 case IncompatiblePointerSign:
6828 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6829 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006830 case FunctionVoidPointer:
6831 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6832 break;
6833 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006834 // If the qualifiers lost were because we were applying the
6835 // (deprecated) C++ conversion from a string literal to a char*
6836 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6837 // Ideally, this check would be performed in
6838 // CheckPointerTypesForAssignment. However, that would require a
6839 // bit of refactoring (so that the second argument is an
6840 // expression, rather than a type), which should be done as part
6841 // of a larger effort to fix CheckPointerTypesForAssignment for
6842 // C++ semantics.
6843 if (getLangOptions().CPlusPlus &&
6844 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6845 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006846 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6847 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006848 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006849 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006850 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006851 case IntToBlockPointer:
6852 DiagKind = diag::err_int_to_block_pointer;
6853 break;
6854 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006855 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006856 break;
Steve Naroff39579072008-10-14 22:18:38 +00006857 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006858 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006859 // it can give a more specific diagnostic.
6860 DiagKind = diag::warn_incompatible_qualified_id;
6861 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006862 case IncompatibleVectors:
6863 DiagKind = diag::warn_incompatible_vectors;
6864 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006865 case Incompatible:
6866 DiagKind = diag::err_typecheck_convert_incompatible;
6867 isInvalid = true;
6868 break;
6869 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006870
Douglas Gregor68647482009-12-16 03:45:30 +00006871 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006872 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006873 return isInvalid;
6874}
Anders Carlssone21555e2008-11-30 19:50:32 +00006875
Chris Lattner3bf68932009-04-25 21:59:05 +00006876bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006877 llvm::APSInt ICEResult;
6878 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6879 if (Result)
6880 *Result = ICEResult;
6881 return false;
6882 }
6883
Anders Carlssone21555e2008-11-30 19:50:32 +00006884 Expr::EvalResult EvalResult;
6885
Mike Stumpeed9cac2009-02-19 03:04:26 +00006886 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006887 EvalResult.HasSideEffects) {
6888 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6889
6890 if (EvalResult.Diag) {
6891 // We only show the note if it's not the usual "invalid subexpression"
6892 // or if it's actually in a subexpression.
6893 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6894 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6895 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6896 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006897
Anders Carlssone21555e2008-11-30 19:50:32 +00006898 return true;
6899 }
6900
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006901 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6902 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006903
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006904 if (EvalResult.Diag &&
6905 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6906 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006907
Anders Carlssone21555e2008-11-30 19:50:32 +00006908 if (Result)
6909 *Result = EvalResult.Val.getInt();
6910 return false;
6911}
Douglas Gregore0762c92009-06-19 23:52:42 +00006912
Douglas Gregor2afce722009-11-26 00:44:06 +00006913void
Mike Stump1eb44332009-09-09 15:08:12 +00006914Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006915 ExprEvalContexts.push_back(
6916 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006917}
6918
Mike Stump1eb44332009-09-09 15:08:12 +00006919void
Douglas Gregor2afce722009-11-26 00:44:06 +00006920Sema::PopExpressionEvaluationContext() {
6921 // Pop the current expression evaluation context off the stack.
6922 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6923 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006924
Douglas Gregor06d33692009-12-12 07:57:52 +00006925 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
6926 if (Rec.PotentiallyReferenced) {
6927 // Mark any remaining declarations in the current position of the stack
6928 // as "referenced". If they were not meant to be referenced, semantic
6929 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6930 for (PotentiallyReferencedDecls::iterator
6931 I = Rec.PotentiallyReferenced->begin(),
6932 IEnd = Rec.PotentiallyReferenced->end();
6933 I != IEnd; ++I)
6934 MarkDeclarationReferenced(I->first, I->second);
6935 }
6936
6937 if (Rec.PotentiallyDiagnosed) {
6938 // Emit any pending diagnostics.
6939 for (PotentiallyEmittedDiagnostics::iterator
6940 I = Rec.PotentiallyDiagnosed->begin(),
6941 IEnd = Rec.PotentiallyDiagnosed->end();
6942 I != IEnd; ++I)
6943 Diag(I->first, I->second);
6944 }
Douglas Gregor2afce722009-11-26 00:44:06 +00006945 }
6946
6947 // When are coming out of an unevaluated context, clear out any
6948 // temporaries that we may have created as part of the evaluation of
6949 // the expression in that context: they aren't relevant because they
6950 // will never be constructed.
6951 if (Rec.Context == Unevaluated &&
6952 ExprTemporaries.size() > Rec.NumTemporaries)
6953 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6954 ExprTemporaries.end());
6955
6956 // Destroy the popped expression evaluation record.
6957 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006958}
Douglas Gregore0762c92009-06-19 23:52:42 +00006959
6960/// \brief Note that the given declaration was referenced in the source code.
6961///
6962/// This routine should be invoke whenever a given declaration is referenced
6963/// in the source code, and where that reference occurred. If this declaration
6964/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6965/// C99 6.9p3), then the declaration will be marked as used.
6966///
6967/// \param Loc the location where the declaration was referenced.
6968///
6969/// \param D the declaration that has been referenced by the source code.
6970void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6971 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006972
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006973 if (D->isUsed())
6974 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006975
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006976 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6977 // template or not. The reason for this is that unevaluated expressions
6978 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6979 // -Wunused-parameters)
6980 if (isa<ParmVarDecl>(D) ||
6981 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006982 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006983
Douglas Gregore0762c92009-06-19 23:52:42 +00006984 // Do not mark anything as "used" within a dependent context; wait for
6985 // an instantiation.
6986 if (CurContext->isDependentContext())
6987 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006988
Douglas Gregor2afce722009-11-26 00:44:06 +00006989 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006990 case Unevaluated:
6991 // We are in an expression that is not potentially evaluated; do nothing.
6992 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006993
Douglas Gregorac7610d2009-06-22 20:57:11 +00006994 case PotentiallyEvaluated:
6995 // We are in a potentially-evaluated expression, so this declaration is
6996 // "used"; handle this below.
6997 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006998
Douglas Gregorac7610d2009-06-22 20:57:11 +00006999 case PotentiallyPotentiallyEvaluated:
7000 // We are in an expression that may be potentially evaluated; queue this
7001 // declaration reference until we know whether the expression is
7002 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007003 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007004 return;
7005 }
Mike Stump1eb44332009-09-09 15:08:12 +00007006
Douglas Gregore0762c92009-06-19 23:52:42 +00007007 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007008 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007009 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007010 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7011 if (!Constructor->isUsed())
7012 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007013 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007014 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007015 if (!Constructor->isUsed())
7016 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7017 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007018
7019 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007020 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7021 if (Destructor->isImplicit() && !Destructor->isUsed())
7022 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007023
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007024 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7025 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7026 MethodDecl->getOverloadedOperator() == OO_Equal) {
7027 if (!MethodDecl->isUsed())
7028 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7029 }
7030 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007031 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007032 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007033 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007034 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007035 bool AlreadyInstantiated = false;
7036 if (FunctionTemplateSpecializationInfo *SpecInfo
7037 = Function->getTemplateSpecializationInfo()) {
7038 if (SpecInfo->getPointOfInstantiation().isInvalid())
7039 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007040 else if (SpecInfo->getTemplateSpecializationKind()
7041 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007042 AlreadyInstantiated = true;
7043 } else if (MemberSpecializationInfo *MSInfo
7044 = Function->getMemberSpecializationInfo()) {
7045 if (MSInfo->getPointOfInstantiation().isInvalid())
7046 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007047 else if (MSInfo->getTemplateSpecializationKind()
7048 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007049 AlreadyInstantiated = true;
7050 }
7051
7052 if (!AlreadyInstantiated)
7053 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7054 }
7055
Douglas Gregore0762c92009-06-19 23:52:42 +00007056 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007057 Function->setUsed(true);
7058 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007059 }
Mike Stump1eb44332009-09-09 15:08:12 +00007060
Douglas Gregore0762c92009-06-19 23:52:42 +00007061 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007062 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007063 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007064 Var->getInstantiatedFromStaticDataMember()) {
7065 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7066 assert(MSInfo && "Missing member specialization information?");
7067 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7068 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7069 MSInfo->setPointOfInstantiation(Loc);
7070 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7071 }
7072 }
Mike Stump1eb44332009-09-09 15:08:12 +00007073
Douglas Gregore0762c92009-06-19 23:52:42 +00007074 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007075
Douglas Gregore0762c92009-06-19 23:52:42 +00007076 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007077 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007078 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007079}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007080
7081bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7082 CallExpr *CE, FunctionDecl *FD) {
7083 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7084 return false;
7085
7086 PartialDiagnostic Note =
7087 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7088 << FD->getDeclName() : PDiag();
7089 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7090
7091 if (RequireCompleteType(Loc, ReturnType,
7092 FD ?
7093 PDiag(diag::err_call_function_incomplete_return)
7094 << CE->getSourceRange() << FD->getDeclName() :
7095 PDiag(diag::err_call_incomplete_return)
7096 << CE->getSourceRange(),
7097 std::make_pair(NoteLoc, Note)))
7098 return true;
7099
7100 return false;
7101}
7102
John McCall5a881bb2009-10-12 21:59:07 +00007103// Diagnose the common s/=/==/ typo. Note that adding parentheses
7104// will prevent this condition from triggering, which is what we want.
7105void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7106 SourceLocation Loc;
7107
John McCalla52ef082009-11-11 02:41:58 +00007108 unsigned diagnostic = diag::warn_condition_is_assignment;
7109
John McCall5a881bb2009-10-12 21:59:07 +00007110 if (isa<BinaryOperator>(E)) {
7111 BinaryOperator *Op = cast<BinaryOperator>(E);
7112 if (Op->getOpcode() != BinaryOperator::Assign)
7113 return;
7114
John McCallc8d8ac52009-11-12 00:06:05 +00007115 // Greylist some idioms by putting them into a warning subcategory.
7116 if (ObjCMessageExpr *ME
7117 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7118 Selector Sel = ME->getSelector();
7119
John McCallc8d8ac52009-11-12 00:06:05 +00007120 // self = [<foo> init...]
7121 if (isSelfExpr(Op->getLHS())
7122 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7123 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7124
7125 // <foo> = [<bar> nextObject]
7126 else if (Sel.isUnarySelector() &&
7127 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7128 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7129 }
John McCalla52ef082009-11-11 02:41:58 +00007130
John McCall5a881bb2009-10-12 21:59:07 +00007131 Loc = Op->getOperatorLoc();
7132 } else if (isa<CXXOperatorCallExpr>(E)) {
7133 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7134 if (Op->getOperator() != OO_Equal)
7135 return;
7136
7137 Loc = Op->getOperatorLoc();
7138 } else {
7139 // Not an assignment.
7140 return;
7141 }
7142
John McCall5a881bb2009-10-12 21:59:07 +00007143 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007144 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007145
John McCalla52ef082009-11-11 02:41:58 +00007146 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007147 << E->getSourceRange()
7148 << CodeModificationHint::CreateInsertion(Open, "(")
7149 << CodeModificationHint::CreateInsertion(Close, ")");
7150}
7151
7152bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7153 DiagnoseAssignmentAsCondition(E);
7154
7155 if (!E->isTypeDependent()) {
7156 DefaultFunctionArrayConversion(E);
7157
7158 QualType T = E->getType();
7159
7160 if (getLangOptions().CPlusPlus) {
7161 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7162 return true;
7163 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7164 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7165 << T << E->getSourceRange();
7166 return true;
7167 }
7168 }
7169
7170 return false;
7171}