blob: 70646dd9ed4b03b7e2ef294a7ecae805fe39b3b8 [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 a C++ class member.
766static bool IsClassMember(NamedDecl *D) {
767 DeclContext *DC = D->getDeclContext();
John McCall336e7742009-12-02 19:59:55 +0000768
John McCall144238e2009-12-02 20:26:00 +0000769 // C++0x [class.mem]p1:
770 // The enumerators of an unscoped enumeration defined in
771 // the class are members of the class.
772 // FIXME: support C++0x scoped enumerations.
773 if (isa<EnumDecl>(DC))
774 DC = DC->getParent();
775
776 return DC->isRecord();
777}
778
779/// Determines if this is an instance member of a class.
780static bool IsInstanceMember(NamedDecl *D) {
781 assert(IsClassMember(D) &&
John McCallaa81e162009-12-01 22:10:20 +0000782 "checking whether non-member is instance member");
783
784 if (isa<FieldDecl>(D)) return true;
785
786 if (isa<CXXMethodDecl>(D))
787 return !cast<CXXMethodDecl>(D)->isStatic();
788
789 if (isa<FunctionTemplateDecl>(D)) {
790 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
791 return !cast<CXXMethodDecl>(D)->isStatic();
792 }
793
794 return false;
795}
796
797enum IMAKind {
798 /// The reference is definitely not an instance member access.
799 IMA_Static,
800
801 /// The reference may be an implicit instance member access.
802 IMA_Mixed,
803
804 /// The reference may be to an instance member, but it is invalid if
805 /// so, because the context is not an instance method.
806 IMA_Mixed_StaticContext,
807
808 /// The reference may be to an instance member, but it is invalid if
809 /// so, because the context is from an unrelated class.
810 IMA_Mixed_Unrelated,
811
812 /// The reference is definitely an implicit instance member access.
813 IMA_Instance,
814
815 /// The reference may be to an unresolved using declaration.
816 IMA_Unresolved,
817
818 /// The reference may be to an unresolved using declaration and the
819 /// context is not an instance method.
820 IMA_Unresolved_StaticContext,
821
822 /// The reference is to a member of an anonymous structure in a
823 /// non-class context.
824 IMA_AnonymousMember,
825
826 /// All possible referrents are instance members and the current
827 /// context is not an instance method.
828 IMA_Error_StaticContext,
829
830 /// All possible referrents are instance members of an unrelated
831 /// class.
832 IMA_Error_Unrelated
833};
834
835/// The given lookup names class member(s) and is not being used for
836/// an address-of-member expression. Classify the type of access
837/// according to whether it's possible that this reference names an
838/// instance member. This is best-effort; it is okay to
839/// conservatively answer "yes", in which case some errors will simply
840/// not be caught until template-instantiation.
841static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
842 const LookupResult &R) {
John McCall144238e2009-12-02 20:26:00 +0000843 assert(!R.empty() && IsClassMember(*R.begin()));
John McCallaa81e162009-12-01 22:10:20 +0000844
845 bool isStaticContext =
846 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
847 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
848
849 if (R.isUnresolvableResult())
850 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
851
852 // Collect all the declaring classes of instance members we find.
853 bool hasNonInstance = false;
854 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
855 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
856 NamedDecl *D = (*I)->getUnderlyingDecl();
857 if (IsInstanceMember(D)) {
858 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
859
860 // If this is a member of an anonymous record, move out to the
861 // innermost non-anonymous struct or union. If there isn't one,
862 // that's a special case.
863 while (R->isAnonymousStructOrUnion()) {
864 R = dyn_cast<CXXRecordDecl>(R->getParent());
865 if (!R) return IMA_AnonymousMember;
866 }
867 Classes.insert(R->getCanonicalDecl());
868 }
869 else
870 hasNonInstance = true;
871 }
872
873 // If we didn't find any instance members, it can't be an implicit
874 // member reference.
875 if (Classes.empty())
876 return IMA_Static;
877
878 // If the current context is not an instance method, it can't be
879 // an implicit member reference.
880 if (isStaticContext)
881 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
882
883 // If we can prove that the current context is unrelated to all the
884 // declaring classes, it can't be an implicit member reference (in
885 // which case it's an error if any of those members are selected).
886 if (IsProvablyNotDerivedFrom(SemaRef,
887 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
888 Classes))
889 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
890
891 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
892}
893
894/// Diagnose a reference to a field with no object available.
895static void DiagnoseInstanceReference(Sema &SemaRef,
896 const CXXScopeSpec &SS,
897 const LookupResult &R) {
898 SourceLocation Loc = R.getNameLoc();
899 SourceRange Range(Loc);
900 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
901
902 if (R.getAsSingle<FieldDecl>()) {
903 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
904 if (MD->isStatic()) {
905 // "invalid use of member 'x' in static member function"
906 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
907 << Range << R.getLookupName();
908 return;
909 }
910 }
911
912 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
913 << R.getLookupName() << Range;
914 return;
915 }
916
917 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000918}
919
John McCallf7a1a742009-11-24 19:00:30 +0000920Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
921 const CXXScopeSpec &SS,
922 UnqualifiedId &Id,
923 bool HasTrailingLParen,
924 bool isAddressOfOperand) {
925 assert(!(isAddressOfOperand && HasTrailingLParen) &&
926 "cannot be direct & operand and have a trailing lparen");
927
928 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000929 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000930
John McCall129e2df2009-11-30 22:42:35 +0000931 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +0000932
933 // Decompose the UnqualifiedId into the following data.
934 DeclarationName Name;
935 SourceLocation NameLoc;
936 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +0000937 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
938 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000939
Douglas Gregor10c42622008-11-18 15:03:34 +0000940 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000941
John McCallf7a1a742009-11-24 19:00:30 +0000942 // C++ [temp.dep.expr]p3:
943 // An id-expression is type-dependent if it contains:
944 // -- a nested-name-specifier that contains a class-name that
945 // names a dependent type.
946 // Determine whether this is a member of an unknown specialization;
947 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +0000948 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +0000949 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000950 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000951 TemplateArgs);
952 }
John McCallba135432009-11-21 08:51:07 +0000953
John McCallf7a1a742009-11-24 19:00:30 +0000954 // Perform the required lookup.
955 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
956 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +0000957 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +0000958 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +0000959 } else {
960 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
John McCallf7a1a742009-11-24 19:00:30 +0000962 // If this reference is in an Objective-C method, then we need to do
963 // some special Objective-C lookup, too.
964 if (!SS.isSet() && II && getCurMethodDecl()) {
965 OwningExprResult E(LookupInObjCMethod(R, S, II));
966 if (E.isInvalid())
967 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000968
John McCallf7a1a742009-11-24 19:00:30 +0000969 Expr *Ex = E.takeAs<Expr>();
970 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000971 }
Chris Lattner8a934232008-03-31 00:36:02 +0000972 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000973
John McCallf7a1a742009-11-24 19:00:30 +0000974 if (R.isAmbiguous())
975 return ExprError();
976
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000977 // Determine whether this name might be a candidate for
978 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000979 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000980
John McCallf7a1a742009-11-24 19:00:30 +0000981 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000983 // in C90, extension in C99, forbidden in C++).
984 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
985 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
986 if (D) R.addDecl(D);
987 }
988
989 // If this name wasn't predeclared and if this is not a function
990 // call, diagnose the problem.
991 if (R.empty()) {
992 if (!SS.isEmpty())
993 return ExprError(Diag(NameLoc, diag::err_no_member)
994 << Name << computeDeclContext(SS, false)
995 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000996 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Sean Hunt3e518bd2009-11-29 07:34:05 +0000997 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000998 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000999 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
1000 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001001 else
John McCallf7a1a742009-11-24 19:00:30 +00001002 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 }
1004 }
Mike Stump1eb44332009-09-09 15:08:12 +00001005
John McCallf7a1a742009-11-24 19:00:30 +00001006 // This is guaranteed from this point on.
1007 assert(!R.empty() || ADL);
1008
1009 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001010 // Warn about constructs like:
1011 // if (void *X = foo()) { ... } else { X }.
1012 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Douglas Gregor751f9a42009-06-30 15:47:41 +00001014 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1015 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001016 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001017 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001018 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001019 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001020 << Var->getDeclName()
1021 << (Var->getType()->isPointerType()? 2 :
1022 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001023 break;
1024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001026 // Move to the parent of this scope.
1027 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001028 }
1029 }
John McCallf7a1a742009-11-24 19:00:30 +00001030 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001031 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1032 // C99 DR 316 says that, if a function type comes from a
1033 // function definition (without a prototype), that type is only
1034 // used for checking compatibility. Therefore, when referencing
1035 // the function, we pretend that we don't have the full function
1036 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001037 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001038 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001039
Douglas Gregor751f9a42009-06-30 15:47:41 +00001040 QualType T = Func->getType();
1041 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001042 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001043 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001044 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001045 }
1046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
John McCallaa81e162009-12-01 22:10:20 +00001048 // Check whether this might be a C++ implicit instance member access.
1049 // C++ [expr.prim.general]p6:
1050 // Within the definition of a non-static member function, an
1051 // identifier that names a non-static member is transformed to a
1052 // class member access expression.
1053 // But note that &SomeClass::foo is grammatically distinct, even
1054 // though we don't parse it that way.
John McCall144238e2009-12-02 20:26:00 +00001055 if (!R.empty() && IsClassMember(*R.begin())) {
John McCallf7a1a742009-11-24 19:00:30 +00001056 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +00001057
John McCallaa81e162009-12-01 22:10:20 +00001058 if (!isAbstractMemberPointer) {
1059 switch (ClassifyImplicitMemberAccess(*this, R)) {
1060 case IMA_Instance:
1061 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1062
1063 case IMA_AnonymousMember:
1064 assert(R.isSingleResult());
1065 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1066 R.getAsSingle<FieldDecl>());
1067
1068 case IMA_Mixed:
1069 case IMA_Mixed_Unrelated:
1070 case IMA_Unresolved:
1071 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1072
1073 case IMA_Static:
1074 case IMA_Mixed_StaticContext:
1075 case IMA_Unresolved_StaticContext:
1076 break;
1077
1078 case IMA_Error_StaticContext:
1079 case IMA_Error_Unrelated:
1080 DiagnoseInstanceReference(*this, SS, R);
1081 return ExprError();
1082 }
John McCall5b3f9132009-11-22 01:44:31 +00001083 }
1084 }
1085
John McCallf7a1a742009-11-24 19:00:30 +00001086 if (TemplateArgs)
1087 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001088
John McCallf7a1a742009-11-24 19:00:30 +00001089 return BuildDeclarationNameExpr(SS, R, ADL);
1090}
1091
John McCall129e2df2009-11-30 22:42:35 +00001092/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1093/// declaration name, generally during template instantiation.
1094/// There's a large number of things which don't need to be done along
1095/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001096Sema::OwningExprResult
1097Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1098 DeclarationName Name,
1099 SourceLocation NameLoc) {
1100 DeclContext *DC;
1101 if (!(DC = computeDeclContext(SS, false)) ||
1102 DC->isDependentContext() ||
1103 RequireCompleteDeclContext(SS))
1104 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1105
1106 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1107 LookupQualifiedName(R, DC);
1108
1109 if (R.isAmbiguous())
1110 return ExprError();
1111
1112 if (R.empty()) {
1113 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1114 return ExprError();
1115 }
1116
1117 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1118}
1119
1120/// LookupInObjCMethod - The parser has read a name in, and Sema has
1121/// detected that we're currently inside an ObjC method. Perform some
1122/// additional lookup.
1123///
1124/// Ideally, most of this would be done by lookup, but there's
1125/// actually quite a lot of extra work involved.
1126///
1127/// Returns a null sentinel to indicate trivial success.
1128Sema::OwningExprResult
1129Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1130 IdentifierInfo *II) {
1131 SourceLocation Loc = Lookup.getNameLoc();
1132
1133 // There are two cases to handle here. 1) scoped lookup could have failed,
1134 // in which case we should look for an ivar. 2) scoped lookup could have
1135 // found a decl, but that decl is outside the current instance method (i.e.
1136 // a global variable). In these two cases, we do a lookup for an ivar with
1137 // this name, if the lookup sucedes, we replace it our current decl.
1138
1139 // If we're in a class method, we don't normally want to look for
1140 // ivars. But if we don't find anything else, and there's an
1141 // ivar, that's an error.
1142 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1143
1144 bool LookForIvars;
1145 if (Lookup.empty())
1146 LookForIvars = true;
1147 else if (IsClassMethod)
1148 LookForIvars = false;
1149 else
1150 LookForIvars = (Lookup.isSingleResult() &&
1151 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1152
1153 if (LookForIvars) {
1154 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1155 ObjCInterfaceDecl *ClassDeclared;
1156 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1157 // Diagnose using an ivar in a class method.
1158 if (IsClassMethod)
1159 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1160 << IV->getDeclName());
1161
1162 // If we're referencing an invalid decl, just return this as a silent
1163 // error node. The error diagnostic was already emitted on the decl.
1164 if (IV->isInvalidDecl())
1165 return ExprError();
1166
1167 // Check if referencing a field with __attribute__((deprecated)).
1168 if (DiagnoseUseOfDecl(IV, Loc))
1169 return ExprError();
1170
1171 // Diagnose the use of an ivar outside of the declaring class.
1172 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1173 ClassDeclared != IFace)
1174 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1175
1176 // FIXME: This should use a new expr for a direct reference, don't
1177 // turn this into Self->ivar, just return a BareIVarExpr or something.
1178 IdentifierInfo &II = Context.Idents.get("self");
1179 UnqualifiedId SelfName;
1180 SelfName.setIdentifier(&II, SourceLocation());
1181 CXXScopeSpec SelfScopeSpec;
1182 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1183 SelfName, false, false);
1184 MarkDeclarationReferenced(Loc, IV);
1185 return Owned(new (Context)
1186 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1187 SelfExpr.takeAs<Expr>(), true, true));
1188 }
1189 } else if (getCurMethodDecl()->isInstanceMethod()) {
1190 // We should warn if a local variable hides an ivar.
1191 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1192 ObjCInterfaceDecl *ClassDeclared;
1193 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1194 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1195 IFace == ClassDeclared)
1196 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1197 }
1198 }
1199
1200 // Needed to implement property "super.method" notation.
1201 if (Lookup.empty() && II->isStr("super")) {
1202 QualType T;
1203
1204 if (getCurMethodDecl()->isInstanceMethod())
1205 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1206 getCurMethodDecl()->getClassInterface()));
1207 else
1208 T = Context.getObjCClassType();
1209 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1210 }
1211
1212 // Sentinel value saying that we didn't do anything special.
1213 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001214}
John McCallba135432009-11-21 08:51:07 +00001215
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001216/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001217bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001218Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1219 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001220 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001221 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001222 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001223 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001224 if (DestType->isDependentType() || From->getType()->isDependentType())
1225 return false;
1226 QualType FromRecordType = From->getType();
1227 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001228 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001229 DestType = Context.getPointerType(DestType);
1230 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001231 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001232 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1233 CheckDerivedToBaseConversion(FromRecordType,
1234 DestRecordType,
1235 From->getSourceRange().getBegin(),
1236 From->getSourceRange()))
1237 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001238 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1239 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001240 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001241 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001242}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001243
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001244/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001245static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001246 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001247 SourceLocation Loc, QualType Ty,
1248 const TemplateArgumentListInfo *TemplateArgs = 0) {
1249 NestedNameSpecifier *Qualifier = 0;
1250 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001251 if (SS.isSet()) {
1252 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1253 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John McCallf7a1a742009-11-24 19:00:30 +00001256 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1257 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001258}
1259
John McCallaa81e162009-12-01 22:10:20 +00001260/// Builds an implicit member access expression. The current context
1261/// is known to be an instance method, and the given unqualified lookup
1262/// set is known to contain only instance members, at least one of which
1263/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001264Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001265Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1266 LookupResult &R,
1267 const TemplateArgumentListInfo *TemplateArgs,
1268 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001269 assert(!R.empty() && !R.isAmbiguous());
1270
John McCallba135432009-11-21 08:51:07 +00001271 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001272
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001273 // We may have found a field within an anonymous union or struct
1274 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001275 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001276 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001277 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001278 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001279 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001280
John McCallaa81e162009-12-01 22:10:20 +00001281 // If this is known to be an instance access, go ahead and build a
1282 // 'this' expression now.
1283 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1284 Expr *This = 0; // null signifies implicit access
1285 if (IsKnownInstance) {
1286 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001287 }
1288
John McCallaa81e162009-12-01 22:10:20 +00001289 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1290 /*OpLoc*/ SourceLocation(),
1291 /*IsArrow*/ true,
1292 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001293}
1294
John McCallf7a1a742009-11-24 19:00:30 +00001295bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001296 const LookupResult &R,
1297 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001298 // Only when used directly as the postfix-expression of a call.
1299 if (!HasTrailingLParen)
1300 return false;
1301
1302 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001303 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001304 return false;
1305
1306 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001307 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001308 return false;
1309
1310 // Turn off ADL when we find certain kinds of declarations during
1311 // normal lookup:
1312 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1313 NamedDecl *D = *I;
1314
1315 // C++0x [basic.lookup.argdep]p3:
1316 // -- a declaration of a class member
1317 // Since using decls preserve this property, we check this on the
1318 // original decl.
John McCall144238e2009-12-02 20:26:00 +00001319 if (IsClassMember(D))
John McCallba135432009-11-21 08:51:07 +00001320 return false;
1321
1322 // C++0x [basic.lookup.argdep]p3:
1323 // -- a block-scope function declaration that is not a
1324 // using-declaration
1325 // NOTE: we also trigger this for function templates (in fact, we
1326 // don't check the decl type at all, since all other decl types
1327 // turn off ADL anyway).
1328 if (isa<UsingShadowDecl>(D))
1329 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1330 else if (D->getDeclContext()->isFunctionOrMethod())
1331 return false;
1332
1333 // C++0x [basic.lookup.argdep]p3:
1334 // -- a declaration that is neither a function or a function
1335 // template
1336 // And also for builtin functions.
1337 if (isa<FunctionDecl>(D)) {
1338 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1339
1340 // But also builtin functions.
1341 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1342 return false;
1343 } else if (!isa<FunctionTemplateDecl>(D))
1344 return false;
1345 }
1346
1347 return true;
1348}
1349
1350
John McCallba135432009-11-21 08:51:07 +00001351/// Diagnoses obvious problems with the use of the given declaration
1352/// as an expression. This is only actually called for lookups that
1353/// were not overloaded, and it doesn't promise that the declaration
1354/// will in fact be used.
1355static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1356 if (isa<TypedefDecl>(D)) {
1357 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1358 return true;
1359 }
1360
1361 if (isa<ObjCInterfaceDecl>(D)) {
1362 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1363 return true;
1364 }
1365
1366 if (isa<NamespaceDecl>(D)) {
1367 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1368 return true;
1369 }
1370
1371 return false;
1372}
1373
1374Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001375Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001376 LookupResult &R,
1377 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001378 // If this is a single, fully-resolved result and we don't need ADL,
1379 // just build an ordinary singleton decl ref.
1380 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001381 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001382
1383 // We only need to check the declaration if there's exactly one
1384 // result, because in the overloaded case the results can only be
1385 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001386 if (R.isSingleResult() &&
1387 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001388 return ExprError();
1389
John McCallf7a1a742009-11-24 19:00:30 +00001390 bool Dependent
1391 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001392 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001393 = UnresolvedLookupExpr::Create(Context, Dependent,
1394 (NestedNameSpecifier*) SS.getScopeRep(),
1395 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001396 R.getLookupName(), R.getNameLoc(),
1397 NeedsADL, R.isOverloadedResult());
1398 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1399 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001400
1401 return Owned(ULE);
1402}
1403
1404
1405/// \brief Complete semantic analysis for a reference to the given declaration.
1406Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001407Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001408 SourceLocation Loc, NamedDecl *D) {
1409 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001410 assert(!isa<FunctionTemplateDecl>(D) &&
1411 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001412 DeclarationName Name = D->getDeclName();
1413
1414 if (CheckDeclInExpr(*this, Loc, D))
1415 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001416
Douglas Gregor9af2f522009-12-01 16:58:18 +00001417 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1418 // Specifically diagnose references to class templates that are missing
1419 // a template argument list.
1420 Diag(Loc, diag::err_template_decl_ref)
1421 << Template << SS.getRange();
1422 Diag(Template->getLocation(), diag::note_template_decl_here);
1423 return ExprError();
1424 }
1425
1426 // Make sure that we're referring to a value.
1427 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1428 if (!VD) {
1429 Diag(Loc, diag::err_ref_non_value)
1430 << D << SS.getRange();
Daniel Dunbarec3455f2009-12-15 04:24:24 +00001431 Diag(D->getLocation(), diag::note_previous_declaration);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001432 return ExprError();
1433 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001434
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001435 // Check whether this declaration can be used. Note that we suppress
1436 // this check when we're going to perform argument-dependent lookup
1437 // on this function name, because this might not be the function
1438 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001439 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001440 return ExprError();
1441
Steve Naroffdd972f22008-09-05 22:11:13 +00001442 // Only create DeclRefExpr's for valid Decl's.
1443 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001444 return ExprError();
1445
Chris Lattner639e2d32008-10-20 05:16:36 +00001446 // If the identifier reference is inside a block, and it refers to a value
1447 // that is outside the block, create a BlockDeclRefExpr instead of a
1448 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1449 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001450 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001451 // We do not do this for things like enum constants, global variables, etc,
1452 // as they do not get snapshotted.
1453 //
1454 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001455 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001456 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001457 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001458 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001459 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001460 // This is to record that a 'const' was actually synthesize and added.
1461 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001462 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Eli Friedman5fdeae12009-03-22 23:00:19 +00001464 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001465 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001466 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001467 }
1468 // If this reference is not in a block or if the referenced variable is
1469 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001470
John McCallf7a1a742009-11-24 19:00:30 +00001471 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472}
1473
Sebastian Redlcd965b92009-01-18 18:53:16 +00001474Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1475 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001476 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001477
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001479 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001480 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1481 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1482 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001484
Chris Lattnerfa28b302008-01-12 08:14:25 +00001485 // Pre-defined identifiers are of type char[x], where x is the length of the
1486 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Anders Carlsson3a082d82009-09-08 18:24:21 +00001488 Decl *currentDecl = getCurFunctionOrMethodDecl();
1489 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001490 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001491 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001492 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001493
Anders Carlsson773f3972009-09-11 01:22:35 +00001494 QualType ResTy;
1495 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1496 ResTy = Context.DependentTy;
1497 } else {
1498 unsigned Length =
1499 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001500
Anders Carlsson773f3972009-09-11 01:22:35 +00001501 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001502 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001503 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1504 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001505 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001506}
1507
Sebastian Redlcd965b92009-01-18 18:53:16 +00001508Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 llvm::SmallString<16> CharBuffer;
1510 CharBuffer.resize(Tok.getLength());
1511 const char *ThisTokBegin = &CharBuffer[0];
1512 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001513
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1515 Tok.getLocation(), PP);
1516 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001517 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001518
1519 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1520
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001521 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1522 Literal.isWide(),
1523 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001524}
1525
Sebastian Redlcd965b92009-01-18 18:53:16 +00001526Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1527 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1529 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001530 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001531 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001532 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001533 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 }
Ted Kremenek28396602009-01-13 23:19:12 +00001535
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001537 // Add padding so that NumericLiteralParser can overread by one character.
1538 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001540
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 // Get the spelling of the token, which eliminates trigraphs, etc.
1542 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001543
Mike Stump1eb44332009-09-09 15:08:12 +00001544 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 Tok.getLocation(), PP);
1546 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001547 return ExprError();
1548
Chris Lattner5d661452007-08-26 03:42:43 +00001549 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001550
Chris Lattner5d661452007-08-26 03:42:43 +00001551 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001552 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001553 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001554 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001555 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001556 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001557 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001558 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001559
1560 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1561
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001562 // isExact will be set by GetFloatValue().
1563 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001564 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1565 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001566
Chris Lattner5d661452007-08-26 03:42:43 +00001567 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001568 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001569 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001570 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571
Neil Boothb9449512007-08-29 22:00:19 +00001572 // long long is a C99 feature.
1573 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001574 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001575 Diag(Tok.getLocation(), diag::ext_longlong);
1576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001578 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001579
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 if (Literal.GetIntegerValue(ResultVal)) {
1581 // If this value didn't fit into uintmax_t, warn and force to ull.
1582 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001583 Ty = Context.UnsignedLongLongTy;
1584 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001585 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 } else {
1587 // If this value fits into a ULL, try to figure out what else it fits into
1588 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1591 // be an unsigned int.
1592 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1593
1594 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001595 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001596 if (!Literal.isLong && !Literal.isLongLong) {
1597 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001598 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001599
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 // Does it fit in a unsigned int?
1601 if (ResultVal.isIntN(IntSize)) {
1602 // Does it fit in a signed int?
1603 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001604 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001606 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001607 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001612 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001613 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001614
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 // Does it fit in a unsigned long?
1616 if (ResultVal.isIntN(LongSize)) {
1617 // Does it fit in a signed long?
1618 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001619 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001621 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001622 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001624 }
1625
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001627 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001628 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // Does it fit in a unsigned long long?
1631 if (ResultVal.isIntN(LongLongSize)) {
1632 // Does it fit in a signed long long?
1633 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001634 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001636 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001637 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 }
1639 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // If we still couldn't decide a type, we probably have something that
1642 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001643 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001645 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001646 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001648
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001649 if (ResultVal.getBitWidth() != Width)
1650 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001652 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001654
Chris Lattner5d661452007-08-26 03:42:43 +00001655 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1656 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001657 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001658 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001659
1660 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001661}
1662
Sebastian Redlcd965b92009-01-18 18:53:16 +00001663Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1664 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001665 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001666 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001667 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001668}
1669
1670/// The UsualUnaryConversions() function is *not* called by this routine.
1671/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001672bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001673 SourceLocation OpLoc,
1674 const SourceRange &ExprRange,
1675 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001676 if (exprType->isDependentType())
1677 return false;
1678
Sebastian Redl5d484e82009-11-23 17:18:46 +00001679 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1680 // the result is the size of the referenced type."
1681 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1682 // result shall be the alignment of the referenced type."
1683 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1684 exprType = Ref->getPointeeType();
1685
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001687 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001688 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001689 if (isSizeof)
1690 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1691 return false;
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Chris Lattner1efaa952009-04-24 00:30:45 +00001694 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001695 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001696 Diag(OpLoc, diag::ext_sizeof_void_type)
1697 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001698 return false;
1699 }
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Chris Lattner1efaa952009-04-24 00:30:45 +00001701 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00001702 PDiag(diag::err_sizeof_alignof_incomplete_type)
1703 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001704 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Chris Lattner1efaa952009-04-24 00:30:45 +00001706 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001707 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001708 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001709 << exprType << isSizeof << ExprRange;
1710 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Chris Lattner1efaa952009-04-24 00:30:45 +00001713 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001714}
1715
Chris Lattner31e21e02009-01-24 20:17:12 +00001716bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1717 const SourceRange &ExprRange) {
1718 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001719
Mike Stump1eb44332009-09-09 15:08:12 +00001720 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001721 if (isa<DeclRefExpr>(E))
1722 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001723
1724 // Cannot know anything else if the expression is dependent.
1725 if (E->isTypeDependent())
1726 return false;
1727
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001728 if (E->getBitField()) {
1729 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1730 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001731 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001732
1733 // Alignment of a field access is always okay, so long as it isn't a
1734 // bit-field.
1735 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001736 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001737 return false;
1738
Chris Lattner31e21e02009-01-24 20:17:12 +00001739 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1740}
1741
Douglas Gregorba498172009-03-13 21:01:28 +00001742/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001743Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001744Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001745 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001746 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001747 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001748 return ExprError();
1749
John McCalla93c9342009-12-07 02:54:59 +00001750 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001751
Douglas Gregorba498172009-03-13 21:01:28 +00001752 if (!T->isDependentType() &&
1753 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1754 return ExprError();
1755
1756 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001757 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001758 Context.getSizeType(), OpLoc,
1759 R.getEnd()));
1760}
1761
1762/// \brief Build a sizeof or alignof expression given an expression
1763/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001764Action::OwningExprResult
1765Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001766 bool isSizeOf, SourceRange R) {
1767 // Verify that the operand is valid.
1768 bool isInvalid = false;
1769 if (E->isTypeDependent()) {
1770 // Delay type-checking for type-dependent expressions.
1771 } else if (!isSizeOf) {
1772 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001773 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001774 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1775 isInvalid = true;
1776 } else {
1777 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1778 }
1779
1780 if (isInvalid)
1781 return ExprError();
1782
1783 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1784 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1785 Context.getSizeType(), OpLoc,
1786 R.getEnd()));
1787}
1788
Sebastian Redl05189992008-11-11 17:56:53 +00001789/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1790/// the same for @c alignof and @c __alignof
1791/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001792Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001793Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1794 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001796 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001797
Sebastian Redl05189992008-11-11 17:56:53 +00001798 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001799 TypeSourceInfo *TInfo;
1800 (void) GetTypeFromParser(TyOrEx, &TInfo);
1801 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001802 }
Sebastian Redl05189992008-11-11 17:56:53 +00001803
Douglas Gregorba498172009-03-13 21:01:28 +00001804 Expr *ArgEx = (Expr *)TyOrEx;
1805 Action::OwningExprResult Result
1806 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1807
1808 if (Result.isInvalid())
1809 DeleteExpr(ArgEx);
1810
1811 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001812}
1813
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001814QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001815 if (V->isTypeDependent())
1816 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Chris Lattnercc26ed72007-08-26 05:39:26 +00001818 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001819 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001820 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Chris Lattnercc26ed72007-08-26 05:39:26 +00001822 // Otherwise they pass through real integer and floating point types here.
1823 if (V->getType()->isArithmeticType())
1824 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Chris Lattnercc26ed72007-08-26 05:39:26 +00001826 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001827 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1828 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001829 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001830}
1831
1832
Reid Spencer5f016e22007-07-11 17:01:13 +00001833
Sebastian Redl0eb23302009-01-19 00:08:26 +00001834Action::OwningExprResult
1835Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1836 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 UnaryOperator::Opcode Opc;
1838 switch (Kind) {
1839 default: assert(0 && "Unknown unary op!");
1840 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1841 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1842 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001843
Eli Friedmane4216e92009-11-18 03:38:04 +00001844 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001845}
1846
Sebastian Redl0eb23302009-01-19 00:08:26 +00001847Action::OwningExprResult
1848Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1849 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001850 // Since this might be a postfix expression, get rid of ParenListExprs.
1851 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1852
Sebastian Redl0eb23302009-01-19 00:08:26 +00001853 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1854 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Douglas Gregor337c6b92008-11-19 17:17:41 +00001856 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001857 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1858 Base.release();
1859 Idx.release();
1860 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1861 Context.DependentTy, RLoc));
1862 }
1863
Mike Stump1eb44332009-09-09 15:08:12 +00001864 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001865 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001866 LHSExp->getType()->isEnumeralType() ||
1867 RHSExp->getType()->isRecordType() ||
1868 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001869 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001870 }
1871
Sebastian Redlf322ed62009-10-29 20:17:01 +00001872 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1873}
1874
1875
1876Action::OwningExprResult
1877Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1878 ExprArg Idx, SourceLocation RLoc) {
1879 Expr *LHSExp = static_cast<Expr*>(Base.get());
1880 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1881
Chris Lattner12d9ff62007-07-16 00:14:47 +00001882 // Perform default conversions.
1883 DefaultFunctionArrayConversion(LHSExp);
1884 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001885
Chris Lattner12d9ff62007-07-16 00:14:47 +00001886 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001887
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001889 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001890 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001892 Expr *BaseExpr, *IndexExpr;
1893 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001894 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1895 BaseExpr = LHSExp;
1896 IndexExpr = RHSExp;
1897 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001898 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001899 BaseExpr = LHSExp;
1900 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001901 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001902 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001903 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001904 BaseExpr = RHSExp;
1905 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001906 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001907 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001908 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001909 BaseExpr = LHSExp;
1910 IndexExpr = RHSExp;
1911 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001912 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001913 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001914 // Handle the uncommon case of "123[Ptr]".
1915 BaseExpr = RHSExp;
1916 IndexExpr = LHSExp;
1917 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001918 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001919 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001920 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001921
Chris Lattner12d9ff62007-07-16 00:14:47 +00001922 // FIXME: need to deal with const...
1923 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001924 } else if (LHSTy->isArrayType()) {
1925 // If we see an array that wasn't promoted by
1926 // DefaultFunctionArrayConversion, it must be an array that
1927 // wasn't promoted because of the C90 rule that doesn't
1928 // allow promoting non-lvalue arrays. Warn, then
1929 // force the promotion here.
1930 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1931 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001932 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1933 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001934 LHSTy = LHSExp->getType();
1935
1936 BaseExpr = LHSExp;
1937 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001938 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001939 } else if (RHSTy->isArrayType()) {
1940 // Same as previous, except for 123[f().a] case
1941 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1942 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001943 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1944 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001945 RHSTy = RHSExp->getType();
1946
1947 BaseExpr = RHSExp;
1948 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001949 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001951 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1952 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001953 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001955 if (!(IndexExpr->getType()->isIntegerType() &&
1956 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001957 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1958 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001959
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001960 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001961 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1962 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001963 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1964
Douglas Gregore7450f52009-03-24 19:52:54 +00001965 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001966 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1967 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001968 // incomplete types are not object types.
1969 if (ResultType->isFunctionType()) {
1970 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1971 << ResultType << BaseExpr->getSourceRange();
1972 return ExprError();
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregore7450f52009-03-24 19:52:54 +00001975 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001976 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001977 PDiag(diag::err_subscript_incomplete_type)
1978 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001979 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Chris Lattner1efaa952009-04-24 00:30:45 +00001981 // Diagnose bad cases where we step over interface counts.
1982 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1983 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1984 << ResultType << BaseExpr->getSourceRange();
1985 return ExprError();
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Sebastian Redl0eb23302009-01-19 00:08:26 +00001988 Base.release();
1989 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001990 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001991 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001992}
1993
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001994QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001995CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001996 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001997 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001998 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1999 // see FIXME there.
2000 //
2001 // FIXME: This logic can be greatly simplified by splitting it along
2002 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002003 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002004
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002005 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002006 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002007
Mike Stumpeed9cac2009-02-19 03:04:26 +00002008 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002009 // special names that indicate a subset of exactly half the elements are
2010 // to be selected.
2011 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002012
Nate Begeman353417a2009-01-18 01:47:54 +00002013 // This flag determines whether or not CompName has an 's' char prefix,
2014 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002015 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002016
2017 // Check that we've found one of the special components, or that the component
2018 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002019 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002020 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2021 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002022 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002023 do
2024 compStr++;
2025 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002026 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002027 do
2028 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002029 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002030 }
Nate Begeman353417a2009-01-18 01:47:54 +00002031
Mike Stumpeed9cac2009-02-19 03:04:26 +00002032 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002033 // We didn't get to the end of the string. This means the component names
2034 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002035 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2036 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002037 return QualType();
2038 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002039
Nate Begeman353417a2009-01-18 01:47:54 +00002040 // Ensure no component accessor exceeds the width of the vector type it
2041 // operates on.
2042 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002043 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002044
2045 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002046 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002047
2048 while (*compStr) {
2049 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2050 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2051 << baseType << SourceRange(CompLoc);
2052 return QualType();
2053 }
2054 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002055 }
Nate Begeman8a997642008-05-09 06:41:27 +00002056
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002057 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002058 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002059 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002060 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002061 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002062 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002063 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002064 if (HexSwizzle)
2065 CompSize--;
2066
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002067 if (CompSize == 1)
2068 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002069
Nate Begeman213541a2008-04-18 23:10:10 +00002070 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002071 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002072 // diagostics look bad. We want extended vector types to appear built-in.
2073 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2074 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2075 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002076 }
2077 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002078}
2079
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002080static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002081 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002082 const Selector &Sel,
2083 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Anders Carlsson8f28f992009-08-26 18:25:21 +00002085 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002086 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002087 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002088 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002090 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2091 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002092 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002093 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002094 return D;
2095 }
2096 return 0;
2097}
2098
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002099static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002100 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002101 const Selector &Sel,
2102 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002103 // Check protocols on qualified interfaces.
2104 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002105 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002106 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002107 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002108 GDecl = PD;
2109 break;
2110 }
2111 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002112 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002113 GDecl = OMD;
2114 break;
2115 }
2116 }
2117 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002118 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002119 E = QIdTy->qual_end(); I != E; ++I) {
2120 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002121 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002122 if (GDecl)
2123 return GDecl;
2124 }
2125 }
2126 return GDecl;
2127}
Chris Lattner76a642f2009-02-15 22:43:40 +00002128
John McCall129e2df2009-11-30 22:42:35 +00002129Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002130Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2131 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002132 const CXXScopeSpec &SS,
2133 NamedDecl *FirstQualifierInScope,
2134 DeclarationName Name, SourceLocation NameLoc,
2135 const TemplateArgumentListInfo *TemplateArgs) {
2136 Expr *BaseExpr = Base.takeAs<Expr>();
2137
2138 // Even in dependent contexts, try to diagnose base expressions with
2139 // obviously wrong types, e.g.:
2140 //
2141 // T* t;
2142 // t.f;
2143 //
2144 // In Obj-C++, however, the above expression is valid, since it could be
2145 // accessing the 'f' property if T is an Obj-C interface. The extra check
2146 // allows this, while still reporting an error if T is a struct pointer.
2147 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002148 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002149 if (PT && (!getLangOptions().ObjC1 ||
2150 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002151 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002152 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002153 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002154 return ExprError();
2155 }
2156 }
2157
John McCallaa81e162009-12-01 22:10:20 +00002158 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002159
2160 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2161 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002162 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002163 IsArrow, OpLoc,
2164 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2165 SS.getRange(),
2166 FirstQualifierInScope,
2167 Name, NameLoc,
2168 TemplateArgs));
2169}
2170
2171/// We know that the given qualified member reference points only to
2172/// declarations which do not belong to the static type of the base
2173/// expression. Diagnose the problem.
2174static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2175 Expr *BaseExpr,
2176 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002177 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002178 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002179 // If this is an implicit member access, use a different set of
2180 // diagnostics.
2181 if (!BaseExpr)
2182 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002183
2184 // FIXME: this is an exceedingly lame diagnostic for some of the more
2185 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002186 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002187 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002188 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002189}
2190
2191// Check whether the declarations we found through a nested-name
2192// specifier in a member expression are actually members of the base
2193// type. The restriction here is:
2194//
2195// C++ [expr.ref]p2:
2196// ... In these cases, the id-expression shall name a
2197// member of the class or of one of its base classes.
2198//
2199// So it's perfectly legitimate for the nested-name specifier to name
2200// an unrelated class, and for us to find an overload set including
2201// decls from classes which are not superclasses, as long as the decl
2202// we actually pick through overload resolution is from a superclass.
2203bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2204 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002205 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002206 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002207 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2208 if (!BaseRT) {
2209 // We can't check this yet because the base type is still
2210 // dependent.
2211 assert(BaseType->isDependentType());
2212 return false;
2213 }
2214 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002215
2216 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002217 // If this is an implicit member reference and we find a
2218 // non-instance member, it's not an error.
2219 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2220 return false;
John McCall129e2df2009-11-30 22:42:35 +00002221
John McCallaa81e162009-12-01 22:10:20 +00002222 // Note that we use the DC of the decl, not the underlying decl.
2223 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2224 while (RecordD->isAnonymousStructOrUnion())
2225 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2226
2227 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2228 MemberRecord.insert(RecordD->getCanonicalDecl());
2229
2230 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2231 return false;
2232 }
2233
John McCall2f841ba2009-12-02 03:53:29 +00002234 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002235 return true;
2236}
2237
2238static bool
2239LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2240 SourceRange BaseRange, const RecordType *RTy,
2241 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2242 RecordDecl *RDecl = RTy->getDecl();
2243 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2244 PDiag(diag::err_typecheck_incomplete_tag)
2245 << BaseRange))
2246 return true;
2247
2248 DeclContext *DC = RDecl;
2249 if (SS.isSet()) {
2250 // If the member name was a qualified-id, look into the
2251 // nested-name-specifier.
2252 DC = SemaRef.computeDeclContext(SS, false);
2253
John McCall2f841ba2009-12-02 03:53:29 +00002254 if (SemaRef.RequireCompleteDeclContext(SS)) {
2255 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2256 << SS.getRange() << DC;
2257 return true;
2258 }
2259
John McCallaa81e162009-12-01 22:10:20 +00002260 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2261
2262 if (!isa<TypeDecl>(DC)) {
2263 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2264 << DC << SS.getRange();
2265 return true;
John McCall129e2df2009-11-30 22:42:35 +00002266 }
2267 }
2268
John McCallaa81e162009-12-01 22:10:20 +00002269 // The record definition is complete, now look up the member.
2270 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002271
2272 return false;
2273}
2274
2275Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002276Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002277 SourceLocation OpLoc, bool IsArrow,
2278 const CXXScopeSpec &SS,
2279 NamedDecl *FirstQualifierInScope,
2280 DeclarationName Name, SourceLocation NameLoc,
2281 const TemplateArgumentListInfo *TemplateArgs) {
2282 Expr *Base = BaseArg.takeAs<Expr>();
2283
John McCall2f841ba2009-12-02 03:53:29 +00002284 if (BaseType->isDependentType() ||
2285 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002286 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002287 IsArrow, OpLoc,
2288 SS, FirstQualifierInScope,
2289 Name, NameLoc,
2290 TemplateArgs);
2291
2292 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002293
John McCallaa81e162009-12-01 22:10:20 +00002294 // Implicit member accesses.
2295 if (!Base) {
2296 QualType RecordTy = BaseType;
2297 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2298 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2299 RecordTy->getAs<RecordType>(),
2300 OpLoc, SS))
2301 return ExprError();
2302
2303 // Explicit member accesses.
2304 } else {
2305 OwningExprResult Result =
2306 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2307 SS, FirstQualifierInScope,
2308 /*ObjCImpDecl*/ DeclPtrTy());
2309
2310 if (Result.isInvalid()) {
2311 Owned(Base);
2312 return ExprError();
2313 }
2314
2315 if (Result.get())
2316 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002317 }
2318
John McCallaa81e162009-12-01 22:10:20 +00002319 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2320 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002321}
2322
2323Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002324Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2325 SourceLocation OpLoc, bool IsArrow,
2326 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002327 LookupResult &R,
2328 const TemplateArgumentListInfo *TemplateArgs) {
2329 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002330 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002331 if (IsArrow) {
2332 assert(BaseType->isPointerType());
2333 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2334 }
2335
2336 NestedNameSpecifier *Qualifier =
2337 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2338 DeclarationName MemberName = R.getLookupName();
2339 SourceLocation MemberLoc = R.getNameLoc();
2340
2341 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002342 return ExprError();
2343
John McCall129e2df2009-11-30 22:42:35 +00002344 if (R.empty()) {
2345 // Rederive where we looked up.
2346 DeclContext *DC = (SS.isSet()
2347 ? computeDeclContext(SS, false)
2348 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002349
John McCall129e2df2009-11-30 22:42:35 +00002350 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002351 << MemberName << DC
2352 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002353 return ExprError();
2354 }
2355
John McCall2f841ba2009-12-02 03:53:29 +00002356 // Diagnose qualified lookups that find only declarations from a
2357 // non-base type. Note that it's okay for lookup to find
2358 // declarations from a non-base type as long as those aren't the
2359 // ones picked by overload resolution.
2360 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002361 return ExprError();
2362
2363 // Construct an unresolved result if we in fact got an unresolved
2364 // result.
2365 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002366 bool Dependent =
2367 R.isUnresolvableResult() ||
2368 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002369
2370 UnresolvedMemberExpr *MemExpr
2371 = UnresolvedMemberExpr::Create(Context, Dependent,
2372 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002373 BaseExpr, BaseExprType,
2374 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002375 Qualifier, SS.getRange(),
2376 MemberName, MemberLoc,
2377 TemplateArgs);
2378 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2379 MemExpr->addDecl(*I);
2380
2381 return Owned(MemExpr);
2382 }
2383
2384 assert(R.isSingleResult());
2385 NamedDecl *MemberDecl = R.getFoundDecl();
2386
2387 // FIXME: diagnose the presence of template arguments now.
2388
2389 // If the decl being referenced had an error, return an error for this
2390 // sub-expr without emitting another error, in order to avoid cascading
2391 // error cases.
2392 if (MemberDecl->isInvalidDecl())
2393 return ExprError();
2394
John McCallaa81e162009-12-01 22:10:20 +00002395 // Handle the implicit-member-access case.
2396 if (!BaseExpr) {
2397 // If this is not an instance member, convert to a non-member access.
2398 if (!IsInstanceMember(MemberDecl))
2399 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2400
2401 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2402 }
2403
John McCall129e2df2009-11-30 22:42:35 +00002404 bool ShouldCheckUse = true;
2405 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2406 // Don't diagnose the use of a virtual member function unless it's
2407 // explicitly qualified.
2408 if (MD->isVirtual() && !SS.isSet())
2409 ShouldCheckUse = false;
2410 }
2411
2412 // Check the use of this member.
2413 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2414 Owned(BaseExpr);
2415 return ExprError();
2416 }
2417
2418 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2419 // We may have found a field within an anonymous union or struct
2420 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002421 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2422 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002423 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2424 BaseExpr, OpLoc);
2425
2426 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2427 QualType MemberType = FD->getType();
2428 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2429 MemberType = Ref->getPointeeType();
2430 else {
2431 Qualifiers BaseQuals = BaseType.getQualifiers();
2432 BaseQuals.removeObjCGCAttr();
2433 if (FD->isMutable()) BaseQuals.removeConst();
2434
2435 Qualifiers MemberQuals
2436 = Context.getCanonicalType(MemberType).getQualifiers();
2437
2438 Qualifiers Combined = BaseQuals + MemberQuals;
2439 if (Combined != MemberQuals)
2440 MemberType = Context.getQualifiedType(MemberType, Combined);
2441 }
2442
2443 MarkDeclarationReferenced(MemberLoc, FD);
2444 if (PerformObjectMemberConversion(BaseExpr, FD))
2445 return ExprError();
2446 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2447 FD, MemberLoc, MemberType));
2448 }
2449
2450 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2451 MarkDeclarationReferenced(MemberLoc, Var);
2452 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2453 Var, MemberLoc,
2454 Var->getType().getNonReferenceType()));
2455 }
2456
2457 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2458 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2459 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2460 MemberFn, MemberLoc,
2461 MemberFn->getType()));
2462 }
2463
2464 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2465 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2466 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2467 Enum, MemberLoc, Enum->getType()));
2468 }
2469
2470 Owned(BaseExpr);
2471
2472 if (isa<TypeDecl>(MemberDecl))
2473 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2474 << MemberName << int(IsArrow));
2475
2476 // We found a declaration kind that we didn't expect. This is a
2477 // generic error message that tells the user that she can't refer
2478 // to this member with '.' or '->'.
2479 return ExprError(Diag(MemberLoc,
2480 diag::err_typecheck_member_reference_unknown)
2481 << MemberName << int(IsArrow));
2482}
2483
2484/// Look up the given member of the given non-type-dependent
2485/// expression. This can return in one of two ways:
2486/// * If it returns a sentinel null-but-valid result, the caller will
2487/// assume that lookup was performed and the results written into
2488/// the provided structure. It will take over from there.
2489/// * Otherwise, the returned expression will be produced in place of
2490/// an ordinary member expression.
2491///
2492/// The ObjCImpDecl bit is a gross hack that will need to be properly
2493/// fixed for ObjC++.
2494Sema::OwningExprResult
2495Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002496 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002497 const CXXScopeSpec &SS,
2498 NamedDecl *FirstQualifierInScope,
2499 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002500 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Steve Naroff3cc4af82007-12-16 21:42:28 +00002502 // Perform default conversions.
2503 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002504
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002505 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002506 assert(!BaseType->isDependentType());
2507
2508 DeclarationName MemberName = R.getLookupName();
2509 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002510
2511 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002512 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002513 // function. Suggest the addition of those parentheses, build the
2514 // call, and continue on.
2515 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2516 if (const FunctionProtoType *Fun
2517 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2518 QualType ResultTy = Fun->getResultType();
2519 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002520 ((!IsArrow && ResultTy->isRecordType()) ||
2521 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002522 ResultTy->getAs<PointerType>()->getPointeeType()
2523 ->isRecordType()))) {
2524 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2525 Diag(Loc, diag::err_member_reference_needs_call)
2526 << QualType(Fun, 0)
2527 << CodeModificationHint::CreateInsertion(Loc, "()");
2528
2529 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002530 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002531 MultiExprArg(*this, 0, 0), 0, Loc);
2532 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002533 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002534
2535 BaseExpr = NewBase.takeAs<Expr>();
2536 DefaultFunctionArrayConversion(BaseExpr);
2537 BaseType = BaseExpr->getType();
2538 }
2539 }
2540 }
2541
David Chisnall0f436562009-08-17 16:35:33 +00002542 // If this is an Objective-C pseudo-builtin and a definition is provided then
2543 // use that.
2544 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002545 if (IsArrow) {
2546 // Handle the following exceptional case PObj->isa.
2547 if (const ObjCObjectPointerType *OPT =
2548 BaseType->getAs<ObjCObjectPointerType>()) {
2549 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2550 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002551 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2552 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002553 }
2554 }
David Chisnall0f436562009-08-17 16:35:33 +00002555 // We have an 'id' type. Rather than fall through, we check if this
2556 // is a reference to 'isa'.
2557 if (BaseType != Context.ObjCIdRedefinitionType) {
2558 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002559 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002560 }
David Chisnall0f436562009-08-17 16:35:33 +00002561 }
John McCall129e2df2009-11-30 22:42:35 +00002562
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002563 // If this is an Objective-C pseudo-builtin and a definition is provided then
2564 // use that.
2565 if (Context.isObjCSelType(BaseType)) {
2566 // We have an 'SEL' type. Rather than fall through, we check if this
2567 // is a reference to 'sel_id'.
2568 if (BaseType != Context.ObjCSelRedefinitionType) {
2569 BaseType = Context.ObjCSelRedefinitionType;
2570 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2571 }
2572 }
John McCall129e2df2009-11-30 22:42:35 +00002573
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002574 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002575
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002576 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002577 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002578 // Also must look for a getter name which uses property syntax.
2579 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2580 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2581 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2582 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2583 ObjCMethodDecl *Getter;
2584 // FIXME: need to also look locally in the implementation.
2585 if ((Getter = IFace->lookupClassMethod(Sel))) {
2586 // Check the use of this method.
2587 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2588 return ExprError();
2589 }
2590 // If we found a getter then this may be a valid dot-reference, we
2591 // will look for the matching setter, in case it is needed.
2592 Selector SetterSel =
2593 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2594 PP.getSelectorTable(), Member);
2595 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2596 if (!Setter) {
2597 // If this reference is in an @implementation, also check for 'private'
2598 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002599 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002600 }
2601 // Look through local category implementations associated with the class.
2602 if (!Setter)
2603 Setter = IFace->getCategoryClassMethod(SetterSel);
2604
2605 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2606 return ExprError();
2607
2608 if (Getter || Setter) {
2609 QualType PType;
2610
2611 if (Getter)
2612 PType = Getter->getResultType();
2613 else
2614 // Get the expression type from Setter's incoming parameter.
2615 PType = (*(Setter->param_end() -1))->getType();
2616 // FIXME: we must check that the setter has property type.
2617 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2618 PType,
2619 Setter, MemberLoc, BaseExpr));
2620 }
2621 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2622 << MemberName << BaseType);
2623 }
2624 }
2625
2626 if (BaseType->isObjCClassType() &&
2627 BaseType != Context.ObjCClassRedefinitionType) {
2628 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002629 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002630 }
Mike Stump1eb44332009-09-09 15:08:12 +00002631
John McCall129e2df2009-11-30 22:42:35 +00002632 if (IsArrow) {
2633 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002634 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002635 else if (BaseType->isObjCObjectPointerType())
2636 ;
John McCall812c1542009-12-07 22:46:59 +00002637 else if (BaseType->isRecordType()) {
2638 // Recover from arrow accesses to records, e.g.:
2639 // struct MyRecord foo;
2640 // foo->bar
2641 // This is actually well-formed in C++ if MyRecord has an
2642 // overloaded operator->, but that should have been dealt with
2643 // by now.
2644 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2645 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2646 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2647 IsArrow = false;
2648 } else {
John McCall129e2df2009-11-30 22:42:35 +00002649 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2650 << BaseType << BaseExpr->getSourceRange();
2651 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002652 }
John McCall812c1542009-12-07 22:46:59 +00002653 } else {
2654 // Recover from dot accesses to pointers, e.g.:
2655 // type *foo;
2656 // foo.bar
2657 // This is actually well-formed in two cases:
2658 // - 'type' is an Objective C type
2659 // - 'bar' is a pseudo-destructor name which happens to refer to
2660 // the appropriate pointer type
2661 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2662 const PointerType *PT = BaseType->getAs<PointerType>();
2663 if (PT && PT->getPointeeType()->isRecordType()) {
2664 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2665 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2666 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2667 BaseType = PT->getPointeeType();
2668 IsArrow = true;
2669 }
2670 }
John McCall129e2df2009-11-30 22:42:35 +00002671 }
John McCall812c1542009-12-07 22:46:59 +00002672
John McCall129e2df2009-11-30 22:42:35 +00002673 // Handle field access to simple records. This also handles access
2674 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002675 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002676 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2677 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002678 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002679 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002680 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002681
Douglas Gregora71d8192009-09-04 17:36:40 +00002682 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2683 // into a record type was handled above, any destructor we see here is a
2684 // pseudo-destructor.
2685 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2686 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002687 // The left hand side of the dot operator shall be of scalar type. The
2688 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002689 // type.
2690 if (!BaseType->isScalarType())
2691 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2692 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Douglas Gregora71d8192009-09-04 17:36:40 +00002694 // [...] The type designated by the pseudo-destructor-name shall be the
2695 // same as the object type.
2696 if (!MemberName.getCXXNameType()->isDependentType() &&
2697 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2698 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2699 << BaseType << MemberName.getCXXNameType()
2700 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002701
2702 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002703 // the form
2704 //
Mike Stump1eb44332009-09-09 15:08:12 +00002705 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2706 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002707 // shall designate the same scalar type.
2708 //
2709 // FIXME: DPG can't see any way to trigger this particular clause, so it
2710 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Douglas Gregora71d8192009-09-04 17:36:40 +00002712 // FIXME: We've lost the precise spelling of the type by going through
2713 // DeclarationName. Can we do better?
2714 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002715 IsArrow, OpLoc,
2716 (NestedNameSpecifier *) SS.getScopeRep(),
2717 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002718 MemberName.getCXXNameType(),
2719 MemberLoc));
2720 }
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Chris Lattnera38e6b12008-07-21 04:59:05 +00002722 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2723 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002724 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2725 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002726 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002727 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002728 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002729 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002730 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2731
Steve Naroffc70e8d92009-07-16 00:25:06 +00002732 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2733 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002734 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Steve Naroffc70e8d92009-07-16 00:25:06 +00002736 if (IV) {
2737 // If the decl being referenced had an error, return an error for this
2738 // sub-expr without emitting another error, in order to avoid cascading
2739 // error cases.
2740 if (IV->isInvalidDecl())
2741 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002742
Steve Naroffc70e8d92009-07-16 00:25:06 +00002743 // Check whether we can reference this field.
2744 if (DiagnoseUseOfDecl(IV, MemberLoc))
2745 return ExprError();
2746 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2747 IV->getAccessControl() != ObjCIvarDecl::Package) {
2748 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2749 if (ObjCMethodDecl *MD = getCurMethodDecl())
2750 ClassOfMethodDecl = MD->getClassInterface();
2751 else if (ObjCImpDecl && getCurFunctionDecl()) {
2752 // Case of a c-function declared inside an objc implementation.
2753 // FIXME: For a c-style function nested inside an objc implementation
2754 // class, there is no implementation context available, so we pass
2755 // down the context as argument to this routine. Ideally, this context
2756 // need be passed down in the AST node and somehow calculated from the
2757 // AST for a function decl.
2758 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002759 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002760 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2761 ClassOfMethodDecl = IMPD->getClassInterface();
2762 else if (ObjCCategoryImplDecl* CatImplClass =
2763 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2764 ClassOfMethodDecl = CatImplClass->getClassInterface();
2765 }
Mike Stump1eb44332009-09-09 15:08:12 +00002766
2767 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2768 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002769 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002770 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002771 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002772 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2773 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002774 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002775 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002776 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002777
2778 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2779 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002780 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002781 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002782 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002783 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002784 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002785 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002786 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002787 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002788 if (!IsArrow && (BaseType->isObjCIdType() ||
2789 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002790 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002791 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Steve Naroff14108da2009-07-10 23:34:53 +00002793 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002794 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002795 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2796 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2797 // Check the use of this declaration
2798 if (DiagnoseUseOfDecl(PD, MemberLoc))
2799 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Steve Naroff14108da2009-07-10 23:34:53 +00002801 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2802 MemberLoc, BaseExpr));
2803 }
2804 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2805 // Check the use of this method.
2806 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2807 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002808
Steve Naroff14108da2009-07-10 23:34:53 +00002809 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002810 OMD->getResultType(),
2811 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002812 NULL, 0));
2813 }
2814 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002815
Steve Naroff14108da2009-07-10 23:34:53 +00002816 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002817 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002818 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002819 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2820 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002821 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002822 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002823 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2824 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002825 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Daniel Dunbar2307d312008-09-03 01:05:41 +00002827 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002828 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002829 // Check whether we can reference this property.
2830 if (DiagnoseUseOfDecl(PD, MemberLoc))
2831 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002832 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002833 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002834 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002835 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2836 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002837 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002838 MemberLoc, BaseExpr));
2839 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002840 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002841 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2842 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002843 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002844 // Check whether we can reference this property.
2845 if (DiagnoseUseOfDecl(PD, MemberLoc))
2846 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002847
Steve Naroff6ece14c2009-01-21 00:14:39 +00002848 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002849 MemberLoc, BaseExpr));
2850 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002851 // If that failed, look for an "implicit" property by seeing if the nullary
2852 // selector is implemented.
2853
2854 // FIXME: The logic for looking up nullary and unary selectors should be
2855 // shared with the code in ActOnInstanceMessage.
2856
Anders Carlsson8f28f992009-08-26 18:25:21 +00002857 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002858 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002859
Daniel Dunbar2307d312008-09-03 01:05:41 +00002860 // If this reference is in an @implementation, check for 'private' methods.
2861 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002862 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002863
Steve Naroff7692ed62008-10-22 19:16:27 +00002864 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002865 if (!Getter)
2866 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002867 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002868 // Check if we can reference this property.
2869 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2870 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002871 }
2872 // If we found a getter then this may be a valid dot-reference, we
2873 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002874 Selector SetterSel =
2875 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002876 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002877 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002878 if (!Setter) {
2879 // If this reference is in an @implementation, also check for 'private'
2880 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002881 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002882 }
2883 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002884 if (!Setter)
2885 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002886
Steve Naroff1ca66942009-03-11 13:48:17 +00002887 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2888 return ExprError();
2889
2890 if (Getter || Setter) {
2891 QualType PType;
2892
2893 if (Getter)
2894 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002895 else
2896 // Get the expression type from Setter's incoming parameter.
2897 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002898 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002899 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002900 Setter, MemberLoc, BaseExpr));
2901 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002902 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002903 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002904 }
Mike Stump1eb44332009-09-09 15:08:12 +00002905
Steve Narofff242b1b2009-07-24 17:54:45 +00002906 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00002907 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002908 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002909 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002910 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002911 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00002912
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002913 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002914 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002915 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002916 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2917 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002918 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002919 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002920 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002921 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002922
Douglas Gregor214f31a2009-03-27 06:00:30 +00002923 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2924 << BaseType << BaseExpr->getSourceRange();
2925
Douglas Gregor214f31a2009-03-27 06:00:30 +00002926 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002927}
2928
John McCall129e2df2009-11-30 22:42:35 +00002929static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2930 SourceLocation NameLoc,
2931 Sema::ExprArg MemExpr) {
2932 Expr *E = (Expr *) MemExpr.get();
2933 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2934 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002935 << isa<CXXPseudoDestructorExpr>(E)
2936 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2937
John McCall129e2df2009-11-30 22:42:35 +00002938 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2939 move(MemExpr),
2940 /*LPLoc*/ ExpectedLParenLoc,
2941 Sema::MultiExprArg(SemaRef, 0, 0),
2942 /*CommaLocs*/ 0,
2943 /*RPLoc*/ ExpectedLParenLoc);
2944}
2945
2946/// The main callback when the parser finds something like
2947/// expression . [nested-name-specifier] identifier
2948/// expression -> [nested-name-specifier] identifier
2949/// where 'identifier' encompasses a fairly broad spectrum of
2950/// possibilities, including destructor and operator references.
2951///
2952/// \param OpKind either tok::arrow or tok::period
2953/// \param HasTrailingLParen whether the next token is '(', which
2954/// is used to diagnose mis-uses of special members that can
2955/// only be called
2956/// \param ObjCImpDecl the current ObjC @implementation decl;
2957/// this is an ugly hack around the fact that ObjC @implementations
2958/// aren't properly put in the context chain
2959Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2960 SourceLocation OpLoc,
2961 tok::TokenKind OpKind,
2962 const CXXScopeSpec &SS,
2963 UnqualifiedId &Id,
2964 DeclPtrTy ObjCImpDecl,
2965 bool HasTrailingLParen) {
2966 if (SS.isSet() && SS.isInvalid())
2967 return ExprError();
2968
2969 TemplateArgumentListInfo TemplateArgsBuffer;
2970
2971 // Decompose the name into its component parts.
2972 DeclarationName Name;
2973 SourceLocation NameLoc;
2974 const TemplateArgumentListInfo *TemplateArgs;
2975 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2976 Name, NameLoc, TemplateArgs);
2977
2978 bool IsArrow = (OpKind == tok::arrow);
2979
2980 NamedDecl *FirstQualifierInScope
2981 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2982 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2983
2984 // This is a postfix expression, so get rid of ParenListExprs.
2985 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2986
2987 Expr *Base = BaseArg.takeAs<Expr>();
2988 OwningExprResult Result(*this);
2989 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00002990 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00002991 IsArrow, OpLoc,
2992 SS, FirstQualifierInScope,
2993 Name, NameLoc,
2994 TemplateArgs);
2995 } else {
2996 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2997 if (TemplateArgs) {
2998 // Re-use the lookup done for the template name.
2999 DecomposeTemplateName(R, Id);
3000 } else {
3001 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3002 SS, FirstQualifierInScope,
3003 ObjCImpDecl);
3004
3005 if (Result.isInvalid()) {
3006 Owned(Base);
3007 return ExprError();
3008 }
3009
3010 if (Result.get()) {
3011 // The only way a reference to a destructor can be used is to
3012 // immediately call it, which falls into this case. If the
3013 // next token is not a '(', produce a diagnostic and build the
3014 // call now.
3015 if (!HasTrailingLParen &&
3016 Id.getKind() == UnqualifiedId::IK_DestructorName)
3017 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3018
3019 return move(Result);
3020 }
3021 }
3022
John McCallaa81e162009-12-01 22:10:20 +00003023 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3024 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003025 }
3026
3027 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003028}
3029
Anders Carlsson56c5e332009-08-25 03:49:14 +00003030Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3031 FunctionDecl *FD,
3032 ParmVarDecl *Param) {
3033 if (Param->hasUnparsedDefaultArg()) {
3034 Diag (CallLoc,
3035 diag::err_use_of_default_argument_to_function_declared_later) <<
3036 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003037 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003038 diag::note_default_argument_declared_here);
3039 } else {
3040 if (Param->hasUninstantiatedDefaultArg()) {
3041 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3042
3043 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003044 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003045
Mike Stump1eb44332009-09-09 15:08:12 +00003046 InstantiatingTemplate Inst(*this, CallLoc, Param,
3047 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003048 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003049
John McCallce3ff2b2009-08-25 22:02:44 +00003050 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003051 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003052 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003053
3054 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00003055 /*FIXME:EqualLoc*/
3056 UninstExpr->getSourceRange().getBegin()))
3057 return ExprError();
3058 }
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Anders Carlsson56c5e332009-08-25 03:49:14 +00003060 // If the default expression creates temporaries, we need to
3061 // push them to the current stack of expression temporaries so they'll
3062 // be properly destroyed.
Anders Carlsson337cba42009-12-15 19:16:31 +00003063 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3064 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003065 }
3066
3067 // We already type-checked the argument, so we know it works.
3068 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3069}
3070
Douglas Gregor88a35142008-12-22 05:46:06 +00003071/// ConvertArgumentsForCall - Converts the arguments specified in
3072/// Args/NumArgs to the parameter types of the function FDecl with
3073/// function prototype Proto. Call is the call expression itself, and
3074/// Fn is the function expression. For a C++ member function, this
3075/// routine does not attempt to convert the object argument. Returns
3076/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003077bool
3078Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003079 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003080 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003081 Expr **Args, unsigned NumArgs,
3082 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003083 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003084 // assignment, to the types of the corresponding parameter, ...
3085 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003086 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003087
Douglas Gregor88a35142008-12-22 05:46:06 +00003088 // If too few arguments are available (and we don't have default
3089 // arguments for the remaining parameters), don't make the call.
3090 if (NumArgs < NumArgsInProto) {
3091 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3092 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3093 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003094 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003095 }
3096
3097 // If too many are passed and not variadic, error on the extras and drop
3098 // them.
3099 if (NumArgs > NumArgsInProto) {
3100 if (!Proto->isVariadic()) {
3101 Diag(Args[NumArgsInProto]->getLocStart(),
3102 diag::err_typecheck_call_too_many_args)
3103 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3104 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3105 Args[NumArgs-1]->getLocEnd());
3106 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003107 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003108 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003109 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003110 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003111 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003112 VariadicCallType CallType =
3113 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3114 if (Fn->getType()->isBlockPointerType())
3115 CallType = VariadicBlock; // Block
3116 else if (isa<MemberExpr>(Fn))
3117 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003118 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003119 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003120 if (Invalid)
3121 return true;
3122 unsigned TotalNumArgs = AllArgs.size();
3123 for (unsigned i = 0; i < TotalNumArgs; ++i)
3124 Call->setArg(i, AllArgs[i]);
3125
3126 return false;
3127}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003128
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003129bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3130 FunctionDecl *FDecl,
3131 const FunctionProtoType *Proto,
3132 unsigned FirstProtoArg,
3133 Expr **Args, unsigned NumArgs,
3134 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003135 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003136 unsigned NumArgsInProto = Proto->getNumArgs();
3137 unsigned NumArgsToCheck = NumArgs;
3138 bool Invalid = false;
3139 if (NumArgs != NumArgsInProto)
3140 // Use default arguments for missing arguments
3141 NumArgsToCheck = NumArgsInProto;
3142 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003143 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003144 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003145 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003146
Douglas Gregor88a35142008-12-22 05:46:06 +00003147 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003148 if (ArgIx < NumArgs) {
3149 Arg = Args[ArgIx++];
3150
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003151 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3152 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003153 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003154 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003155 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003156
Douglas Gregor61366e92008-12-24 00:01:03 +00003157 // Pass the argument.
3158 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3159 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00003160
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00003161 if (!ProtoArgType->isReferenceType())
3162 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003163 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003164 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003165
Mike Stump1eb44332009-09-09 15:08:12 +00003166 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003167 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003168 if (ArgExpr.isInvalid())
3169 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003170
Anders Carlsson56c5e332009-08-25 03:49:14 +00003171 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003172 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003173 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003174 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003175
Douglas Gregor88a35142008-12-22 05:46:06 +00003176 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003177 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003178 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003179 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003180 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003181 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003182 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003183 }
3184 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003185 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003186}
3187
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003188/// \brief "Deconstruct" the function argument of a call expression to find
3189/// the underlying declaration (if any), the name of the called function,
3190/// whether argument-dependent lookup is available, whether it has explicit
3191/// template arguments, etc.
3192void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00003193 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003194 DeclarationName &Name,
3195 NestedNameSpecifier *&Qualifier,
3196 SourceRange &QualifierRange,
3197 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00003198 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003199 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00003200 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003201 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003202 Name = DeclarationName();
3203 Qualifier = 0;
3204 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00003205 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00003206 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003207 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00003208
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003209 // If we're directly calling a function, get the appropriate declaration.
3210 // Also, in C++, keep track of whether we should perform argument-dependent
3211 // lookup and whether there were any explicitly-specified template arguments.
3212 while (true) {
3213 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3214 FnExpr = IcExpr->getSubExpr();
3215 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003216 FnExpr = PExpr->getSubExpr();
3217 } else if (isa<UnaryOperator>(FnExpr) &&
3218 cast<UnaryOperator>(FnExpr)->getOpcode()
3219 == UnaryOperator::AddrOf) {
3220 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003221 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00003222 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3223 ArgumentDependentLookup = false;
3224 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00003225 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003226 break;
John McCallba135432009-11-21 08:51:07 +00003227 } else if (UnresolvedLookupExpr *UnresLookup
3228 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3229 Name = UnresLookup->getName();
3230 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3231 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00003232 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00003233 if ((Qualifier = UnresLookup->getQualifier()))
3234 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00003235 if (UnresLookup->hasExplicitTemplateArgs()) {
3236 HasExplicitTemplateArguments = true;
3237 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003238 }
3239 break;
3240 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003241 break;
3242 }
3243 }
3244}
3245
Steve Narofff69936d2007-09-16 03:34:24 +00003246/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003247/// This provides the location of the left/right parens and a list of comma
3248/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003249Action::OwningExprResult
3250Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3251 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003252 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003253 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003254
3255 // Since this might be a postfix expression, get rid of ParenListExprs.
3256 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003257
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003258 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003259 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003260 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Douglas Gregor88a35142008-12-22 05:46:06 +00003262 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003263 // If this is a pseudo-destructor expression, build the call immediately.
3264 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3265 if (NumArgs > 0) {
3266 // Pseudo-destructor calls should not have any arguments.
3267 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3268 << CodeModificationHint::CreateRemoval(
3269 SourceRange(Args[0]->getLocStart(),
3270 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003271
Douglas Gregora71d8192009-09-04 17:36:40 +00003272 for (unsigned I = 0; I != NumArgs; ++I)
3273 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Douglas Gregora71d8192009-09-04 17:36:40 +00003275 NumArgs = 0;
3276 }
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Douglas Gregora71d8192009-09-04 17:36:40 +00003278 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3279 RParenLoc));
3280 }
Mike Stump1eb44332009-09-09 15:08:12 +00003281
Douglas Gregor17330012009-02-04 15:01:18 +00003282 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003283 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003284 // FIXME: Will need to cache the results of name lookup (including ADL) in
3285 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003286 bool Dependent = false;
3287 if (Fn->isTypeDependent())
3288 Dependent = true;
3289 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3290 Dependent = true;
3291
3292 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003293 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003294 Context.DependentTy, RParenLoc));
3295
3296 // Determine whether this is a call to an object (C++ [over.call.object]).
3297 if (Fn->getType()->isRecordType())
3298 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3299 CommaLocs, RParenLoc));
3300
John McCall129e2df2009-11-30 22:42:35 +00003301 Expr *NakedFn = Fn->IgnoreParens();
3302
3303 // Determine whether this is a call to an unresolved member function.
3304 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3305 // If lookup was unresolved but not dependent (i.e. didn't find
3306 // an unresolved using declaration), it has to be an overloaded
3307 // function set, which means it must contain either multiple
3308 // declarations (all methods or method templates) or a single
3309 // method template.
3310 assert((MemE->getNumDecls() > 1) ||
3311 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003312 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003313
John McCallaa81e162009-12-01 22:10:20 +00003314 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3315 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003316 }
3317
Douglas Gregorfa047642009-02-04 00:32:51 +00003318 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003319 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003320 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003321 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003322 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3323 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003324 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003325
3326 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003328 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3329 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003330 if (const FunctionProtoType *FPT =
3331 dyn_cast<FunctionProtoType>(BO->getType())) {
3332 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003333
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003334 ExprOwningPtr<CXXMemberCallExpr>
3335 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3336 NumArgs, ResultTy,
3337 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003338
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003339 if (CheckCallReturnType(FPT->getResultType(),
3340 BO->getRHS()->getSourceRange().getBegin(),
3341 TheCall.get(), 0))
3342 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003343
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003344 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3345 RParenLoc))
3346 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003347
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003348 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3349 }
3350 return ExprError(Diag(Fn->getLocStart(),
3351 diag::err_typecheck_call_not_function)
3352 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003353 }
3354 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003355 }
3356
Douglas Gregorfa047642009-02-04 00:32:51 +00003357 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003358 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003359 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00003360 llvm::SmallVector<NamedDecl*,8> Fns;
3361 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00003362 bool Overloaded;
3363 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003364 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00003365 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003366 NestedNameSpecifier *Qualifier = 0;
3367 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00003368 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00003369 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00003370 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003371
John McCall7453ed42009-11-22 00:44:51 +00003372 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3373 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00003374
John McCall7453ed42009-11-22 00:44:51 +00003375 if (Overloaded || ADL) {
3376#ifndef NDEBUG
3377 if (ADL) {
3378 // To do ADL, we must have found an unqualified name.
3379 assert(UnqualifiedName && "found no unqualified name for ADL");
3380
3381 // We don't perform ADL for implicit declarations of builtins.
3382 // Verify that this was correctly set up.
3383 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3384 FDecl->getBuiltinID() && FDecl->isImplicit())
3385 assert(0 && "performing ADL for builtin");
3386
3387 // We don't perform ADL in C.
3388 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3389 }
3390
3391 if (Overloaded) {
3392 // To be overloaded, we must either have multiple functions or
3393 // at least one function template (which is effectively an
3394 // infinite set of functions).
3395 assert((Fns.size() > 1 ||
3396 (Fns.size() == 1 &&
3397 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3398 && "unrecognized overload situation");
3399 }
3400#endif
3401
3402 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00003403 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00003404 LParenLoc, Args, NumArgs, CommaLocs,
3405 RParenLoc, ADL);
3406 if (!FDecl)
3407 return ExprError();
3408
3409 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3410
3411 NDecl = FDecl;
3412 } else {
3413 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3414 if (Fns.empty())
John McCallaa81e162009-12-01 22:10:20 +00003415 NDecl = 0;
John McCall7453ed42009-11-22 00:44:51 +00003416 else {
3417 NDecl = Fns[0];
Douglas Gregorfa047642009-02-04 00:32:51 +00003418 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003419 }
Chris Lattner04421082008-04-08 04:40:51 +00003420
John McCallaa81e162009-12-01 22:10:20 +00003421 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3422}
3423
3424/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3425/// expression not of \p OverloadTy. The expression should
3426/// unary-convert to an expression of function-pointer or
3427/// block-pointer type.
3428///
3429/// \param NDecl the declaration being called, if available
3430Sema::OwningExprResult
3431Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3432 SourceLocation LParenLoc,
3433 Expr **Args, unsigned NumArgs,
3434 SourceLocation RParenLoc) {
3435 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3436
Chris Lattner04421082008-04-08 04:40:51 +00003437 // Promote the function operand.
3438 UsualUnaryConversions(Fn);
3439
Chris Lattner925e60d2007-12-28 05:29:59 +00003440 // Make the call expr early, before semantic checks. This guarantees cleanup
3441 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003442 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3443 Args, NumArgs,
3444 Context.BoolTy,
3445 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003446
Steve Naroffdd972f22008-09-05 22:11:13 +00003447 const FunctionType *FuncT;
3448 if (!Fn->getType()->isBlockPointerType()) {
3449 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3450 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003451 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003452 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003453 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3454 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003455 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003456 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003457 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003458 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003459 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003460 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003461 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3462 << Fn->getType() << Fn->getSourceRange());
3463
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003464 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003465 if (CheckCallReturnType(FuncT->getResultType(),
3466 Fn->getSourceRange().getBegin(), TheCall.get(),
3467 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003468 return ExprError();
3469
Chris Lattner925e60d2007-12-28 05:29:59 +00003470 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003471 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003472
Douglas Gregor72564e72009-02-26 23:50:07 +00003473 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003474 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003475 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003476 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003477 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003478 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003479
Douglas Gregor74734d52009-04-02 15:37:10 +00003480 if (FDecl) {
3481 // Check if we have too few/too many template arguments, based
3482 // on our knowledge of the function definition.
3483 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003484 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003485 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003486 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003487 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3488 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3489 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3490 }
3491 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003492 }
3493
Steve Naroffb291ab62007-08-28 23:30:39 +00003494 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003495 for (unsigned i = 0; i != NumArgs; i++) {
3496 Expr *Arg = Args[i];
3497 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003498 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3499 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003500 PDiag(diag::err_call_incomplete_argument)
3501 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003502 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003503 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003504 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003505 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003506
Douglas Gregor88a35142008-12-22 05:46:06 +00003507 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3508 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003509 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3510 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003511
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003512 // Check for sentinels
3513 if (NDecl)
3514 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Chris Lattner59907c42007-08-10 20:18:51 +00003516 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003517 if (FDecl) {
3518 if (CheckFunctionCall(FDecl, TheCall.get()))
3519 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003521 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003522 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3523 } else if (NDecl) {
3524 if (CheckBlockCall(NDecl, TheCall.get()))
3525 return ExprError();
3526 }
Chris Lattner59907c42007-08-10 20:18:51 +00003527
Anders Carlssonec74c592009-08-16 03:06:32 +00003528 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003529}
3530
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003531Action::OwningExprResult
3532Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3533 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003534 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor99a2e602009-12-16 01:38:02 +00003535
3536 TypeSourceInfo *TInfo = 0;
3537 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3538 if (!TInfo)
3539 TInfo = Context.getTrivialTypeSourceInfo(literalType, LParenLoc);
3540
Steve Naroffaff1edd2007-07-19 21:32:11 +00003541 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003542 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003543 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003544
Eli Friedman6223c222008-05-20 05:22:08 +00003545 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003546 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003547 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3548 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003549 } else if (!literalType->isDependentType() &&
3550 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003551 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003552 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003553 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003554 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003555
Douglas Gregor99a2e602009-12-16 01:38:02 +00003556 InitializedEntity Entity
3557 = InitializedEntity::InitializeTemporary(TInfo->getTypeLoc());
3558 InitializationKind Kind
3559 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3560 /*IsCStyleCast=*/true);
3561 if (CheckInitializerTypes(literalExpr, literalType, Entity, Kind))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003562 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003563
Chris Lattner371f2582008-12-04 23:50:19 +00003564 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003565 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003566 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003567 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003568 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003569 InitExpr.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003570
3571 // FIXME: Store the TInfo to preserve type information better.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003572 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003573 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003574}
3575
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003576Action::OwningExprResult
3577Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003578 SourceLocation RBraceLoc) {
3579 unsigned NumInit = initlist.size();
3580 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003581
Steve Naroff08d92e42007-09-15 18:49:24 +00003582 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003583 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003584
Mike Stumpeed9cac2009-02-19 03:04:26 +00003585 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003586 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003587 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003588 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003589}
3590
Anders Carlsson82debc72009-10-18 18:12:03 +00003591static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3592 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003593 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003594 return CastExpr::CK_NoOp;
3595
3596 if (SrcTy->hasPointerRepresentation()) {
3597 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003598 return DestTy->isObjCObjectPointerType() ?
3599 CastExpr::CK_AnyPointerToObjCPointerCast :
3600 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003601 if (DestTy->isIntegerType())
3602 return CastExpr::CK_PointerToIntegral;
3603 }
3604
3605 if (SrcTy->isIntegerType()) {
3606 if (DestTy->isIntegerType())
3607 return CastExpr::CK_IntegralCast;
3608 if (DestTy->hasPointerRepresentation())
3609 return CastExpr::CK_IntegralToPointer;
3610 if (DestTy->isRealFloatingType())
3611 return CastExpr::CK_IntegralToFloating;
3612 }
3613
3614 if (SrcTy->isRealFloatingType()) {
3615 if (DestTy->isRealFloatingType())
3616 return CastExpr::CK_FloatingCast;
3617 if (DestTy->isIntegerType())
3618 return CastExpr::CK_FloatingToIntegral;
3619 }
3620
3621 // FIXME: Assert here.
3622 // assert(false && "Unhandled cast combination!");
3623 return CastExpr::CK_Unknown;
3624}
3625
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003626/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003627bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003628 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003629 CXXMethodDecl *& ConversionDecl,
3630 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003631 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003632 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3633 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003634
Eli Friedman199ea952009-08-15 19:02:19 +00003635 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003636
3637 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3638 // type needs to be scalar.
3639 if (castType->isVoidType()) {
3640 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003641 Kind = CastExpr::CK_ToVoid;
3642 return false;
3643 }
3644
3645 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003646 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003647 (castType->isStructureType() || castType->isUnionType())) {
3648 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003649 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003650 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3651 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003652 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003653 return false;
3654 }
3655
3656 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003657 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003658 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003659 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003660 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003661 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003662 if (Context.hasSameUnqualifiedType(Field->getType(),
3663 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003664 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3665 << castExpr->getSourceRange();
3666 break;
3667 }
3668 }
3669 if (Field == FieldEnd)
3670 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3671 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003672 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003673 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003674 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003675
3676 // Reject any other conversions to non-scalar types.
3677 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3678 << castType << castExpr->getSourceRange();
3679 }
3680
3681 if (!castExpr->getType()->isScalarType() &&
3682 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003683 return Diag(castExpr->getLocStart(),
3684 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003685 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003686 }
3687
Anders Carlsson16a89042009-10-16 05:23:41 +00003688 if (castType->isExtVectorType())
3689 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3690
Anders Carlssonc3516322009-10-16 02:48:28 +00003691 if (castType->isVectorType())
3692 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3693 if (castExpr->getType()->isVectorType())
3694 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3695
3696 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003697 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003698
Anders Carlsson16a89042009-10-16 05:23:41 +00003699 if (isa<ObjCSelectorExpr>(castExpr))
3700 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3701
Anders Carlssonc3516322009-10-16 02:48:28 +00003702 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003703 QualType castExprType = castExpr->getType();
3704 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3705 return Diag(castExpr->getLocStart(),
3706 diag::err_cast_pointer_from_non_pointer_int)
3707 << castExprType << castExpr->getSourceRange();
3708 } else if (!castExpr->getType()->isArithmeticType()) {
3709 if (!castType->isIntegralType() && castType->isArithmeticType())
3710 return Diag(castExpr->getLocStart(),
3711 diag::err_cast_pointer_to_non_pointer_int)
3712 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003713 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003714
3715 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003716 return false;
3717}
3718
Anders Carlssonc3516322009-10-16 02:48:28 +00003719bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3720 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003721 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003722
Anders Carlssona64db8f2007-11-27 05:51:55 +00003723 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003724 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003725 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003726 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003727 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003728 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003729 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003730 } else
3731 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003732 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003733 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003734
Anders Carlssonc3516322009-10-16 02:48:28 +00003735 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003736 return false;
3737}
3738
Anders Carlsson16a89042009-10-16 05:23:41 +00003739bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3740 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003741 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003742
3743 QualType SrcTy = CastExpr->getType();
3744
Nate Begeman9b10da62009-06-27 22:05:55 +00003745 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3746 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003747 if (SrcTy->isVectorType()) {
3748 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3749 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3750 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003751 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003752 return false;
3753 }
3754
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003755 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003756 // conversion will take place first from scalar to elt type, and then
3757 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003758 if (SrcTy->isPointerType())
3759 return Diag(R.getBegin(),
3760 diag::err_invalid_conversion_between_vector_and_scalar)
3761 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003762
3763 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3764 ImpCastExprToType(CastExpr, DestElemTy,
3765 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003766
3767 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003768 return false;
3769}
3770
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003771Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003772Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003773 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003774 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003776 assert((Ty != 0) && (Op.get() != 0) &&
3777 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003778
Nate Begeman2ef13e52009-08-10 23:49:36 +00003779 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003780 //FIXME: Preserve type source info.
3781 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Nate Begeman2ef13e52009-08-10 23:49:36 +00003783 // If the Expr being casted is a ParenListExpr, handle it specially.
3784 if (isa<ParenListExpr>(castExpr))
3785 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003786 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003787 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003788 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003789 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003790
3791 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003792 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003793 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003794
Anders Carlsson0aebc812009-09-09 21:33:21 +00003795 if (CastArg.isInvalid())
3796 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003797
Anders Carlsson0aebc812009-09-09 21:33:21 +00003798 castExpr = CastArg.takeAs<Expr>();
3799 } else {
3800 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003801 }
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003803 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003804 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003805 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003806}
3807
Nate Begeman2ef13e52009-08-10 23:49:36 +00003808/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3809/// of comma binary operators.
3810Action::OwningExprResult
3811Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3812 Expr *expr = EA.takeAs<Expr>();
3813 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3814 if (!E)
3815 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Nate Begeman2ef13e52009-08-10 23:49:36 +00003817 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Nate Begeman2ef13e52009-08-10 23:49:36 +00003819 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3820 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3821 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Nate Begeman2ef13e52009-08-10 23:49:36 +00003823 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3824}
3825
3826Action::OwningExprResult
3827Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3828 SourceLocation RParenLoc, ExprArg Op,
3829 QualType Ty) {
3830 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003831
3832 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003833 // then handle it as such.
3834 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3835 if (PE->getNumExprs() == 0) {
3836 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3837 return ExprError();
3838 }
3839
3840 llvm::SmallVector<Expr *, 8> initExprs;
3841 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3842 initExprs.push_back(PE->getExpr(i));
3843
3844 // FIXME: This means that pretty-printing the final AST will produce curly
3845 // braces instead of the original commas.
3846 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003847 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003848 initExprs.size(), RParenLoc);
3849 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003850 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003851 Owned(E));
3852 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003853 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003854 // sequence of BinOp comma operators.
3855 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3856 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3857 }
3858}
3859
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003860Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003861 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003862 MultiExprArg Val,
3863 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003864 unsigned nexprs = Val.size();
3865 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003866 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3867 Expr *expr;
3868 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3869 expr = new (Context) ParenExpr(L, R, exprs[0]);
3870 else
3871 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003872 return Owned(expr);
3873}
3874
Sebastian Redl28507842009-02-26 14:39:58 +00003875/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3876/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003877/// C99 6.5.15
3878QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3879 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003880 // C++ is sufficiently different to merit its own checker.
3881 if (getLangOptions().CPlusPlus)
3882 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3883
John McCallb13c87f2009-11-05 09:23:39 +00003884 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3885
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003886 UsualUnaryConversions(Cond);
3887 UsualUnaryConversions(LHS);
3888 UsualUnaryConversions(RHS);
3889 QualType CondTy = Cond->getType();
3890 QualType LHSTy = LHS->getType();
3891 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003892
Reid Spencer5f016e22007-07-11 17:01:13 +00003893 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003894 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3895 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3896 << CondTy;
3897 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003898 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003899
Chris Lattner70d67a92008-01-06 22:42:25 +00003900 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003901 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3902 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003903
Chris Lattner70d67a92008-01-06 22:42:25 +00003904 // If both operands have arithmetic type, do the usual arithmetic conversions
3905 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003906 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3907 UsualArithmeticConversions(LHS, RHS);
3908 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003909 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003910
Chris Lattner70d67a92008-01-06 22:42:25 +00003911 // If both operands are the same structure or union type, the result is that
3912 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003913 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3914 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003915 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003916 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003917 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003918 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003919 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003920 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003921
Chris Lattner70d67a92008-01-06 22:42:25 +00003922 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003923 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003924 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3925 if (!LHSTy->isVoidType())
3926 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3927 << RHS->getSourceRange();
3928 if (!RHSTy->isVoidType())
3929 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3930 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003931 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3932 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003933 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003934 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003935 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3936 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003937 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003938 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003939 // promote the null to a pointer.
3940 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003941 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003942 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003943 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003944 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003945 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003946 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003947 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003948
3949 // All objective-c pointer type analysis is done here.
3950 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3951 QuestionLoc);
3952 if (!compositeType.isNull())
3953 return compositeType;
3954
3955
Steve Naroff7154a772009-07-01 14:36:47 +00003956 // Handle block pointer types.
3957 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3958 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3959 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3960 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003961 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3962 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003963 return destType;
3964 }
3965 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003966 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00003967 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003968 }
Steve Naroff7154a772009-07-01 14:36:47 +00003969 // We have 2 block pointer types.
3970 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3971 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003972 return LHSTy;
3973 }
Steve Naroff7154a772009-07-01 14:36:47 +00003974 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003975 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3976 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003977
Steve Naroff7154a772009-07-01 14:36:47 +00003978 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3979 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003980 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003981 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003982 // In this situation, we assume void* type. No especially good
3983 // reason, but this is what gcc does, and we do have to pick
3984 // to get a consistent AST.
3985 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003986 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3987 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003988 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003989 }
Steve Naroff7154a772009-07-01 14:36:47 +00003990 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003991 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3992 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003993 return LHSTy;
3994 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00003995
Steve Naroff7154a772009-07-01 14:36:47 +00003996 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3997 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3998 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003999 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4000 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004001
4002 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4003 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4004 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004005 QualType destPointee
4006 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004007 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004008 // Add qualifiers if necessary.
4009 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4010 // Promote to void*.
4011 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004012 return destType;
4013 }
4014 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004015 QualType destPointee
4016 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004017 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004018 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004019 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004020 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004021 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004022 return destType;
4023 }
4024
4025 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4026 // Two identical pointer types are always compatible.
4027 return LHSTy;
4028 }
4029 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4030 rhptee.getUnqualifiedType())) {
4031 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4032 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4033 // In this situation, we assume void* type. No especially good
4034 // reason, but this is what gcc does, and we do have to pick
4035 // to get a consistent AST.
4036 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004037 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4038 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004039 return incompatTy;
4040 }
4041 // The pointer types are compatible.
4042 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4043 // differently qualified versions of compatible types, the result type is
4044 // a pointer to an appropriately qualified version of the *composite*
4045 // type.
4046 // FIXME: Need to calculate the composite type.
4047 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004048 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4049 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004050 return LHSTy;
4051 }
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Steve Naroff7154a772009-07-01 14:36:47 +00004053 // GCC compatibility: soften pointer/integer mismatch.
4054 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4055 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4056 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004057 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004058 return RHSTy;
4059 }
4060 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4061 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4062 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004063 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004064 return LHSTy;
4065 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004066
Chris Lattner70d67a92008-01-06 22:42:25 +00004067 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004068 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4069 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004070 return QualType();
4071}
4072
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004073/// FindCompositeObjCPointerType - Helper method to find composite type of
4074/// two objective-c pointer types of the two input expressions.
4075QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4076 SourceLocation QuestionLoc) {
4077 QualType LHSTy = LHS->getType();
4078 QualType RHSTy = RHS->getType();
4079
4080 // Handle things like Class and struct objc_class*. Here we case the result
4081 // to the pseudo-builtin, because that will be implicitly cast back to the
4082 // redefinition type if an attempt is made to access its fields.
4083 if (LHSTy->isObjCClassType() &&
4084 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4085 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4086 return LHSTy;
4087 }
4088 if (RHSTy->isObjCClassType() &&
4089 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4090 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4091 return RHSTy;
4092 }
4093 // And the same for struct objc_object* / id
4094 if (LHSTy->isObjCIdType() &&
4095 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4096 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4097 return LHSTy;
4098 }
4099 if (RHSTy->isObjCIdType() &&
4100 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4101 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4102 return RHSTy;
4103 }
4104 // And the same for struct objc_selector* / SEL
4105 if (Context.isObjCSelType(LHSTy) &&
4106 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4107 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4108 return LHSTy;
4109 }
4110 if (Context.isObjCSelType(RHSTy) &&
4111 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4112 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4113 return RHSTy;
4114 }
4115 // Check constraints for Objective-C object pointers types.
4116 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4117
4118 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4119 // Two identical object pointer types are always compatible.
4120 return LHSTy;
4121 }
4122 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4123 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4124 QualType compositeType = LHSTy;
4125
4126 // If both operands are interfaces and either operand can be
4127 // assigned to the other, use that type as the composite
4128 // type. This allows
4129 // xxx ? (A*) a : (B*) b
4130 // where B is a subclass of A.
4131 //
4132 // Additionally, as for assignment, if either type is 'id'
4133 // allow silent coercion. Finally, if the types are
4134 // incompatible then make sure to use 'id' as the composite
4135 // type so the result is acceptable for sending messages to.
4136
4137 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4138 // It could return the composite type.
4139 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4140 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4141 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4142 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4143 } else if ((LHSTy->isObjCQualifiedIdType() ||
4144 RHSTy->isObjCQualifiedIdType()) &&
4145 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4146 // Need to handle "id<xx>" explicitly.
4147 // GCC allows qualified id and any Objective-C type to devolve to
4148 // id. Currently localizing to here until clear this should be
4149 // part of ObjCQualifiedIdTypesAreCompatible.
4150 compositeType = Context.getObjCIdType();
4151 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4152 compositeType = Context.getObjCIdType();
4153 } else if (!(compositeType =
4154 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4155 ;
4156 else {
4157 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4158 << LHSTy << RHSTy
4159 << LHS->getSourceRange() << RHS->getSourceRange();
4160 QualType incompatTy = Context.getObjCIdType();
4161 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4162 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4163 return incompatTy;
4164 }
4165 // The object pointer types are compatible.
4166 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4167 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4168 return compositeType;
4169 }
4170 // Check Objective-C object pointer types and 'void *'
4171 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4172 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4173 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4174 QualType destPointee
4175 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4176 QualType destType = Context.getPointerType(destPointee);
4177 // Add qualifiers if necessary.
4178 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4179 // Promote to void*.
4180 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4181 return destType;
4182 }
4183 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4184 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4185 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4186 QualType destPointee
4187 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4188 QualType destType = Context.getPointerType(destPointee);
4189 // Add qualifiers if necessary.
4190 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4191 // Promote to void*.
4192 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4193 return destType;
4194 }
4195 return QualType();
4196}
4197
Steve Narofff69936d2007-09-16 03:34:24 +00004198/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004199/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004200Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4201 SourceLocation ColonLoc,
4202 ExprArg Cond, ExprArg LHS,
4203 ExprArg RHS) {
4204 Expr *CondExpr = (Expr *) Cond.get();
4205 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004206
4207 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4208 // was the condition.
4209 bool isLHSNull = LHSExpr == 0;
4210 if (isLHSNull)
4211 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004212
4213 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004214 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004215 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004216 return ExprError();
4217
4218 Cond.release();
4219 LHS.release();
4220 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004221 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004222 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004223 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004224}
4225
Reid Spencer5f016e22007-07-11 17:01:13 +00004226// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004227// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004228// routine is it effectively iqnores the qualifiers on the top level pointee.
4229// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4230// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004231Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004232Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4233 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004234
David Chisnall0f436562009-08-17 16:35:33 +00004235 if ((lhsType->isObjCClassType() &&
4236 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4237 (rhsType->isObjCClassType() &&
4238 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4239 return Compatible;
4240 }
4241
Reid Spencer5f016e22007-07-11 17:01:13 +00004242 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004243 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4244 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004245
Reid Spencer5f016e22007-07-11 17:01:13 +00004246 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004247 lhptee = Context.getCanonicalType(lhptee);
4248 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004249
Chris Lattner5cf216b2008-01-04 18:04:52 +00004250 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004251
4252 // C99 6.5.16.1p1: This following citation is common to constraints
4253 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4254 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004255 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004256 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004257 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004258
Mike Stumpeed9cac2009-02-19 03:04:26 +00004259 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4260 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004261 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004262 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004263 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004264 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004265
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004266 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004267 assert(rhptee->isFunctionType());
4268 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004269 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004270
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004271 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004272 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004273 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004274
4275 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004276 assert(lhptee->isFunctionType());
4277 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004278 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004279 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004280 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004281 lhptee = lhptee.getUnqualifiedType();
4282 rhptee = rhptee.getUnqualifiedType();
4283 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4284 // Check if the pointee types are compatible ignoring the sign.
4285 // We explicitly check for char so that we catch "char" vs
4286 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004287 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004288 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004289 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004290 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004291
4292 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004293 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004294 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004295 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004296
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004297 if (lhptee == rhptee) {
4298 // Types are compatible ignoring the sign. Qualifier incompatibility
4299 // takes priority over sign incompatibility because the sign
4300 // warning can be disabled.
4301 if (ConvTy != Compatible)
4302 return ConvTy;
4303 return IncompatiblePointerSign;
4304 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004305
4306 // If we are a multi-level pointer, it's possible that our issue is simply
4307 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4308 // the eventual target type is the same and the pointers have the same
4309 // level of indirection, this must be the issue.
4310 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4311 do {
4312 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4313 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4314
4315 lhptee = Context.getCanonicalType(lhptee);
4316 rhptee = Context.getCanonicalType(rhptee);
4317 } while (lhptee->isPointerType() && rhptee->isPointerType());
4318
Douglas Gregora4923eb2009-11-16 21:35:15 +00004319 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004320 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004321 }
4322
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004323 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004324 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004325 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004326 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004327}
4328
Steve Naroff1c7d0672008-09-04 15:10:53 +00004329/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4330/// block pointer types are compatible or whether a block and normal pointer
4331/// are compatible. It is more restrict than comparing two function pointer
4332// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004333Sema::AssignConvertType
4334Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004335 QualType rhsType) {
4336 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004337
Steve Naroff1c7d0672008-09-04 15:10:53 +00004338 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004339 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4340 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004341
Steve Naroff1c7d0672008-09-04 15:10:53 +00004342 // make sure we operate on the canonical type
4343 lhptee = Context.getCanonicalType(lhptee);
4344 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004345
Steve Naroff1c7d0672008-09-04 15:10:53 +00004346 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004347
Steve Naroff1c7d0672008-09-04 15:10:53 +00004348 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004349 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004350 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004351
Eli Friedman26784c12009-06-08 05:08:54 +00004352 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004353 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004354 return ConvTy;
4355}
4356
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004357/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4358/// for assignment compatibility.
4359Sema::AssignConvertType
4360Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4361 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4362 return Compatible;
4363 QualType lhptee =
4364 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4365 QualType rhptee =
4366 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4367 // make sure we operate on the canonical type
4368 lhptee = Context.getCanonicalType(lhptee);
4369 rhptee = Context.getCanonicalType(rhptee);
4370 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4371 return CompatiblePointerDiscardsQualifiers;
4372
4373 if (Context.typesAreCompatible(lhsType, rhsType))
4374 return Compatible;
4375 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4376 return IncompatibleObjCQualifiedId;
4377 return IncompatiblePointer;
4378}
4379
Mike Stumpeed9cac2009-02-19 03:04:26 +00004380/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4381/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004382/// pointers. Here are some objectionable examples that GCC considers warnings:
4383///
4384/// int a, *pint;
4385/// short *pshort;
4386/// struct foo *pfoo;
4387///
4388/// pint = pshort; // warning: assignment from incompatible pointer type
4389/// a = pint; // warning: assignment makes integer from pointer without a cast
4390/// pint = a; // warning: assignment makes pointer from integer without a cast
4391/// pint = pfoo; // warning: assignment from incompatible pointer type
4392///
4393/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004394/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004395///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004396Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004397Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004398 // Get canonical types. We're not formatting these types, just comparing
4399 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004400 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4401 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004402
4403 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004404 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004405
David Chisnall0f436562009-08-17 16:35:33 +00004406 if ((lhsType->isObjCClassType() &&
4407 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4408 (rhsType->isObjCClassType() &&
4409 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4410 return Compatible;
4411 }
4412
Douglas Gregor9d293df2008-10-28 00:22:11 +00004413 // If the left-hand side is a reference type, then we are in a
4414 // (rare!) case where we've allowed the use of references in C,
4415 // e.g., as a parameter type in a built-in function. In this case,
4416 // just make sure that the type referenced is compatible with the
4417 // right-hand side type. The caller is responsible for adjusting
4418 // lhsType so that the resulting expression does not have reference
4419 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004420 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004421 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004422 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004423 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004424 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004425 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4426 // to the same ExtVector type.
4427 if (lhsType->isExtVectorType()) {
4428 if (rhsType->isExtVectorType())
4429 return lhsType == rhsType ? Compatible : Incompatible;
4430 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4431 return Compatible;
4432 }
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Nate Begemanbe2341d2008-07-14 18:02:46 +00004434 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004435 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004436 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004437 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004438 if (getLangOptions().LaxVectorConversions &&
4439 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004440 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004441 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004442 }
4443 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004444 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004445
Chris Lattnere8b3e962008-01-04 23:32:24 +00004446 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004447 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004448
Chris Lattner78eca282008-04-07 06:49:41 +00004449 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004450 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004451 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004452
Chris Lattner78eca282008-04-07 06:49:41 +00004453 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004454 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004455
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004456 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004457 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004458 if (lhsType->isVoidPointerType()) // an exception to the rule.
4459 return Compatible;
4460 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004461 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004462 if (rhsType->getAs<BlockPointerType>()) {
4463 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004464 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004465
4466 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004467 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004468 return Compatible;
4469 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004470 return Incompatible;
4471 }
4472
4473 if (isa<BlockPointerType>(lhsType)) {
4474 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004475 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004476
Steve Naroffb4406862008-09-29 18:10:17 +00004477 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004478 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004479 return Compatible;
4480
Steve Naroff1c7d0672008-09-04 15:10:53 +00004481 if (rhsType->isBlockPointerType())
4482 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004483
Ted Kremenek6217b802009-07-29 21:53:49 +00004484 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004485 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004486 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004487 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004488 return Incompatible;
4489 }
4490
Steve Naroff14108da2009-07-10 23:34:53 +00004491 if (isa<ObjCObjectPointerType>(lhsType)) {
4492 if (rhsType->isIntegerType())
4493 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004494
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004495 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004496 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004497 if (rhsType->isVoidPointerType()) // an exception to the rule.
4498 return Compatible;
4499 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004500 }
4501 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004502 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004503 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004504 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004505 if (RHSPT->getPointeeType()->isVoidType())
4506 return Compatible;
4507 }
4508 // Treat block pointers as objects.
4509 if (rhsType->isBlockPointerType())
4510 return Compatible;
4511 return Incompatible;
4512 }
Chris Lattner78eca282008-04-07 06:49:41 +00004513 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004514 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004515 if (lhsType == Context.BoolTy)
4516 return Compatible;
4517
4518 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004519 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004520
Mike Stumpeed9cac2009-02-19 03:04:26 +00004521 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004522 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004523
4524 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004525 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004526 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004527 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004528 }
Steve Naroff14108da2009-07-10 23:34:53 +00004529 if (isa<ObjCObjectPointerType>(rhsType)) {
4530 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4531 if (lhsType == Context.BoolTy)
4532 return Compatible;
4533
4534 if (lhsType->isIntegerType())
4535 return PointerToInt;
4536
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004537 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004538 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004539 if (lhsType->isVoidPointerType()) // an exception to the rule.
4540 return Compatible;
4541 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004542 }
4543 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004544 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004545 return Compatible;
4546 return Incompatible;
4547 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004548
Chris Lattnerfc144e22008-01-04 23:18:45 +00004549 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004550 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004551 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004552 }
4553 return Incompatible;
4554}
4555
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004556/// \brief Constructs a transparent union from an expression that is
4557/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004558static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004559 QualType UnionType, FieldDecl *Field) {
4560 // Build an initializer list that designates the appropriate member
4561 // of the transparent union.
4562 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4563 &E, 1,
4564 SourceLocation());
4565 Initializer->setType(UnionType);
4566 Initializer->setInitializedFieldInUnion(Field);
4567
4568 // Build a compound literal constructing a value of the transparent
4569 // union type from this initializer list.
4570 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4571 false);
4572}
4573
4574Sema::AssignConvertType
4575Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4576 QualType FromType = rExpr->getType();
4577
Mike Stump1eb44332009-09-09 15:08:12 +00004578 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004579 // transparent_union GCC extension.
4580 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004581 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004582 return Incompatible;
4583
4584 // The field to initialize within the transparent union.
4585 RecordDecl *UD = UT->getDecl();
4586 FieldDecl *InitField = 0;
4587 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004588 for (RecordDecl::field_iterator it = UD->field_begin(),
4589 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004590 it != itend; ++it) {
4591 if (it->getType()->isPointerType()) {
4592 // If the transparent union contains a pointer type, we allow:
4593 // 1) void pointer
4594 // 2) null pointer constant
4595 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004596 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004597 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004598 InitField = *it;
4599 break;
4600 }
Mike Stump1eb44332009-09-09 15:08:12 +00004601
Douglas Gregorce940492009-09-25 04:25:58 +00004602 if (rExpr->isNullPointerConstant(Context,
4603 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004604 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004605 InitField = *it;
4606 break;
4607 }
4608 }
4609
4610 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4611 == Compatible) {
4612 InitField = *it;
4613 break;
4614 }
4615 }
4616
4617 if (!InitField)
4618 return Incompatible;
4619
4620 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4621 return Compatible;
4622}
4623
Chris Lattner5cf216b2008-01-04 18:04:52 +00004624Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004625Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004626 if (getLangOptions().CPlusPlus) {
4627 if (!lhsType->isRecordType()) {
4628 // C++ 5.17p3: If the left operand is not of class type, the
4629 // expression is implicitly converted (C++ 4) to the
4630 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004631 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4632 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004633 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004634 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004635 }
4636
4637 // FIXME: Currently, we fall through and treat C++ classes like C
4638 // structures.
4639 }
4640
Steve Naroff529a4ad2007-11-27 17:58:44 +00004641 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4642 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004643 if ((lhsType->isPointerType() ||
4644 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004645 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004646 && rExpr->isNullPointerConstant(Context,
4647 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004648 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004649 return Compatible;
4650 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004651
Chris Lattner943140e2007-10-16 02:55:40 +00004652 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004653 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004654 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004655 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004656 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004657 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004658 if (!lhsType->isReferenceType())
4659 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004660
Chris Lattner5cf216b2008-01-04 18:04:52 +00004661 Sema::AssignConvertType result =
4662 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004663
Steve Narofff1120de2007-08-24 22:33:52 +00004664 // C99 6.5.16.1p2: The value of the right operand is converted to the
4665 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004666 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4667 // so that we can use references in built-in functions even in C.
4668 // The getNonReferenceType() call makes sure that the resulting expression
4669 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004670 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004671 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4672 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004673 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004674}
4675
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004676QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004677 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004678 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004679 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004680 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004681}
4682
Mike Stumpeed9cac2009-02-19 03:04:26 +00004683inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004684 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004685 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004686 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004687 QualType lhsType =
4688 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4689 QualType rhsType =
4690 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004691
Nate Begemanbe2341d2008-07-14 18:02:46 +00004692 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004693 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004694 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004695
Nate Begemanbe2341d2008-07-14 18:02:46 +00004696 // Handle the case of a vector & extvector type of the same size and element
4697 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004698 if (getLangOptions().LaxVectorConversions) {
4699 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004700 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4701 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004702 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004703 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004704 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004705 }
4706 }
4707 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004708
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004709 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4710 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4711 bool swapped = false;
4712 if (rhsType->isExtVectorType()) {
4713 swapped = true;
4714 std::swap(rex, lex);
4715 std::swap(rhsType, lhsType);
4716 }
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Nate Begemandde25982009-06-28 19:12:57 +00004718 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004719 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004720 QualType EltTy = LV->getElementType();
4721 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4722 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004723 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004724 if (swapped) std::swap(rex, lex);
4725 return lhsType;
4726 }
4727 }
4728 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4729 rhsType->isRealFloatingType()) {
4730 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004731 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004732 if (swapped) std::swap(rex, lex);
4733 return lhsType;
4734 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004735 }
4736 }
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Nate Begemandde25982009-06-28 19:12:57 +00004738 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004739 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004740 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004741 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004742 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004743}
4744
Reid Spencer5f016e22007-07-11 17:01:13 +00004745inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004746 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004747 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004748 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004749
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004750 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004751
Steve Naroffa4332e22007-07-17 00:58:39 +00004752 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004753 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004754 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004755}
4756
4757inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004758 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004759 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4760 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4761 return CheckVectorOperands(Loc, lex, rex);
4762 return InvalidOperands(Loc, lex, rex);
4763 }
Steve Naroff90045e82007-07-13 23:32:42 +00004764
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004765 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004766
Steve Naroffa4332e22007-07-17 00:58:39 +00004767 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004768 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004769 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004770}
4771
4772inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004773 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004774 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4775 QualType compType = CheckVectorOperands(Loc, lex, rex);
4776 if (CompLHSTy) *CompLHSTy = compType;
4777 return compType;
4778 }
Steve Naroff49b45262007-07-13 16:58:59 +00004779
Eli Friedmanab3a8522009-03-28 01:22:36 +00004780 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004781
Reid Spencer5f016e22007-07-11 17:01:13 +00004782 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004783 if (lex->getType()->isArithmeticType() &&
4784 rex->getType()->isArithmeticType()) {
4785 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004786 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004787 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004788
Eli Friedmand72d16e2008-05-18 18:08:51 +00004789 // Put any potential pointer into PExp
4790 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004791 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004792 std::swap(PExp, IExp);
4793
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004794 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Eli Friedmand72d16e2008-05-18 18:08:51 +00004796 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004797 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Chris Lattnerb5f15622009-04-24 23:50:08 +00004799 // Check for arithmetic on pointers to incomplete types.
4800 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004801 if (getLangOptions().CPlusPlus) {
4802 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004803 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004804 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004805 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004806
4807 // GNU extension: arithmetic on pointer to void
4808 Diag(Loc, diag::ext_gnu_void_ptr)
4809 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004810 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004811 if (getLangOptions().CPlusPlus) {
4812 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4813 << lex->getType() << lex->getSourceRange();
4814 return QualType();
4815 }
4816
4817 // GNU extension: arithmetic on pointer to function
4818 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4819 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004820 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004821 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004822 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004823 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004824 PExp->getType()->isObjCObjectPointerType()) &&
4825 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004826 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4827 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004828 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004829 return QualType();
4830 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004831 // Diagnose bad cases where we step over interface counts.
4832 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4833 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4834 << PointeeTy << PExp->getSourceRange();
4835 return QualType();
4836 }
Mike Stump1eb44332009-09-09 15:08:12 +00004837
Eli Friedmanab3a8522009-03-28 01:22:36 +00004838 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004839 QualType LHSTy = Context.isPromotableBitField(lex);
4840 if (LHSTy.isNull()) {
4841 LHSTy = lex->getType();
4842 if (LHSTy->isPromotableIntegerType())
4843 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004844 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004845 *CompLHSTy = LHSTy;
4846 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004847 return PExp->getType();
4848 }
4849 }
4850
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004851 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004852}
4853
Chris Lattnereca7be62008-04-07 05:30:13 +00004854// C99 6.5.6
4855QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004856 SourceLocation Loc, QualType* CompLHSTy) {
4857 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4858 QualType compType = CheckVectorOperands(Loc, lex, rex);
4859 if (CompLHSTy) *CompLHSTy = compType;
4860 return compType;
4861 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004862
Eli Friedmanab3a8522009-03-28 01:22:36 +00004863 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004864
Chris Lattner6e4ab612007-12-09 21:53:25 +00004865 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004866
Chris Lattner6e4ab612007-12-09 21:53:25 +00004867 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004868 if (lex->getType()->isArithmeticType()
4869 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004870 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004871 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004872 }
Mike Stump1eb44332009-09-09 15:08:12 +00004873
Chris Lattner6e4ab612007-12-09 21:53:25 +00004874 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004875 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004876 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004877
Douglas Gregore7450f52009-03-24 19:52:54 +00004878 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004879
Douglas Gregore7450f52009-03-24 19:52:54 +00004880 bool ComplainAboutVoid = false;
4881 Expr *ComplainAboutFunc = 0;
4882 if (lpointee->isVoidType()) {
4883 if (getLangOptions().CPlusPlus) {
4884 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4885 << lex->getSourceRange() << rex->getSourceRange();
4886 return QualType();
4887 }
4888
4889 // GNU C extension: arithmetic on pointer to void
4890 ComplainAboutVoid = true;
4891 } else if (lpointee->isFunctionType()) {
4892 if (getLangOptions().CPlusPlus) {
4893 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004894 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004895 return QualType();
4896 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004897
4898 // GNU C extension: arithmetic on pointer to function
4899 ComplainAboutFunc = lex;
4900 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004901 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004902 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004903 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004904 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004905 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004906
Chris Lattnerb5f15622009-04-24 23:50:08 +00004907 // Diagnose bad cases where we step over interface counts.
4908 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4909 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4910 << lpointee << lex->getSourceRange();
4911 return QualType();
4912 }
Mike Stump1eb44332009-09-09 15:08:12 +00004913
Chris Lattner6e4ab612007-12-09 21:53:25 +00004914 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004915 if (rex->getType()->isIntegerType()) {
4916 if (ComplainAboutVoid)
4917 Diag(Loc, diag::ext_gnu_void_ptr)
4918 << lex->getSourceRange() << rex->getSourceRange();
4919 if (ComplainAboutFunc)
4920 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004921 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004922 << ComplainAboutFunc->getSourceRange();
4923
Eli Friedmanab3a8522009-03-28 01:22:36 +00004924 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004925 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004926 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004927
Chris Lattner6e4ab612007-12-09 21:53:25 +00004928 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004929 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004930 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004931
Douglas Gregore7450f52009-03-24 19:52:54 +00004932 // RHS must be a completely-type object type.
4933 // Handle the GNU void* extension.
4934 if (rpointee->isVoidType()) {
4935 if (getLangOptions().CPlusPlus) {
4936 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4937 << lex->getSourceRange() << rex->getSourceRange();
4938 return QualType();
4939 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004940
Douglas Gregore7450f52009-03-24 19:52:54 +00004941 ComplainAboutVoid = true;
4942 } else if (rpointee->isFunctionType()) {
4943 if (getLangOptions().CPlusPlus) {
4944 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004945 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004946 return QualType();
4947 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004948
4949 // GNU extension: arithmetic on pointer to function
4950 if (!ComplainAboutFunc)
4951 ComplainAboutFunc = rex;
4952 } else if (!rpointee->isDependentType() &&
4953 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004954 PDiag(diag::err_typecheck_sub_ptr_object)
4955 << rex->getSourceRange()
4956 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004957 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004958
Eli Friedman88d936b2009-05-16 13:54:38 +00004959 if (getLangOptions().CPlusPlus) {
4960 // Pointee types must be the same: C++ [expr.add]
4961 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4962 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4963 << lex->getType() << rex->getType()
4964 << lex->getSourceRange() << rex->getSourceRange();
4965 return QualType();
4966 }
4967 } else {
4968 // Pointee types must be compatible C99 6.5.6p3
4969 if (!Context.typesAreCompatible(
4970 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4971 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4972 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4973 << lex->getType() << rex->getType()
4974 << lex->getSourceRange() << rex->getSourceRange();
4975 return QualType();
4976 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004977 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004978
Douglas Gregore7450f52009-03-24 19:52:54 +00004979 if (ComplainAboutVoid)
4980 Diag(Loc, diag::ext_gnu_void_ptr)
4981 << lex->getSourceRange() << rex->getSourceRange();
4982 if (ComplainAboutFunc)
4983 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004984 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004985 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004986
4987 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004988 return Context.getPointerDiffType();
4989 }
4990 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004991
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004992 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004993}
4994
Chris Lattnereca7be62008-04-07 05:30:13 +00004995// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004996QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004997 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004998 // C99 6.5.7p2: Each of the operands shall have integer type.
4999 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005000 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005001
Nate Begeman2207d792009-10-25 02:26:48 +00005002 // Vector shifts promote their scalar inputs to vector type.
5003 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5004 return CheckVectorOperands(Loc, lex, rex);
5005
Chris Lattnerca5eede2007-12-12 05:47:28 +00005006 // Shifts don't perform usual arithmetic conversions, they just do integer
5007 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005008 QualType LHSTy = Context.isPromotableBitField(lex);
5009 if (LHSTy.isNull()) {
5010 LHSTy = lex->getType();
5011 if (LHSTy->isPromotableIntegerType())
5012 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005013 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005014 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005015 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005016
Chris Lattnerca5eede2007-12-12 05:47:28 +00005017 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005018
Ryan Flynnd0439682009-08-07 16:20:20 +00005019 // Sanity-check shift operands
5020 llvm::APSInt Right;
5021 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005022 if (!rex->isValueDependent() &&
5023 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005024 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005025 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5026 else {
5027 llvm::APInt LeftBits(Right.getBitWidth(),
5028 Context.getTypeSize(lex->getType()));
5029 if (Right.uge(LeftBits))
5030 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5031 }
5032 }
5033
Chris Lattnerca5eede2007-12-12 05:47:28 +00005034 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005035 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005036}
5037
John McCall5dbad3d2009-11-06 08:49:08 +00005038/// \brief Implements -Wsign-compare.
5039///
5040/// \param lex the left-hand expression
5041/// \param rex the right-hand expression
5042/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00005043/// \param Equality whether this is an "equality-like" join, which
5044/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00005045void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00005046 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00005047 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00005048 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00005049 return;
5050
John McCall45aa4552009-11-05 00:40:04 +00005051 QualType lt = lex->getType(), rt = rex->getType();
5052
5053 // Only warn if both operands are integral.
5054 if (!lt->isIntegerType() || !rt->isIntegerType())
5055 return;
5056
Sebastian Redl732429c2009-11-05 21:09:23 +00005057 // If either expression is value-dependent, don't warn. We'll get another
5058 // chance at instantiation time.
5059 if (lex->isValueDependent() || rex->isValueDependent())
5060 return;
5061
John McCall45aa4552009-11-05 00:40:04 +00005062 // The rule is that the signed operand becomes unsigned, so isolate the
5063 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00005064 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00005065 if (lt->isSignedIntegerType()) {
5066 if (rt->isSignedIntegerType()) return;
5067 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00005068 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00005069 } else {
5070 if (!rt->isSignedIntegerType()) return;
5071 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00005072 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00005073 }
5074
John McCall5dbad3d2009-11-06 08:49:08 +00005075 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00005076 // then (1) the result type will be signed and (2) the unsigned
5077 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00005078 // of the comparison will be exact.
5079 if (Context.getIntWidth(signedOperand->getType()) >
5080 Context.getIntWidth(unsignedOperand->getType()))
5081 return;
5082
John McCall45aa4552009-11-05 00:40:04 +00005083 // If the value is a non-negative integer constant, then the
5084 // signed->unsigned conversion won't change it.
5085 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00005086 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00005087 assert(value.isSigned() && "result of signed expression not signed");
5088
5089 if (value.isNonNegative())
5090 return;
5091 }
5092
John McCall5dbad3d2009-11-06 08:49:08 +00005093 if (Equality) {
5094 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00005095 // constant which cannot collide with a overflowed signed operand,
5096 // then reinterpreting the signed operand as unsigned will not
5097 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00005098 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5099 assert(!value.isSigned() && "result of unsigned expression is signed");
5100
5101 // 2's complement: test the top bit.
5102 if (value.isNonNegative())
5103 return;
5104 }
5105 }
5106
John McCallb13c87f2009-11-05 09:23:39 +00005107 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00005108 << lex->getType() << rex->getType()
5109 << lex->getSourceRange() << rex->getSourceRange();
5110}
5111
Douglas Gregor0c6db942009-05-04 06:07:12 +00005112// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005113QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005114 unsigned OpaqueOpc, bool isRelational) {
5115 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5116
Chris Lattner02dd4b12009-12-05 05:40:13 +00005117 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005118 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005119 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005120
John McCall5dbad3d2009-11-06 08:49:08 +00005121 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5122 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005123
Chris Lattnera5937dd2007-08-26 01:18:55 +00005124 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005125 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5126 UsualArithmeticConversions(lex, rex);
5127 else {
5128 UsualUnaryConversions(lex);
5129 UsualUnaryConversions(rex);
5130 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005131 QualType lType = lex->getType();
5132 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005133
Mike Stumpaf199f32009-05-07 18:43:07 +00005134 if (!lType->isFloatingType()
5135 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005136 // For non-floating point types, check for self-comparisons of the form
5137 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5138 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005139 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005140 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005141 Expr *LHSStripped = lex->IgnoreParens();
5142 Expr *RHSStripped = rex->IgnoreParens();
5143 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5144 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005145 if (DRL->getDecl() == DRR->getDecl() &&
5146 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005147 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005148
Chris Lattner55660a72009-03-08 19:39:53 +00005149 if (isa<CastExpr>(LHSStripped))
5150 LHSStripped = LHSStripped->IgnoreParenCasts();
5151 if (isa<CastExpr>(RHSStripped))
5152 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005153
Chris Lattner55660a72009-03-08 19:39:53 +00005154 // Warn about comparisons against a string constant (unless the other
5155 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005156 Expr *literalString = 0;
5157 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005158 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005159 !RHSStripped->isNullPointerConstant(Context,
5160 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005161 literalString = lex;
5162 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005163 } else if ((isa<StringLiteral>(RHSStripped) ||
5164 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005165 !LHSStripped->isNullPointerConstant(Context,
5166 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005167 literalString = rex;
5168 literalStringStripped = RHSStripped;
5169 }
5170
5171 if (literalString) {
5172 std::string resultComparison;
5173 switch (Opc) {
5174 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5175 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5176 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5177 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5178 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5179 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5180 default: assert(false && "Invalid comparison operator");
5181 }
5182 Diag(Loc, diag::warn_stringcompare)
5183 << isa<ObjCEncodeExpr>(literalStringStripped)
5184 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005185 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5186 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5187 "strcmp(")
5188 << CodeModificationHint::CreateInsertion(
5189 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005190 resultComparison);
5191 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005192 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005193
Douglas Gregor447b69e2008-11-19 03:25:36 +00005194 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005195 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005196
Chris Lattnera5937dd2007-08-26 01:18:55 +00005197 if (isRelational) {
5198 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005199 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005200 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005201 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005202 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005203 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005204
Chris Lattnera5937dd2007-08-26 01:18:55 +00005205 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005206 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005207 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005208
Douglas Gregorce940492009-09-25 04:25:58 +00005209 bool LHSIsNull = lex->isNullPointerConstant(Context,
5210 Expr::NPC_ValueDependentIsNull);
5211 bool RHSIsNull = rex->isNullPointerConstant(Context,
5212 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005213
Chris Lattnera5937dd2007-08-26 01:18:55 +00005214 // All of the following pointer related warnings are GCC extensions, except
5215 // when handling null pointer constants. One day, we can consider making them
5216 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005217 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005218 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005219 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005220 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005221 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005222
Douglas Gregor0c6db942009-05-04 06:07:12 +00005223 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005224 if (LCanPointeeTy == RCanPointeeTy)
5225 return ResultTy;
5226
Douglas Gregor0c6db942009-05-04 06:07:12 +00005227 // C++ [expr.rel]p2:
5228 // [...] Pointer conversions (4.10) and qualification
5229 // conversions (4.4) are performed on pointer operands (or on
5230 // a pointer operand and a null pointer constant) to bring
5231 // them to their composite pointer type. [...]
5232 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005233 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005234 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005235 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005236 if (T.isNull()) {
5237 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5238 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5239 return QualType();
5240 }
5241
Eli Friedman73c39ab2009-10-20 08:27:19 +00005242 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5243 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005244 return ResultTy;
5245 }
Eli Friedman3075e762009-08-23 00:27:47 +00005246 // C99 6.5.9p2 and C99 6.5.8p2
5247 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5248 RCanPointeeTy.getUnqualifiedType())) {
5249 // Valid unless a relational comparison of function pointers
5250 if (isRelational && LCanPointeeTy->isFunctionType()) {
5251 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5252 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5253 }
5254 } else if (!isRelational &&
5255 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5256 // Valid unless comparison between non-null pointer and function pointer
5257 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5258 && !LHSIsNull && !RHSIsNull) {
5259 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5260 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5261 }
5262 } else {
5263 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005264 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005265 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005266 }
Eli Friedman3075e762009-08-23 00:27:47 +00005267 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005268 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005269 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005270 }
Mike Stump1eb44332009-09-09 15:08:12 +00005271
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005272 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005273 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005274 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005275 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005276 (lType->isPointerType() ||
5277 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005278 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005279 return ResultTy;
5280 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005281 if (LHSIsNull &&
5282 (rType->isPointerType() ||
5283 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005284 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005285 return ResultTy;
5286 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005287
5288 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005289 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005290 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5291 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005292 // In addition, pointers to members can be compared, or a pointer to
5293 // member and a null pointer constant. Pointer to member conversions
5294 // (4.11) and qualification conversions (4.4) are performed to bring
5295 // them to a common type. If one operand is a null pointer constant,
5296 // the common type is the type of the other operand. Otherwise, the
5297 // common type is a pointer to member type similar (4.4) to the type
5298 // of one of the operands, with a cv-qualification signature (4.4)
5299 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005300 // types.
5301 QualType T = FindCompositePointerType(lex, rex);
5302 if (T.isNull()) {
5303 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5304 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5305 return QualType();
5306 }
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Eli Friedman73c39ab2009-10-20 08:27:19 +00005308 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5309 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005310 return ResultTy;
5311 }
Mike Stump1eb44332009-09-09 15:08:12 +00005312
Douglas Gregor20b3e992009-08-24 17:42:35 +00005313 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005314 if (lType->isNullPtrType() && rType->isNullPtrType())
5315 return ResultTy;
5316 }
Mike Stump1eb44332009-09-09 15:08:12 +00005317
Steve Naroff1c7d0672008-09-04 15:10:53 +00005318 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005319 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005320 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5321 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005322
Steve Naroff1c7d0672008-09-04 15:10:53 +00005323 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005324 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005325 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005326 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005327 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005328 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005329 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005330 }
Steve Naroff59f53942008-09-28 01:11:11 +00005331 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005332 if (!isRelational
5333 && ((lType->isBlockPointerType() && rType->isPointerType())
5334 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005335 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005336 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005337 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005338 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005339 ->getPointeeType()->isVoidType())))
5340 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5341 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005342 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005343 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005344 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005345 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005346
Steve Naroff14108da2009-07-10 23:34:53 +00005347 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005348 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005349 const PointerType *LPT = lType->getAs<PointerType>();
5350 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005351 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005352 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005353 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005354 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005355
Steve Naroffa8069f12008-11-17 19:49:16 +00005356 if (!LPtrToVoid && !RPtrToVoid &&
5357 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005358 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005359 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005360 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005361 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005362 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005363 }
Steve Naroff14108da2009-07-10 23:34:53 +00005364 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005365 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005366 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5367 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005368 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005369 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005370 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005371 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005372 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005373 unsigned DiagID = 0;
5374 if (RHSIsNull) {
5375 if (isRelational)
5376 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5377 } else if (isRelational)
5378 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5379 else
5380 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005381
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005382 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005383 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005384 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005385 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005386 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005387 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005388 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005389 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005390 unsigned DiagID = 0;
5391 if (LHSIsNull) {
5392 if (isRelational)
5393 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5394 } else if (isRelational)
5395 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5396 else
5397 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005398
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005399 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005400 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005401 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005402 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005403 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005404 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005405 }
Steve Naroff39218df2008-09-04 16:56:14 +00005406 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005407 if (!isRelational && RHSIsNull
5408 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005409 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005410 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005411 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005412 if (!isRelational && LHSIsNull
5413 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005414 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005415 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005416 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005417 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005418}
5419
Nate Begemanbe2341d2008-07-14 18:02:46 +00005420/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005421/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005422/// like a scalar comparison, a vector comparison produces a vector of integer
5423/// types.
5424QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005425 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005426 bool isRelational) {
5427 // Check to make sure we're operating on vectors of the same type and width,
5428 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005429 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005430 if (vType.isNull())
5431 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005432
Nate Begemanbe2341d2008-07-14 18:02:46 +00005433 QualType lType = lex->getType();
5434 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005435
Nate Begemanbe2341d2008-07-14 18:02:46 +00005436 // For non-floating point types, check for self-comparisons of the form
5437 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5438 // often indicate logic errors in the program.
5439 if (!lType->isFloatingType()) {
5440 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5441 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5442 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005443 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005444 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005445
Nate Begemanbe2341d2008-07-14 18:02:46 +00005446 // Check for comparisons of floating point operands using != and ==.
5447 if (!isRelational && lType->isFloatingType()) {
5448 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005449 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005450 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005451
Nate Begemanbe2341d2008-07-14 18:02:46 +00005452 // Return the type for the comparison, which is the same as vector type for
5453 // integer vectors, or an integer type of identical size and number of
5454 // elements for floating point vectors.
5455 if (lType->isIntegerType())
5456 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005457
John McCall183700f2009-09-21 23:43:11 +00005458 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005459 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005460 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005461 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005462 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005463 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5464
Mike Stumpeed9cac2009-02-19 03:04:26 +00005465 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005466 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005467 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5468}
5469
Reid Spencer5f016e22007-07-11 17:01:13 +00005470inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005471 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005472 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005473 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005474
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005475 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005476
Steve Naroffa4332e22007-07-17 00:58:39 +00005477 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005478 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005479 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005480}
5481
5482inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005483 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005484 if (!Context.getLangOptions().CPlusPlus) {
5485 UsualUnaryConversions(lex);
5486 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005487
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005488 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5489 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005490
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005491 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005492 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005493
5494 // C++ [expr.log.and]p1
5495 // C++ [expr.log.or]p1
5496 // The operands are both implicitly converted to type bool (clause 4).
5497 StandardConversionSequence LHS;
5498 if (!IsStandardConversion(lex, Context.BoolTy,
5499 /*InOverloadResolution=*/false, LHS))
5500 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005501
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005502 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5503 "passing", /*IgnoreBaseAccess=*/false))
5504 return InvalidOperands(Loc, lex, rex);
5505
5506 StandardConversionSequence RHS;
5507 if (!IsStandardConversion(rex, Context.BoolTy,
5508 /*InOverloadResolution=*/false, RHS))
5509 return InvalidOperands(Loc, lex, rex);
5510
5511 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5512 "passing", /*IgnoreBaseAccess=*/false))
5513 return InvalidOperands(Loc, lex, rex);
5514
5515 // C++ [expr.log.and]p2
5516 // C++ [expr.log.or]p2
5517 // The result is a bool.
5518 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005519}
5520
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005521/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5522/// is a read-only property; return true if so. A readonly property expression
5523/// depends on various declarations and thus must be treated specially.
5524///
Mike Stump1eb44332009-09-09 15:08:12 +00005525static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005526 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5527 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5528 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5529 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005530 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005531 BaseType->getAsObjCInterfacePointerType())
5532 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5533 if (S.isPropertyReadonly(PDecl, IFace))
5534 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005535 }
5536 }
5537 return false;
5538}
5539
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005540/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5541/// emit an error and return true. If so, return false.
5542static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005543 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005544 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005545 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005546 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5547 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005548 if (IsLV == Expr::MLV_Valid)
5549 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005550
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005551 unsigned Diag = 0;
5552 bool NeedType = false;
5553 switch (IsLV) { // C99 6.5.16p2
5554 default: assert(0 && "Unknown result from isModifiableLvalue!");
5555 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005556 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005557 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5558 NeedType = true;
5559 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005560 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005561 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5562 NeedType = true;
5563 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005564 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005565 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5566 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005567 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005568 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5569 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005570 case Expr::MLV_IncompleteType:
5571 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005572 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005573 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5574 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005575 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005576 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5577 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005578 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005579 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5580 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005581 case Expr::MLV_ReadonlyProperty:
5582 Diag = diag::error_readonly_property_assignment;
5583 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005584 case Expr::MLV_NoSetterProperty:
5585 Diag = diag::error_nosetter_property_assignment;
5586 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005587 case Expr::MLV_SubObjCPropertySetting:
5588 Diag = diag::error_no_subobject_property_setting;
5589 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005590 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005591
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005592 SourceRange Assign;
5593 if (Loc != OrigLoc)
5594 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005595 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005596 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005597 else
Mike Stump1eb44332009-09-09 15:08:12 +00005598 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005599 return true;
5600}
5601
5602
5603
5604// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005605QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5606 SourceLocation Loc,
5607 QualType CompoundType) {
5608 // Verify that LHS is a modifiable lvalue, and emit error if not.
5609 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005610 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005611
5612 QualType LHSType = LHS->getType();
5613 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005614
Chris Lattner5cf216b2008-01-04 18:04:52 +00005615 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005616 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005617 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005618 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005619 // Special case of NSObject attributes on c-style pointer types.
5620 if (ConvTy == IncompatiblePointer &&
5621 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005622 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005623 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005624 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005625 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005626
Chris Lattner2c156472008-08-21 18:04:13 +00005627 // If the RHS is a unary plus or minus, check to see if they = and + are
5628 // right next to each other. If so, the user may have typo'd "x =+ 4"
5629 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005630 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005631 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5632 RHSCheck = ICE->getSubExpr();
5633 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5634 if ((UO->getOpcode() == UnaryOperator::Plus ||
5635 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005636 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005637 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005638 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5639 // And there is a space or other character before the subexpr of the
5640 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005641 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5642 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005643 Diag(Loc, diag::warn_not_compound_assign)
5644 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5645 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005646 }
Chris Lattner2c156472008-08-21 18:04:13 +00005647 }
5648 } else {
5649 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005650 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005651 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005652
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005653 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5654 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005655 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005656
Reid Spencer5f016e22007-07-11 17:01:13 +00005657 // C99 6.5.16p3: The type of an assignment expression is the type of the
5658 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005659 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005660 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5661 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005662 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005663 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005664 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005665}
5666
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005667// C99 6.5.17
5668QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005669 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005670 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005671
5672 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5673 // incomplete in C++).
5674
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005675 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005676}
5677
Steve Naroff49b45262007-07-13 16:58:59 +00005678/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5679/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005680QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5681 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005682 if (Op->isTypeDependent())
5683 return Context.DependentTy;
5684
Chris Lattner3528d352008-11-21 07:05:48 +00005685 QualType ResType = Op->getType();
5686 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005687
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005688 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5689 // Decrement of bool is not allowed.
5690 if (!isInc) {
5691 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5692 return QualType();
5693 }
5694 // Increment of bool sets it to true, but is deprecated.
5695 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5696 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005697 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005698 } else if (ResType->isAnyPointerType()) {
5699 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005700
Chris Lattner3528d352008-11-21 07:05:48 +00005701 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005702 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005703 if (getLangOptions().CPlusPlus) {
5704 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5705 << Op->getSourceRange();
5706 return QualType();
5707 }
5708
5709 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005710 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005711 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005712 if (getLangOptions().CPlusPlus) {
5713 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5714 << Op->getType() << Op->getSourceRange();
5715 return QualType();
5716 }
5717
5718 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005719 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005720 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005721 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005722 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005723 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005724 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005725 // Diagnose bad cases where we step over interface counts.
5726 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5727 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5728 << PointeeTy << Op->getSourceRange();
5729 return QualType();
5730 }
Chris Lattner3528d352008-11-21 07:05:48 +00005731 } else if (ResType->isComplexType()) {
5732 // C99 does not support ++/-- on complex types, we allow as an extension.
5733 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005734 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005735 } else {
5736 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005737 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005738 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005739 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005740 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005741 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005742 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005743 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005744 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005745}
5746
Anders Carlsson369dee42008-02-01 07:15:58 +00005747/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005748/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005749/// where the declaration is needed for type checking. We only need to
5750/// handle cases when the expression references a function designator
5751/// or is an lvalue. Here are some examples:
5752/// - &(x) => x
5753/// - &*****f => f for f a function designator.
5754/// - &s.xx => s
5755/// - &s.zz[1].yy -> s, if zz is an array
5756/// - *(x + 1) -> x, if x is an array
5757/// - &"123"[2] -> 0
5758/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005759static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005760 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005761 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005762 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005763 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005764 // If this is an arrow operator, the address is an offset from
5765 // the base's value, so the object the base refers to is
5766 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005767 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005768 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005769 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005770 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005771 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005772 // FIXME: This code shouldn't be necessary! We should catch the implicit
5773 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005774 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5775 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5776 if (ICE->getSubExpr()->getType()->isArrayType())
5777 return getPrimaryDecl(ICE->getSubExpr());
5778 }
5779 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005780 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005781 case Stmt::UnaryOperatorClass: {
5782 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005783
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005784 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005785 case UnaryOperator::Real:
5786 case UnaryOperator::Imag:
5787 case UnaryOperator::Extension:
5788 return getPrimaryDecl(UO->getSubExpr());
5789 default:
5790 return 0;
5791 }
5792 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005793 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005794 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005795 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005796 // If the result of an implicit cast is an l-value, we care about
5797 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005798 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005799 default:
5800 return 0;
5801 }
5802}
5803
5804/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005805/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005806/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005807/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005808/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005809/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005810/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005811QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005812 // Make sure to ignore parentheses in subsequent checks
5813 op = op->IgnoreParens();
5814
Douglas Gregor9103bb22008-12-17 22:52:20 +00005815 if (op->isTypeDependent())
5816 return Context.DependentTy;
5817
Steve Naroff08f19672008-01-13 17:10:08 +00005818 if (getLangOptions().C99) {
5819 // Implement C99-only parts of addressof rules.
5820 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5821 if (uOp->getOpcode() == UnaryOperator::Deref)
5822 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5823 // (assuming the deref expression is valid).
5824 return uOp->getSubExpr()->getType();
5825 }
5826 // Technically, there should be a check for array subscript
5827 // expressions here, but the result of one is always an lvalue anyway.
5828 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005829 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005830 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005831
Eli Friedman441cf102009-05-16 23:27:50 +00005832 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5833 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005834 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005835 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005836 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005837 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5838 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005839 return QualType();
5840 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005841 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005842 // The operand cannot be a bit-field
5843 Diag(OpLoc, diag::err_typecheck_address_of)
5844 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005845 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005846 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5847 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005848 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005849 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005850 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005851 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005852 } else if (isa<ObjCPropertyRefExpr>(op)) {
5853 // cannot take address of a property expression.
5854 Diag(OpLoc, diag::err_typecheck_address_of)
5855 << "property expression" << op->getSourceRange();
5856 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005857 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5858 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005859 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5860 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005861 } else if (isa<UnresolvedLookupExpr>(op)) {
5862 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005863 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005864 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005865 // with the register storage-class specifier.
5866 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5867 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005868 Diag(OpLoc, diag::err_typecheck_address_of)
5869 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005870 return QualType();
5871 }
John McCallba135432009-11-21 08:51:07 +00005872 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005873 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005874 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005875 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005876 // Could be a pointer to member, though, if there is an explicit
5877 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005878 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005879 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005880 if (Ctx && Ctx->isRecord()) {
5881 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005882 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005883 diag::err_cannot_form_pointer_to_member_of_reference_type)
5884 << FD->getDeclName() << FD->getType();
5885 return QualType();
5886 }
Mike Stump1eb44332009-09-09 15:08:12 +00005887
Sebastian Redlebc07d52009-02-03 20:19:35 +00005888 return Context.getMemberPointerType(op->getType(),
5889 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005890 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005891 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005892 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005893 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005894 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005895 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5896 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005897 return Context.getMemberPointerType(op->getType(),
5898 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5899 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005900 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005901 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005902
Eli Friedman441cf102009-05-16 23:27:50 +00005903 if (lval == Expr::LV_IncompleteVoidType) {
5904 // Taking the address of a void variable is technically illegal, but we
5905 // allow it in cases which are otherwise valid.
5906 // Example: "extern void x; void* y = &x;".
5907 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5908 }
5909
Reid Spencer5f016e22007-07-11 17:01:13 +00005910 // If the operand has type "type", the result has type "pointer to type".
5911 return Context.getPointerType(op->getType());
5912}
5913
Chris Lattner22caddc2008-11-23 09:13:29 +00005914QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005915 if (Op->isTypeDependent())
5916 return Context.DependentTy;
5917
Chris Lattner22caddc2008-11-23 09:13:29 +00005918 UsualUnaryConversions(Op);
5919 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005920
Chris Lattner22caddc2008-11-23 09:13:29 +00005921 // Note that per both C89 and C99, this is always legal, even if ptype is an
5922 // incomplete type or void. It would be possible to warn about dereferencing
5923 // a void pointer, but it's completely well-defined, and such a warning is
5924 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005925 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005926 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005927
John McCall183700f2009-09-21 23:43:11 +00005928 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005929 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005930
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005931 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005932 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005933 return QualType();
5934}
5935
5936static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5937 tok::TokenKind Kind) {
5938 BinaryOperator::Opcode Opc;
5939 switch (Kind) {
5940 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005941 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5942 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005943 case tok::star: Opc = BinaryOperator::Mul; break;
5944 case tok::slash: Opc = BinaryOperator::Div; break;
5945 case tok::percent: Opc = BinaryOperator::Rem; break;
5946 case tok::plus: Opc = BinaryOperator::Add; break;
5947 case tok::minus: Opc = BinaryOperator::Sub; break;
5948 case tok::lessless: Opc = BinaryOperator::Shl; break;
5949 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5950 case tok::lessequal: Opc = BinaryOperator::LE; break;
5951 case tok::less: Opc = BinaryOperator::LT; break;
5952 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5953 case tok::greater: Opc = BinaryOperator::GT; break;
5954 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5955 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5956 case tok::amp: Opc = BinaryOperator::And; break;
5957 case tok::caret: Opc = BinaryOperator::Xor; break;
5958 case tok::pipe: Opc = BinaryOperator::Or; break;
5959 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5960 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5961 case tok::equal: Opc = BinaryOperator::Assign; break;
5962 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5963 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5964 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5965 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5966 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5967 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5968 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5969 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5970 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5971 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5972 case tok::comma: Opc = BinaryOperator::Comma; break;
5973 }
5974 return Opc;
5975}
5976
5977static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5978 tok::TokenKind Kind) {
5979 UnaryOperator::Opcode Opc;
5980 switch (Kind) {
5981 default: assert(0 && "Unknown unary op!");
5982 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5983 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5984 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5985 case tok::star: Opc = UnaryOperator::Deref; break;
5986 case tok::plus: Opc = UnaryOperator::Plus; break;
5987 case tok::minus: Opc = UnaryOperator::Minus; break;
5988 case tok::tilde: Opc = UnaryOperator::Not; break;
5989 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005990 case tok::kw___real: Opc = UnaryOperator::Real; break;
5991 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5992 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5993 }
5994 return Opc;
5995}
5996
Douglas Gregoreaebc752008-11-06 23:29:22 +00005997/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5998/// operator @p Opc at location @c TokLoc. This routine only supports
5999/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006000Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6001 unsigned Op,
6002 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006003 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006004 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006005 // The following two variables are used for compound assignment operators
6006 QualType CompLHSTy; // Type of LHS after promotions for computation
6007 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006008
6009 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006010 case BinaryOperator::Assign:
6011 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6012 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006013 case BinaryOperator::PtrMemD:
6014 case BinaryOperator::PtrMemI:
6015 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6016 Opc == BinaryOperator::PtrMemI);
6017 break;
6018 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006019 case BinaryOperator::Div:
6020 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6021 break;
6022 case BinaryOperator::Rem:
6023 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6024 break;
6025 case BinaryOperator::Add:
6026 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6027 break;
6028 case BinaryOperator::Sub:
6029 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6030 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006031 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006032 case BinaryOperator::Shr:
6033 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6034 break;
6035 case BinaryOperator::LE:
6036 case BinaryOperator::LT:
6037 case BinaryOperator::GE:
6038 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006039 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006040 break;
6041 case BinaryOperator::EQ:
6042 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006043 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006044 break;
6045 case BinaryOperator::And:
6046 case BinaryOperator::Xor:
6047 case BinaryOperator::Or:
6048 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6049 break;
6050 case BinaryOperator::LAnd:
6051 case BinaryOperator::LOr:
6052 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6053 break;
6054 case BinaryOperator::MulAssign:
6055 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006056 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6057 CompLHSTy = CompResultTy;
6058 if (!CompResultTy.isNull())
6059 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006060 break;
6061 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006062 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6063 CompLHSTy = CompResultTy;
6064 if (!CompResultTy.isNull())
6065 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006066 break;
6067 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006068 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6069 if (!CompResultTy.isNull())
6070 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006071 break;
6072 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006073 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6074 if (!CompResultTy.isNull())
6075 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006076 break;
6077 case BinaryOperator::ShlAssign:
6078 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006079 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6080 CompLHSTy = CompResultTy;
6081 if (!CompResultTy.isNull())
6082 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006083 break;
6084 case BinaryOperator::AndAssign:
6085 case BinaryOperator::XorAssign:
6086 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006087 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6088 CompLHSTy = CompResultTy;
6089 if (!CompResultTy.isNull())
6090 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006091 break;
6092 case BinaryOperator::Comma:
6093 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6094 break;
6095 }
6096 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006097 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006098 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006099 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6100 else
6101 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006102 CompLHSTy, CompResultTy,
6103 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006104}
6105
Sebastian Redlaee3c932009-10-27 12:10:02 +00006106/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6107/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006108static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6109 const PartialDiagnostic &PD,
6110 SourceRange ParenRange)
6111{
6112 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6113 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6114 // We can't display the parentheses, so just dig the
6115 // warning/error and return.
6116 Self.Diag(Loc, PD);
6117 return;
6118 }
6119
6120 Self.Diag(Loc, PD)
6121 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6122 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6123}
6124
Sebastian Redlaee3c932009-10-27 12:10:02 +00006125/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6126/// operators are mixed in a way that suggests that the programmer forgot that
6127/// comparison operators have higher precedence. The most typical example of
6128/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006129static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6130 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006131 typedef BinaryOperator BinOp;
6132 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6133 rhsopc = static_cast<BinOp::Opcode>(-1);
6134 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006135 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006136 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006137 rhsopc = BO->getOpcode();
6138
6139 // Subs are not binary operators.
6140 if (lhsopc == -1 && rhsopc == -1)
6141 return;
6142
6143 // Bitwise operations are sometimes used as eager logical ops.
6144 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006145 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6146 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006147 return;
6148
Sebastian Redlaee3c932009-10-27 12:10:02 +00006149 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006150 SuggestParentheses(Self, OpLoc,
6151 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006152 << SourceRange(lhs->getLocStart(), OpLoc)
6153 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6154 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6155 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006156 SuggestParentheses(Self, OpLoc,
6157 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006158 << SourceRange(OpLoc, rhs->getLocEnd())
6159 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6160 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006161}
6162
6163/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6164/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6165/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6166static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6167 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006168 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006169 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6170}
6171
Reid Spencer5f016e22007-07-11 17:01:13 +00006172// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006173Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6174 tok::TokenKind Kind,
6175 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006176 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006177 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006178
Steve Narofff69936d2007-09-16 03:34:24 +00006179 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6180 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006181
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006182 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6183 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6184
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006185 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6186}
6187
6188Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6189 BinaryOperator::Opcode Opc,
6190 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006191 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006192 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006193 rhs->getType()->isOverloadableType())) {
6194 // Find all of the overloaded operators visible from this
6195 // point. We perform both an operator-name lookup from the local
6196 // scope and an argument-dependent lookup based on the types of
6197 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006198 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006199 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6200 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006201 if (S)
6202 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6203 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006204 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006205 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006206 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006207 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006208 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006209
Douglas Gregor063daf62009-03-13 18:40:31 +00006210 // Build the (potentially-overloaded, potentially-dependent)
6211 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006212 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006213 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006214
Douglas Gregoreaebc752008-11-06 23:29:22 +00006215 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006216 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006217}
6218
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006219Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006220 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006221 ExprArg InputArg) {
6222 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006223
Mike Stump390b4cc2009-05-16 07:39:55 +00006224 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006225 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006226 QualType resultType;
6227 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006228 case UnaryOperator::OffsetOf:
6229 assert(false && "Invalid unary operator");
6230 break;
6231
Reid Spencer5f016e22007-07-11 17:01:13 +00006232 case UnaryOperator::PreInc:
6233 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006234 case UnaryOperator::PostInc:
6235 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006236 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006237 Opc == UnaryOperator::PreInc ||
6238 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006239 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006240 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006241 resultType = CheckAddressOfOperand(Input, OpLoc);
6242 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006243 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006244 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006245 resultType = CheckIndirectionOperand(Input, OpLoc);
6246 break;
6247 case UnaryOperator::Plus:
6248 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006249 UsualUnaryConversions(Input);
6250 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006251 if (resultType->isDependentType())
6252 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006253 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6254 break;
6255 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6256 resultType->isEnumeralType())
6257 break;
6258 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6259 Opc == UnaryOperator::Plus &&
6260 resultType->isPointerType())
6261 break;
6262
Sebastian Redl0eb23302009-01-19 00:08:26 +00006263 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6264 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006265 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006266 UsualUnaryConversions(Input);
6267 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006268 if (resultType->isDependentType())
6269 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006270 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6271 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6272 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006273 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006274 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006275 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006276 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6277 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006278 break;
6279 case UnaryOperator::LNot: // logical negation
6280 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006281 DefaultFunctionArrayConversion(Input);
6282 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006283 if (resultType->isDependentType())
6284 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006285 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006286 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6287 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006288 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006289 // In C++, it's bool. C++ 5.3.1p8
6290 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006291 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006292 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006293 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006294 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006295 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006296 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006297 resultType = Input->getType();
6298 break;
6299 }
6300 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006301 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006302
6303 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006304 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006305}
6306
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006307Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6308 UnaryOperator::Opcode Opc,
6309 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006310 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006311 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6312 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006313 // Find all of the overloaded operators visible from this
6314 // point. We perform both an operator-name lookup from the local
6315 // scope and an argument-dependent lookup based on the types of
6316 // the arguments.
6317 FunctionSet Functions;
6318 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6319 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006320 if (S)
6321 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6322 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006323 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006324 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006325 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006326 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006327
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006328 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6329 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006330
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006331 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6332}
6333
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006334// Unary Operators. 'Tok' is the token for the operator.
6335Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6336 tok::TokenKind Op, ExprArg input) {
6337 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6338}
6339
Steve Naroff1b273c42007-09-16 14:56:35 +00006340/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006341Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6342 SourceLocation LabLoc,
6343 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006344 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006345 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006346
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006347 // If we haven't seen this label yet, create a forward reference. It
6348 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006349 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006350 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006351
Reid Spencer5f016e22007-07-11 17:01:13 +00006352 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006353 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6354 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006355}
6356
Sebastian Redlf53597f2009-03-15 17:47:39 +00006357Sema::OwningExprResult
6358Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6359 SourceLocation RPLoc) { // "({..})"
6360 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006361 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6362 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6363
Eli Friedmandca2b732009-01-24 23:09:00 +00006364 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006365 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006366 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006367
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006368 // FIXME: there are a variety of strange constraints to enforce here, for
6369 // example, it is not possible to goto into a stmt expression apparently.
6370 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006371
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006372 // If there are sub stmts in the compound stmt, take the type of the last one
6373 // as the type of the stmtexpr.
6374 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006375
Chris Lattner611b2ec2008-07-26 19:51:01 +00006376 if (!Compound->body_empty()) {
6377 Stmt *LastStmt = Compound->body_back();
6378 // If LastStmt is a label, skip down through into the body.
6379 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6380 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006381
Chris Lattner611b2ec2008-07-26 19:51:01 +00006382 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006383 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006384 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006385
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006386 // FIXME: Check that expression type is complete/non-abstract; statement
6387 // expressions are not lvalues.
6388
Sebastian Redlf53597f2009-03-15 17:47:39 +00006389 substmt.release();
6390 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006391}
Steve Naroffd34e9152007-08-01 22:05:33 +00006392
Sebastian Redlf53597f2009-03-15 17:47:39 +00006393Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6394 SourceLocation BuiltinLoc,
6395 SourceLocation TypeLoc,
6396 TypeTy *argty,
6397 OffsetOfComponent *CompPtr,
6398 unsigned NumComponents,
6399 SourceLocation RPLoc) {
6400 // FIXME: This function leaks all expressions in the offset components on
6401 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006402 // FIXME: Preserve type source info.
6403 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006404 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006405
Sebastian Redl28507842009-02-26 14:39:58 +00006406 bool Dependent = ArgTy->isDependentType();
6407
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006408 // We must have at least one component that refers to the type, and the first
6409 // one is known to be a field designator. Verify that the ArgTy represents
6410 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006411 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006412 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006413
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006414 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6415 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006416
Eli Friedman35183ac2009-02-27 06:44:11 +00006417 // Otherwise, create a null pointer as the base, and iteratively process
6418 // the offsetof designators.
6419 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6420 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006421 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006422 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006423
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006424 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6425 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006426 // FIXME: This diagnostic isn't actually visible because the location is in
6427 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006428 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006429 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6430 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006431
Sebastian Redl28507842009-02-26 14:39:58 +00006432 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006433 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006434
John McCalld00f2002009-11-04 03:03:43 +00006435 if (RequireCompleteType(TypeLoc, Res->getType(),
6436 diag::err_offsetof_incomplete_type))
6437 return ExprError();
6438
Sebastian Redl28507842009-02-26 14:39:58 +00006439 // FIXME: Dependent case loses a lot of information here. And probably
6440 // leaks like a sieve.
6441 for (unsigned i = 0; i != NumComponents; ++i) {
6442 const OffsetOfComponent &OC = CompPtr[i];
6443 if (OC.isBrackets) {
6444 // Offset of an array sub-field. TODO: Should we allow vector elements?
6445 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6446 if (!AT) {
6447 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006448 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6449 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006450 }
6451
6452 // FIXME: C++: Verify that operator[] isn't overloaded.
6453
Eli Friedman35183ac2009-02-27 06:44:11 +00006454 // Promote the array so it looks more like a normal array subscript
6455 // expression.
6456 DefaultFunctionArrayConversion(Res);
6457
Sebastian Redl28507842009-02-26 14:39:58 +00006458 // C99 6.5.2.1p1
6459 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006460 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006461 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006462 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006463 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006464 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006465
6466 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6467 OC.LocEnd);
6468 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006469 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006470
Ted Kremenek6217b802009-07-29 21:53:49 +00006471 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006472 if (!RC) {
6473 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006474 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6475 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006476 }
Chris Lattner704fe352007-08-30 17:59:59 +00006477
Sebastian Redl28507842009-02-26 14:39:58 +00006478 // Get the decl corresponding to this.
6479 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006480 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006481 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Douglas Gregor75b699a2009-12-12 07:25:49 +00006482 switch (ExprEvalContexts.back().Context ) {
6483 case Unevaluated:
6484 // The argument will never be evaluated, so don't complain.
6485 break;
6486
6487 case PotentiallyEvaluated:
6488 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6489 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6490 << Res->getType());
6491 DidWarnAboutNonPOD = true;
6492 break;
6493
6494 case PotentiallyPotentiallyEvaluated:
Douglas Gregor06d33692009-12-12 07:57:52 +00006495 ExprEvalContexts.back().addDiagnostic(BuiltinLoc,
6496 PDiag(diag::warn_offsetof_non_pod_type)
6497 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6498 << Res->getType());
Douglas Gregor75b699a2009-12-12 07:25:49 +00006499 DidWarnAboutNonPOD = true;
6500 break;
6501 }
Anders Carlsson5992e4a2009-05-02 18:36:10 +00006502 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006503 }
Mike Stump1eb44332009-09-09 15:08:12 +00006504
John McCalla24dc2e2009-11-17 02:14:36 +00006505 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6506 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006507
John McCall1bcee0a2009-12-02 08:25:40 +00006508 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006509 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006510 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006511 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6512 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006513
Sebastian Redl28507842009-02-26 14:39:58 +00006514 // FIXME: C++: Verify that MemberDecl isn't a static field.
6515 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006516 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006517 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006518 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006519 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006520 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006521 // MemberDecl->getType() doesn't get the right qualifiers, but it
6522 // doesn't matter here.
6523 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6524 MemberDecl->getType().getNonReferenceType());
6525 }
Sebastian Redl28507842009-02-26 14:39:58 +00006526 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006527 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006528
Sebastian Redlf53597f2009-03-15 17:47:39 +00006529 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6530 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006531}
6532
6533
Sebastian Redlf53597f2009-03-15 17:47:39 +00006534Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6535 TypeTy *arg1,TypeTy *arg2,
6536 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006537 // FIXME: Preserve type source info.
6538 QualType argT1 = GetTypeFromParser(arg1);
6539 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006540
Steve Naroffd34e9152007-08-01 22:05:33 +00006541 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006542
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006543 if (getLangOptions().CPlusPlus) {
6544 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6545 << SourceRange(BuiltinLoc, RPLoc);
6546 return ExprError();
6547 }
6548
Sebastian Redlf53597f2009-03-15 17:47:39 +00006549 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6550 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006551}
6552
Sebastian Redlf53597f2009-03-15 17:47:39 +00006553Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6554 ExprArg cond,
6555 ExprArg expr1, ExprArg expr2,
6556 SourceLocation RPLoc) {
6557 Expr *CondExpr = static_cast<Expr*>(cond.get());
6558 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6559 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006560
Steve Naroffd04fdd52007-08-03 21:21:27 +00006561 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6562
Sebastian Redl28507842009-02-26 14:39:58 +00006563 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006564 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006565 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006566 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006567 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006568 } else {
6569 // The conditional expression is required to be a constant expression.
6570 llvm::APSInt condEval(32);
6571 SourceLocation ExpLoc;
6572 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006573 return ExprError(Diag(ExpLoc,
6574 diag::err_typecheck_choose_expr_requires_constant)
6575 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006576
Sebastian Redl28507842009-02-26 14:39:58 +00006577 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6578 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006579 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6580 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006581 }
6582
Sebastian Redlf53597f2009-03-15 17:47:39 +00006583 cond.release(); expr1.release(); expr2.release();
6584 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006585 resType, RPLoc,
6586 resType->isDependentType(),
6587 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006588}
6589
Steve Naroff4eb206b2008-09-03 18:15:37 +00006590//===----------------------------------------------------------------------===//
6591// Clang Extensions.
6592//===----------------------------------------------------------------------===//
6593
6594/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006595void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006596 // Analyze block parameters.
6597 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006598
Steve Naroff4eb206b2008-09-03 18:15:37 +00006599 // Add BSI to CurBlock.
6600 BSI->PrevBlockInfo = CurBlock;
6601 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006602
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006603 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006604 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006605 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006606 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006607 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6608 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006609
Steve Naroff090276f2008-10-10 01:28:17 +00006610 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006611 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006612 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006613}
6614
Mike Stump98eb8a72009-02-04 22:31:32 +00006615void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006616 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006617
6618 if (ParamInfo.getNumTypeObjects() == 0
6619 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006620 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006621 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6622
Mike Stump4eeab842009-04-28 01:10:27 +00006623 if (T->isArrayType()) {
6624 Diag(ParamInfo.getSourceRange().getBegin(),
6625 diag::err_block_returns_array);
6626 return;
6627 }
6628
Mike Stump98eb8a72009-02-04 22:31:32 +00006629 // The parameter list is optional, if there was none, assume ().
6630 if (!T->isFunctionType())
6631 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6632
6633 CurBlock->hasPrototype = true;
6634 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006635 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006636 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006637 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006638 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006639 // FIXME: remove the attribute.
6640 }
John McCall183700f2009-09-21 23:43:11 +00006641 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006642
Chris Lattner9097af12009-04-11 19:27:54 +00006643 // Do not allow returning a objc interface by-value.
6644 if (RetTy->isObjCInterfaceType()) {
6645 Diag(ParamInfo.getSourceRange().getBegin(),
6646 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6647 return;
6648 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006649 return;
6650 }
6651
Steve Naroff4eb206b2008-09-03 18:15:37 +00006652 // Analyze arguments to block.
6653 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6654 "Not a function declarator!");
6655 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006656
Steve Naroff090276f2008-10-10 01:28:17 +00006657 CurBlock->hasPrototype = FTI.hasPrototype;
6658 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006659
Steve Naroff4eb206b2008-09-03 18:15:37 +00006660 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6661 // no arguments, not a function that takes a single void argument.
6662 if (FTI.hasPrototype &&
6663 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006664 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6665 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006666 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006667 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006668 } else if (FTI.hasPrototype) {
6669 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006670 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006671 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006672 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006673 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006674 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006675 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006676 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006677 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6678 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6679 // If this has an identifier, add it to the scope stack.
6680 if ((*AI)->getIdentifier())
6681 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006682
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006683 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006684 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006685 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006686 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006687 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006688 // FIXME: remove the attribute.
6689 }
Mike Stump1eb44332009-09-09 15:08:12 +00006690
Chris Lattner9097af12009-04-11 19:27:54 +00006691 // Analyze the return type.
6692 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006693 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006694
Chris Lattner9097af12009-04-11 19:27:54 +00006695 // Do not allow returning a objc interface by-value.
6696 if (RetTy->isObjCInterfaceType()) {
6697 Diag(ParamInfo.getSourceRange().getBegin(),
6698 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6699 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006700 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006701}
6702
6703/// ActOnBlockError - If there is an error parsing a block, this callback
6704/// is invoked to pop the information about the block from the action impl.
6705void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6706 // Ensure that CurBlock is deleted.
6707 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006708
Chris Lattner17a78302009-04-19 05:28:12 +00006709 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6710
Steve Naroff4eb206b2008-09-03 18:15:37 +00006711 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006712 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006713 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006714 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006715}
6716
6717/// ActOnBlockStmtExpr - This is called when the body of a block statement
6718/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006719Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6720 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006721 // If blocks are disabled, emit an error.
6722 if (!LangOpts.Blocks)
6723 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006724
Steve Naroff4eb206b2008-09-03 18:15:37 +00006725 // Ensure that CurBlock is deleted.
6726 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006727
Steve Naroff090276f2008-10-10 01:28:17 +00006728 PopDeclContext();
6729
Steve Naroff4eb206b2008-09-03 18:15:37 +00006730 // Pop off CurBlock, handle nested blocks.
6731 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006732
Steve Naroff4eb206b2008-09-03 18:15:37 +00006733 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006734 if (!BSI->ReturnType.isNull())
6735 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006736
Steve Naroff4eb206b2008-09-03 18:15:37 +00006737 llvm::SmallVector<QualType, 8> ArgTypes;
6738 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6739 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006740
Mike Stump56925862009-07-28 22:04:01 +00006741 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006742 QualType BlockTy;
6743 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006744 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6745 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006746 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006747 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006748 BSI->isVariadic, 0, false, false, 0, 0,
6749 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006750
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006751 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006752 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006753 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006754
Chris Lattner17a78302009-04-19 05:28:12 +00006755 // If needed, diagnose invalid gotos and switches in the block.
6756 if (CurFunctionNeedsScopeChecking)
6757 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6758 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006759
Anders Carlssone9146f22009-05-01 19:49:17 +00006760 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006761 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006762 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6763 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006764}
6765
Sebastian Redlf53597f2009-03-15 17:47:39 +00006766Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6767 ExprArg expr, TypeTy *type,
6768 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006769 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006770 Expr *E = static_cast<Expr*>(expr.get());
6771 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006772
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006773 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006774
6775 // Get the va_list type
6776 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006777 if (VaListType->isArrayType()) {
6778 // Deal with implicit array decay; for example, on x86-64,
6779 // va_list is an array, but it's supposed to decay to
6780 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006781 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006782 // Make sure the input expression also decays appropriately.
6783 UsualUnaryConversions(E);
6784 } else {
6785 // Otherwise, the va_list argument must be an l-value because
6786 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006787 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006788 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006789 return ExprError();
6790 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006791
Douglas Gregordd027302009-05-19 23:10:31 +00006792 if (!E->isTypeDependent() &&
6793 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006794 return ExprError(Diag(E->getLocStart(),
6795 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006796 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006797 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006798
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006799 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006800 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006801
Sebastian Redlf53597f2009-03-15 17:47:39 +00006802 expr.release();
6803 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6804 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006805}
6806
Sebastian Redlf53597f2009-03-15 17:47:39 +00006807Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006808 // The type of __null will be int or long, depending on the size of
6809 // pointers on the target.
6810 QualType Ty;
6811 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6812 Ty = Context.IntTy;
6813 else
6814 Ty = Context.LongTy;
6815
Sebastian Redlf53597f2009-03-15 17:47:39 +00006816 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006817}
6818
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006819static void
6820MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6821 QualType DstType,
6822 Expr *SrcExpr,
6823 CodeModificationHint &Hint) {
6824 if (!SemaRef.getLangOptions().ObjC1)
6825 return;
6826
6827 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6828 if (!PT)
6829 return;
6830
6831 // Check if the destination is of type 'id'.
6832 if (!PT->isObjCIdType()) {
6833 // Check if the destination is the 'NSString' interface.
6834 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6835 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6836 return;
6837 }
6838
6839 // Strip off any parens and casts.
6840 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6841 if (!SL || SL->isWide())
6842 return;
6843
6844 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6845}
6846
Chris Lattner5cf216b2008-01-04 18:04:52 +00006847bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6848 SourceLocation Loc,
6849 QualType DstType, QualType SrcType,
6850 Expr *SrcExpr, const char *Flavor) {
6851 // Decode the result (notice that AST's are still created for extensions).
6852 bool isInvalid = false;
6853 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006854 CodeModificationHint Hint;
6855
Chris Lattner5cf216b2008-01-04 18:04:52 +00006856 switch (ConvTy) {
6857 default: assert(0 && "Unknown conversion type");
6858 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006859 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006860 DiagKind = diag::ext_typecheck_convert_pointer_int;
6861 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006862 case IntToPointer:
6863 DiagKind = diag::ext_typecheck_convert_int_pointer;
6864 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006865 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006866 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006867 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6868 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006869 case IncompatiblePointerSign:
6870 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6871 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006872 case FunctionVoidPointer:
6873 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6874 break;
6875 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006876 // If the qualifiers lost were because we were applying the
6877 // (deprecated) C++ conversion from a string literal to a char*
6878 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6879 // Ideally, this check would be performed in
6880 // CheckPointerTypesForAssignment. However, that would require a
6881 // bit of refactoring (so that the second argument is an
6882 // expression, rather than a type), which should be done as part
6883 // of a larger effort to fix CheckPointerTypesForAssignment for
6884 // C++ semantics.
6885 if (getLangOptions().CPlusPlus &&
6886 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6887 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006888 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6889 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006890 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006891 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006892 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006893 case IntToBlockPointer:
6894 DiagKind = diag::err_int_to_block_pointer;
6895 break;
6896 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006897 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006898 break;
Steve Naroff39579072008-10-14 22:18:38 +00006899 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006900 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006901 // it can give a more specific diagnostic.
6902 DiagKind = diag::warn_incompatible_qualified_id;
6903 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006904 case IncompatibleVectors:
6905 DiagKind = diag::warn_incompatible_vectors;
6906 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006907 case Incompatible:
6908 DiagKind = diag::err_typecheck_convert_incompatible;
6909 isInvalid = true;
6910 break;
6911 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006912
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006913 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006914 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006915 return isInvalid;
6916}
Anders Carlssone21555e2008-11-30 19:50:32 +00006917
Chris Lattner3bf68932009-04-25 21:59:05 +00006918bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006919 llvm::APSInt ICEResult;
6920 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6921 if (Result)
6922 *Result = ICEResult;
6923 return false;
6924 }
6925
Anders Carlssone21555e2008-11-30 19:50:32 +00006926 Expr::EvalResult EvalResult;
6927
Mike Stumpeed9cac2009-02-19 03:04:26 +00006928 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006929 EvalResult.HasSideEffects) {
6930 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6931
6932 if (EvalResult.Diag) {
6933 // We only show the note if it's not the usual "invalid subexpression"
6934 // or if it's actually in a subexpression.
6935 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6936 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6937 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6938 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006939
Anders Carlssone21555e2008-11-30 19:50:32 +00006940 return true;
6941 }
6942
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006943 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6944 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006945
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006946 if (EvalResult.Diag &&
6947 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6948 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006949
Anders Carlssone21555e2008-11-30 19:50:32 +00006950 if (Result)
6951 *Result = EvalResult.Val.getInt();
6952 return false;
6953}
Douglas Gregore0762c92009-06-19 23:52:42 +00006954
Douglas Gregor2afce722009-11-26 00:44:06 +00006955void
Mike Stump1eb44332009-09-09 15:08:12 +00006956Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006957 ExprEvalContexts.push_back(
6958 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006959}
6960
Mike Stump1eb44332009-09-09 15:08:12 +00006961void
Douglas Gregor2afce722009-11-26 00:44:06 +00006962Sema::PopExpressionEvaluationContext() {
6963 // Pop the current expression evaluation context off the stack.
6964 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6965 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006966
Douglas Gregor06d33692009-12-12 07:57:52 +00006967 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
6968 if (Rec.PotentiallyReferenced) {
6969 // Mark any remaining declarations in the current position of the stack
6970 // as "referenced". If they were not meant to be referenced, semantic
6971 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6972 for (PotentiallyReferencedDecls::iterator
6973 I = Rec.PotentiallyReferenced->begin(),
6974 IEnd = Rec.PotentiallyReferenced->end();
6975 I != IEnd; ++I)
6976 MarkDeclarationReferenced(I->first, I->second);
6977 }
6978
6979 if (Rec.PotentiallyDiagnosed) {
6980 // Emit any pending diagnostics.
6981 for (PotentiallyEmittedDiagnostics::iterator
6982 I = Rec.PotentiallyDiagnosed->begin(),
6983 IEnd = Rec.PotentiallyDiagnosed->end();
6984 I != IEnd; ++I)
6985 Diag(I->first, I->second);
6986 }
Douglas Gregor2afce722009-11-26 00:44:06 +00006987 }
6988
6989 // When are coming out of an unevaluated context, clear out any
6990 // temporaries that we may have created as part of the evaluation of
6991 // the expression in that context: they aren't relevant because they
6992 // will never be constructed.
6993 if (Rec.Context == Unevaluated &&
6994 ExprTemporaries.size() > Rec.NumTemporaries)
6995 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6996 ExprTemporaries.end());
6997
6998 // Destroy the popped expression evaluation record.
6999 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007000}
Douglas Gregore0762c92009-06-19 23:52:42 +00007001
7002/// \brief Note that the given declaration was referenced in the source code.
7003///
7004/// This routine should be invoke whenever a given declaration is referenced
7005/// in the source code, and where that reference occurred. If this declaration
7006/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7007/// C99 6.9p3), then the declaration will be marked as used.
7008///
7009/// \param Loc the location where the declaration was referenced.
7010///
7011/// \param D the declaration that has been referenced by the source code.
7012void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7013 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007014
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007015 if (D->isUsed())
7016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007017
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007018 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7019 // template or not. The reason for this is that unevaluated expressions
7020 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7021 // -Wunused-parameters)
7022 if (isa<ParmVarDecl>(D) ||
7023 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007024 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007025
Douglas Gregore0762c92009-06-19 23:52:42 +00007026 // Do not mark anything as "used" within a dependent context; wait for
7027 // an instantiation.
7028 if (CurContext->isDependentContext())
7029 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007030
Douglas Gregor2afce722009-11-26 00:44:06 +00007031 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007032 case Unevaluated:
7033 // We are in an expression that is not potentially evaluated; do nothing.
7034 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007035
Douglas Gregorac7610d2009-06-22 20:57:11 +00007036 case PotentiallyEvaluated:
7037 // We are in a potentially-evaluated expression, so this declaration is
7038 // "used"; handle this below.
7039 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007040
Douglas Gregorac7610d2009-06-22 20:57:11 +00007041 case PotentiallyPotentiallyEvaluated:
7042 // We are in an expression that may be potentially evaluated; queue this
7043 // declaration reference until we know whether the expression is
7044 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007045 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007046 return;
7047 }
Mike Stump1eb44332009-09-09 15:08:12 +00007048
Douglas Gregore0762c92009-06-19 23:52:42 +00007049 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007050 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007051 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007052 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7053 if (!Constructor->isUsed())
7054 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007055 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007056 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007057 if (!Constructor->isUsed())
7058 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7059 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007060
7061 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007062 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7063 if (Destructor->isImplicit() && !Destructor->isUsed())
7064 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007065
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007066 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7067 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7068 MethodDecl->getOverloadedOperator() == OO_Equal) {
7069 if (!MethodDecl->isUsed())
7070 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7071 }
7072 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007073 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007074 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007075 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007076 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007077 bool AlreadyInstantiated = false;
7078 if (FunctionTemplateSpecializationInfo *SpecInfo
7079 = Function->getTemplateSpecializationInfo()) {
7080 if (SpecInfo->getPointOfInstantiation().isInvalid())
7081 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007082 else if (SpecInfo->getTemplateSpecializationKind()
7083 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007084 AlreadyInstantiated = true;
7085 } else if (MemberSpecializationInfo *MSInfo
7086 = Function->getMemberSpecializationInfo()) {
7087 if (MSInfo->getPointOfInstantiation().isInvalid())
7088 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007089 else if (MSInfo->getTemplateSpecializationKind()
7090 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007091 AlreadyInstantiated = true;
7092 }
7093
7094 if (!AlreadyInstantiated)
7095 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7096 }
7097
Douglas Gregore0762c92009-06-19 23:52:42 +00007098 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007099 Function->setUsed(true);
7100 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007101 }
Mike Stump1eb44332009-09-09 15:08:12 +00007102
Douglas Gregore0762c92009-06-19 23:52:42 +00007103 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007104 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007105 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007106 Var->getInstantiatedFromStaticDataMember()) {
7107 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7108 assert(MSInfo && "Missing member specialization information?");
7109 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7110 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7111 MSInfo->setPointOfInstantiation(Loc);
7112 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7113 }
7114 }
Mike Stump1eb44332009-09-09 15:08:12 +00007115
Douglas Gregore0762c92009-06-19 23:52:42 +00007116 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007117
Douglas Gregore0762c92009-06-19 23:52:42 +00007118 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007119 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007120 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007121}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007122
7123bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7124 CallExpr *CE, FunctionDecl *FD) {
7125 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7126 return false;
7127
7128 PartialDiagnostic Note =
7129 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7130 << FD->getDeclName() : PDiag();
7131 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7132
7133 if (RequireCompleteType(Loc, ReturnType,
7134 FD ?
7135 PDiag(diag::err_call_function_incomplete_return)
7136 << CE->getSourceRange() << FD->getDeclName() :
7137 PDiag(diag::err_call_incomplete_return)
7138 << CE->getSourceRange(),
7139 std::make_pair(NoteLoc, Note)))
7140 return true;
7141
7142 return false;
7143}
7144
John McCall5a881bb2009-10-12 21:59:07 +00007145// Diagnose the common s/=/==/ typo. Note that adding parentheses
7146// will prevent this condition from triggering, which is what we want.
7147void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7148 SourceLocation Loc;
7149
John McCalla52ef082009-11-11 02:41:58 +00007150 unsigned diagnostic = diag::warn_condition_is_assignment;
7151
John McCall5a881bb2009-10-12 21:59:07 +00007152 if (isa<BinaryOperator>(E)) {
7153 BinaryOperator *Op = cast<BinaryOperator>(E);
7154 if (Op->getOpcode() != BinaryOperator::Assign)
7155 return;
7156
John McCallc8d8ac52009-11-12 00:06:05 +00007157 // Greylist some idioms by putting them into a warning subcategory.
7158 if (ObjCMessageExpr *ME
7159 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7160 Selector Sel = ME->getSelector();
7161
John McCallc8d8ac52009-11-12 00:06:05 +00007162 // self = [<foo> init...]
7163 if (isSelfExpr(Op->getLHS())
7164 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7165 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7166
7167 // <foo> = [<bar> nextObject]
7168 else if (Sel.isUnarySelector() &&
7169 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7170 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7171 }
John McCalla52ef082009-11-11 02:41:58 +00007172
John McCall5a881bb2009-10-12 21:59:07 +00007173 Loc = Op->getOperatorLoc();
7174 } else if (isa<CXXOperatorCallExpr>(E)) {
7175 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7176 if (Op->getOperator() != OO_Equal)
7177 return;
7178
7179 Loc = Op->getOperatorLoc();
7180 } else {
7181 // Not an assignment.
7182 return;
7183 }
7184
John McCall5a881bb2009-10-12 21:59:07 +00007185 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007186 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007187
John McCalla52ef082009-11-11 02:41:58 +00007188 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007189 << E->getSourceRange()
7190 << CodeModificationHint::CreateInsertion(Open, "(")
7191 << CodeModificationHint::CreateInsertion(Close, ")");
7192}
7193
7194bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7195 DiagnoseAssignmentAsCondition(E);
7196
7197 if (!E->isTypeDependent()) {
7198 DefaultFunctionArrayConversion(E);
7199
7200 QualType T = E->getType();
7201
7202 if (getLangOptions().CPlusPlus) {
7203 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7204 return true;
7205 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7206 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7207 << T << E->getSourceRange();
7208 return true;
7209 }
7210 }
7211
7212 return false;
7213}