blob: f1311098336d7f4e8e1c27b410b2cd8c5a0778a4 [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
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000262 if (Expr->getType()->isObjCInterfaceType() &&
263 DiagRuntimeBehavior(Expr->getLocStart(),
264 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
265 << Expr->getType() << CT))
266 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000267
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000268 if (!Expr->getType()->isPODType() &&
269 DiagRuntimeBehavior(Expr->getLocStart(),
270 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
271 << Expr->getType() << CT))
272 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000273
274 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000275}
276
277
Chris Lattnere7a2e912008-07-25 21:10:04 +0000278/// UsualArithmeticConversions - Performs various conversions that are common to
279/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000281/// responsible for emitting appropriate error diagnostics.
282/// FIXME: verify the conversion rules for "complex int" are consistent with
283/// GCC.
284QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
285 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000286 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000287 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000288
289 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000290
Mike Stump1eb44332009-09-09 15:08:12 +0000291 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000292 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000293 QualType lhs =
294 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000295 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000296 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000297
298 // If both types are identical, no conversion is needed.
299 if (lhs == rhs)
300 return lhs;
301
302 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
303 // The caller can deal with this (e.g. pointer + int).
304 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
305 return lhs;
306
Douglas Gregor2d833e32009-05-02 00:36:19 +0000307 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000308 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000309 if (!LHSBitfieldPromoteTy.isNull())
310 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000311 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000312 if (!RHSBitfieldPromoteTy.isNull())
313 rhs = RHSBitfieldPromoteTy;
314
Eli Friedmana95d7572009-08-19 07:44:53 +0000315 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000316 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000317 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
318 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000319 return destType;
320}
321
Chris Lattnere7a2e912008-07-25 21:10:04 +0000322//===----------------------------------------------------------------------===//
323// Semantic Analysis for various Expression Types
324//===----------------------------------------------------------------------===//
325
326
Steve Narofff69936d2007-09-16 03:34:24 +0000327/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000328/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
329/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
330/// multiple tokens. However, the common case is that StringToks points to one
331/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000332///
333Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000334Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 assert(NumStringToks && "Must have at least one string!");
336
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000337 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000339 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000340
341 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
342 for (unsigned i = 0; i != NumStringToks; ++i)
343 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000344
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000345 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000346 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000347 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000348
349 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
350 if (getLangOptions().CPlusPlus)
351 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000352
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000353 // Get an array type for the string, according to C99 6.4.5. This includes
354 // the nul terminator character as well as the string length for pascal
355 // strings.
356 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000357 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000358 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000361 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000362 Literal.GetStringLength(),
363 Literal.AnyWide, StrTy,
364 &StringTokLocs[0],
365 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000366}
367
Chris Lattner639e2d32008-10-20 05:16:36 +0000368/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
369/// CurBlock to VD should cause it to be snapshotted (as we do for auto
370/// variables defined outside the block) or false if this is not needed (e.g.
371/// for values inside the block or for globals).
372///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000373/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
374/// up-to-date.
375///
Chris Lattner639e2d32008-10-20 05:16:36 +0000376static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
377 ValueDecl *VD) {
378 // If the value is defined inside the block, we couldn't snapshot it even if
379 // we wanted to.
380 if (CurBlock->TheDecl == VD->getDeclContext())
381 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chris Lattner639e2d32008-10-20 05:16:36 +0000383 // If this is an enum constant or function, it is constant, don't snapshot.
384 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
385 return false;
386
387 // If this is a reference to an extern, static, or global variable, no need to
388 // snapshot it.
389 // FIXME: What about 'const' variables in C++?
390 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000391 if (!Var->hasLocalStorage())
392 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000394 // Blocks that have these can't be constant.
395 CurBlock->hasBlockDeclRefExprs = true;
396
397 // If we have nested blocks, the decl may be declared in an outer block (in
398 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
399 // be defined outside all of the current blocks (in which case the blocks do
400 // all get the bit). Walk the nesting chain.
401 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
402 NextBlock = NextBlock->PrevBlockInfo) {
403 // If we found the defining block for the variable, don't mark the block as
404 // having a reference outside it.
405 if (NextBlock->TheDecl == VD->getDeclContext())
406 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000408 // Otherwise, the DeclRef from the inner block causes the outer one to need
409 // a snapshot as well.
410 NextBlock->hasBlockDeclRefExprs = true;
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner639e2d32008-10-20 05:16:36 +0000413 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000414}
415
Chris Lattner639e2d32008-10-20 05:16:36 +0000416
417
Douglas Gregora2813ce2009-10-23 18:54:35 +0000418/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000419Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000420Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000421 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
423 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000424 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000425 << D->getDeclName();
426 return ExprError();
427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Anders Carlssone41590d2009-06-24 00:10:43 +0000429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
430 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
432 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000434 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000435 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000436 << D->getIdentifier();
437 return ExprError();
438 }
439 }
440 }
441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregore0762c92009-06-19 23:52:42 +0000443 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregora2813ce2009-10-23 18:54:35 +0000445 return Owned(DeclRefExpr::Create(Context,
446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
447 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000448 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000449}
450
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000451/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
452/// variable corresponding to the anonymous union or struct whose type
453/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000454static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
455 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000457 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Mike Stump390b4cc2009-05-16 07:39:55 +0000459 // FIXME: Once Decls are directly linked together, this will be an O(1)
460 // operation rather than a slow walk through DeclContext's vector (which
461 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000462 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000463 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000464 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000465 D != DEnd; ++D) {
466 if (*D == Record) {
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
469 ++D;
470 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000472 return *D;
473 }
474 }
475
476 assert(false && "Missing object for anonymous record");
477 return 0;
478}
479
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000480/// \brief Given a field that represents a member of an anonymous
481/// struct/union, build the path from that field's context to the
482/// actual member.
483///
484/// Construct the sequence of field member references we'll have to
485/// perform to get to the field in the anonymous union/struct. The
486/// list of members is built from the field outward, so traverse it
487/// backwards to go from an object in the current context to the field
488/// we found.
489///
490/// \returns The variable from which the field access should begin,
491/// for an anonymous struct/union that is not a member of another
492/// class. Otherwise, returns NULL.
493VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
494 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000495 assert(Field->getDeclContext()->isRecord() &&
496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
497 && "Field must be stored inside an anonymous struct or union");
498
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000499 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000500 VarDecl *BaseObject = 0;
501 DeclContext *Ctx = Field->getDeclContext();
502 do {
503 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000506 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000507 else {
508 BaseObject = cast<VarDecl>(AnonObject);
509 break;
510 }
511 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000512 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000514
515 return BaseObject;
516}
517
518Sema::OwningExprResult
519Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
520 FieldDecl *Field,
521 Expr *BaseObjectExpr,
522 SourceLocation OpLoc) {
523 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000525 AnonFields);
526
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 // Build the expression that refers to the base object, from
528 // which we will build a sequence of member references to each
529 // of the anonymous union objects and, eventually, the field we
530 // found via name lookup.
531 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000532 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 if (BaseObject) {
534 // BaseObject is an anonymous struct/union variable (and is,
535 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000537 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000539 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000540 BaseQuals
541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
John McCall0953e762009-09-24 19:53:00 +0000551 BaseQuals
552 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000553 } else {
554 // We've found a member of an anonymous struct/union that is
555 // inside a non-anonymous struct/union, so in a well-formed
556 // program our base object expression is "this".
557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
558 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000559 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000560 = Context.getTagDeclType(
561 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
562 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000563 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000564 == Context.getCanonicalType(ThisType)) ||
565 IsDerivedFrom(ThisType, AnonFieldType)) {
566 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000567 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000568 MD->getThisType(Context),
569 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000570 BaseObjectIsPointer = true;
571 }
572 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000573 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
574 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 }
John McCall0953e762009-09-24 19:53:00 +0000576 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000577 }
578
Mike Stump1eb44332009-09-09 15:08:12 +0000579 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000580 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
581 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000582 }
583
584 // Build the implicit member references to the field of the
585 // anonymous struct/union.
586 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000587 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000588 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
589 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
590 FI != FIEnd; ++FI) {
591 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000592 Qualifiers MemberTypeQuals =
593 Context.getCanonicalType(MemberType).getQualifiers();
594
595 // CVR attributes from the base are picked up by members,
596 // except that 'mutable' members don't pick up 'const'.
597 if ((*FI)->isMutable())
598 ResultQuals.removeConst();
599
600 // GC attributes are never picked up by members.
601 ResultQuals.removeObjCGCAttr();
602
603 // TR 18037 does not allow fields to be declared with address spaces.
604 assert(!MemberTypeQuals.hasAddressSpace());
605
606 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
607 if (NewQuals != MemberTypeQuals)
608 MemberType = Context.getQualifiedType(MemberType, NewQuals);
609
Douglas Gregore0762c92009-06-19 23:52:42 +0000610 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000611 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000612 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000613 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
614 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000615 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000616 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000617 }
618
Sebastian Redlcd965b92009-01-18 18:53:16 +0000619 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000620}
621
John McCall129e2df2009-11-30 22:42:35 +0000622/// Decomposes the given name into a DeclarationName, its location, and
623/// possibly a list of template arguments.
624///
625/// If this produces template arguments, it is permitted to call
626/// DecomposeTemplateName.
627///
628/// This actually loses a lot of source location information for
629/// non-standard name kinds; we should consider preserving that in
630/// some way.
631static void DecomposeUnqualifiedId(Sema &SemaRef,
632 const UnqualifiedId &Id,
633 TemplateArgumentListInfo &Buffer,
634 DeclarationName &Name,
635 SourceLocation &NameLoc,
636 const TemplateArgumentListInfo *&TemplateArgs) {
637 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
638 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
639 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
640
641 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
642 Id.TemplateId->getTemplateArgs(),
643 Id.TemplateId->NumArgs);
644 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
645 TemplateArgsPtr.release();
646
647 TemplateName TName =
648 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
649
650 Name = SemaRef.Context.getNameForTemplate(TName);
651 NameLoc = Id.TemplateId->TemplateNameLoc;
652 TemplateArgs = &Buffer;
653 } else {
654 Name = SemaRef.GetNameFromUnqualifiedId(Id);
655 NameLoc = Id.StartLocation;
656 TemplateArgs = 0;
657 }
658}
659
660/// Decompose the given template name into a list of lookup results.
661///
662/// The unqualified ID must name a non-dependent template, which can
663/// be more easily tested by checking whether DecomposeUnqualifiedId
664/// found template arguments.
665static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
666 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
667 TemplateName TName =
668 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
669
John McCallf7a1a742009-11-24 19:00:30 +0000670 if (TemplateDecl *TD = TName.getAsTemplateDecl())
671 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000672 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
673 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
674 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000675 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000676
John McCallf7a1a742009-11-24 19:00:30 +0000677 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000678}
679
John McCall129e2df2009-11-30 22:42:35 +0000680static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
681 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
682 E = Record->bases_end(); I != E; ++I) {
683 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
684 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
685 if (!BaseRT) return false;
686
687 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
688 if (!BaseRecord->isDefinition() ||
689 !IsFullyFormedScope(SemaRef, BaseRecord))
690 return false;
691 }
692
693 return true;
694}
695
John McCalle1599ce2009-11-30 23:50:49 +0000696/// Determines whether we can lookup this id-expression now or whether
697/// we have to wait until template instantiation is complete.
698static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000699 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000700
John McCalle1599ce2009-11-30 23:50:49 +0000701 // If the qualifier scope isn't computable, it's definitely dependent.
702 if (!DC) return true;
703
704 // If the qualifier scope doesn't name a record, we can always look into it.
705 if (!isa<CXXRecordDecl>(DC)) return false;
706
707 // We can't look into record types unless they're fully-formed.
708 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
709
John McCallaa81e162009-12-01 22:10:20 +0000710 return false;
711}
John McCalle1599ce2009-11-30 23:50:49 +0000712
John McCallaa81e162009-12-01 22:10:20 +0000713/// Determines if the given class is provably not derived from all of
714/// the prospective base classes.
715static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
716 CXXRecordDecl *Record,
717 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000718 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000719 return false;
720
John McCallb1b42562009-12-01 22:28:41 +0000721 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
722 if (!RD) return false;
723 Record = cast<CXXRecordDecl>(RD);
724
John McCallaa81e162009-12-01 22:10:20 +0000725 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
726 E = Record->bases_end(); I != E; ++I) {
727 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
728 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
729 if (!BaseRT) return false;
730
731 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000732 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
733 return false;
734 }
735
736 return true;
737}
738
John McCall144238e2009-12-02 20:26:00 +0000739/// Determines if this is an instance member of a class.
740static bool IsInstanceMember(NamedDecl *D) {
John McCall3b4294e2009-12-16 12:17:52 +0000741 assert(D->isCXXClassMember() &&
John McCallaa81e162009-12-01 22:10:20 +0000742 "checking whether non-member is instance member");
743
744 if (isa<FieldDecl>(D)) return true;
745
746 if (isa<CXXMethodDecl>(D))
747 return !cast<CXXMethodDecl>(D)->isStatic();
748
749 if (isa<FunctionTemplateDecl>(D)) {
750 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
751 return !cast<CXXMethodDecl>(D)->isStatic();
752 }
753
754 return false;
755}
756
757enum IMAKind {
758 /// The reference is definitely not an instance member access.
759 IMA_Static,
760
761 /// The reference may be an implicit instance member access.
762 IMA_Mixed,
763
764 /// The reference may be to an instance member, but it is invalid if
765 /// so, because the context is not an instance method.
766 IMA_Mixed_StaticContext,
767
768 /// The reference may be to an instance member, but it is invalid if
769 /// so, because the context is from an unrelated class.
770 IMA_Mixed_Unrelated,
771
772 /// The reference is definitely an implicit instance member access.
773 IMA_Instance,
774
775 /// The reference may be to an unresolved using declaration.
776 IMA_Unresolved,
777
778 /// The reference may be to an unresolved using declaration and the
779 /// context is not an instance method.
780 IMA_Unresolved_StaticContext,
781
782 /// The reference is to a member of an anonymous structure in a
783 /// non-class context.
784 IMA_AnonymousMember,
785
786 /// All possible referrents are instance members and the current
787 /// context is not an instance method.
788 IMA_Error_StaticContext,
789
790 /// All possible referrents are instance members of an unrelated
791 /// class.
792 IMA_Error_Unrelated
793};
794
795/// The given lookup names class member(s) and is not being used for
796/// an address-of-member expression. Classify the type of access
797/// according to whether it's possible that this reference names an
798/// instance member. This is best-effort; it is okay to
799/// conservatively answer "yes", in which case some errors will simply
800/// not be caught until template-instantiation.
801static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
802 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000803 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000804
805 bool isStaticContext =
806 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
807 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
808
809 if (R.isUnresolvableResult())
810 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
811
812 // Collect all the declaring classes of instance members we find.
813 bool hasNonInstance = false;
814 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
815 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
816 NamedDecl *D = (*I)->getUnderlyingDecl();
817 if (IsInstanceMember(D)) {
818 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
819
820 // If this is a member of an anonymous record, move out to the
821 // innermost non-anonymous struct or union. If there isn't one,
822 // that's a special case.
823 while (R->isAnonymousStructOrUnion()) {
824 R = dyn_cast<CXXRecordDecl>(R->getParent());
825 if (!R) return IMA_AnonymousMember;
826 }
827 Classes.insert(R->getCanonicalDecl());
828 }
829 else
830 hasNonInstance = true;
831 }
832
833 // If we didn't find any instance members, it can't be an implicit
834 // member reference.
835 if (Classes.empty())
836 return IMA_Static;
837
838 // If the current context is not an instance method, it can't be
839 // an implicit member reference.
840 if (isStaticContext)
841 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
842
843 // If we can prove that the current context is unrelated to all the
844 // declaring classes, it can't be an implicit member reference (in
845 // which case it's an error if any of those members are selected).
846 if (IsProvablyNotDerivedFrom(SemaRef,
847 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
848 Classes))
849 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
850
851 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
852}
853
854/// Diagnose a reference to a field with no object available.
855static void DiagnoseInstanceReference(Sema &SemaRef,
856 const CXXScopeSpec &SS,
857 const LookupResult &R) {
858 SourceLocation Loc = R.getNameLoc();
859 SourceRange Range(Loc);
860 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
861
862 if (R.getAsSingle<FieldDecl>()) {
863 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
864 if (MD->isStatic()) {
865 // "invalid use of member 'x' in static member function"
866 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
867 << Range << R.getLookupName();
868 return;
869 }
870 }
871
872 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
873 << R.getLookupName() << Range;
874 return;
875 }
876
877 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000878}
879
John McCall578b69b2009-12-16 08:11:27 +0000880/// Diagnose an empty lookup.
881///
882/// \return false if new lookup candidates were found
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000883bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCall578b69b2009-12-16 08:11:27 +0000884 LookupResult &R) {
885 DeclarationName Name = R.getLookupName();
886
John McCall578b69b2009-12-16 08:11:27 +0000887 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000888 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000889 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
890 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000891 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000892 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000893 diagnostic_suggest = diag::err_undeclared_use_suggest;
894 }
John McCall578b69b2009-12-16 08:11:27 +0000895
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000896 // If the original lookup was an unqualified lookup, fake an
897 // unqualified lookup. This is useful when (for example) the
898 // original lookup would not have found something because it was a
899 // dependent name.
900 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
901 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000902 if (isa<CXXRecordDecl>(DC)) {
903 LookupQualifiedName(R, DC);
904
905 if (!R.empty()) {
906 // Don't give errors about ambiguities in this lookup.
907 R.suppressDiagnostics();
908
909 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
910 bool isInstance = CurMethod &&
911 CurMethod->isInstance() &&
912 DC == CurMethod->getParent();
913
914 // Give a code modification hint to insert 'this->'.
915 // TODO: fixit for inserting 'Base<T>::' in the other cases.
916 // Actually quite difficult!
917 if (isInstance)
918 Diag(R.getNameLoc(), diagnostic) << Name
919 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
920 "this->");
921 else
922 Diag(R.getNameLoc(), diagnostic) << Name;
923
924 // Do we really want to note all of these?
925 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
926 Diag((*I)->getLocation(), diag::note_dependent_var_use);
927
928 // Tell the callee to try to recover.
929 return false;
930 }
931 }
932 }
933
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000934 // We didn't find anything, so try to correct for a typo.
Douglas Gregord203a162010-01-01 00:15:04 +0000935 if (S && CorrectTypo(R, S, &SS)) {
936 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
937 if (SS.isEmpty())
938 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
939 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000940 R.getLookupName().getAsString());
Douglas Gregord203a162010-01-01 00:15:04 +0000941 else
942 Diag(R.getNameLoc(), diag::err_no_member_suggest)
943 << Name << computeDeclContext(SS, false) << R.getLookupName()
944 << SS.getRange()
945 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000946 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000947 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
948 Diag(ND->getLocation(), diag::note_previous_decl)
949 << ND->getDeclName();
950
Douglas Gregord203a162010-01-01 00:15:04 +0000951 // Tell the callee to try to recover.
952 return false;
953 }
954
955 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
956 // FIXME: If we ended up with a typo for a type name or
957 // Objective-C class name, we're in trouble because the parser
958 // is in the wrong place to recover. Suggest the typo
959 // correction, but don't make it a fix-it since we're not going
960 // to recover well anyway.
961 if (SS.isEmpty())
962 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
963 else
964 Diag(R.getNameLoc(), diag::err_no_member_suggest)
965 << Name << computeDeclContext(SS, false) << R.getLookupName()
966 << SS.getRange();
967
968 // Don't try to recover; it won't work.
969 return true;
970 }
971
972 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000973 }
974
975 // Emit a special diagnostic for failed member lookups.
976 // FIXME: computing the declaration context might fail here (?)
977 if (!SS.isEmpty()) {
978 Diag(R.getNameLoc(), diag::err_no_member)
979 << Name << computeDeclContext(SS, false)
980 << SS.getRange();
981 return true;
982 }
983
John McCall578b69b2009-12-16 08:11:27 +0000984 // Give up, we can't recover.
985 Diag(R.getNameLoc(), diagnostic) << Name;
986 return true;
987}
988
John McCallf7a1a742009-11-24 19:00:30 +0000989Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
990 const CXXScopeSpec &SS,
991 UnqualifiedId &Id,
992 bool HasTrailingLParen,
993 bool isAddressOfOperand) {
994 assert(!(isAddressOfOperand && HasTrailingLParen) &&
995 "cannot be direct & operand and have a trailing lparen");
996
997 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000998 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000999
John McCall129e2df2009-11-30 22:42:35 +00001000 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001001
1002 // Decompose the UnqualifiedId into the following data.
1003 DeclarationName Name;
1004 SourceLocation NameLoc;
1005 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +00001006 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1007 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001008
Douglas Gregor10c42622008-11-18 15:03:34 +00001009 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +00001010
John McCallf7a1a742009-11-24 19:00:30 +00001011 // C++ [temp.dep.expr]p3:
1012 // An id-expression is type-dependent if it contains:
1013 // -- a nested-name-specifier that contains a class-name that
1014 // names a dependent type.
1015 // Determine whether this is a member of an unknown specialization;
1016 // we need to handle these differently.
John McCalle1599ce2009-11-30 23:50:49 +00001017 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCallf7a1a742009-11-24 19:00:30 +00001018 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +00001019 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001020 TemplateArgs);
1021 }
John McCallba135432009-11-21 08:51:07 +00001022
John McCallf7a1a742009-11-24 19:00:30 +00001023 // Perform the required lookup.
1024 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1025 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001026 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001027 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001028 } else {
1029 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001030
John McCallf7a1a742009-11-24 19:00:30 +00001031 // If this reference is in an Objective-C method, then we need to do
1032 // some special Objective-C lookup, too.
1033 if (!SS.isSet() && II && getCurMethodDecl()) {
1034 OwningExprResult E(LookupInObjCMethod(R, S, II));
1035 if (E.isInvalid())
1036 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001037
John McCallf7a1a742009-11-24 19:00:30 +00001038 Expr *Ex = E.takeAs<Expr>();
1039 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001040 }
Chris Lattner8a934232008-03-31 00:36:02 +00001041 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001042
John McCallf7a1a742009-11-24 19:00:30 +00001043 if (R.isAmbiguous())
1044 return ExprError();
1045
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001046 // Determine whether this name might be a candidate for
1047 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001048 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001049
John McCallf7a1a742009-11-24 19:00:30 +00001050 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001052 // in C90, extension in C99, forbidden in C++).
1053 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1054 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1055 if (D) R.addDecl(D);
1056 }
1057
1058 // If this name wasn't predeclared and if this is not a function
1059 // call, diagnose the problem.
1060 if (R.empty()) {
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001061 if (DiagnoseEmptyLookup(S, SS, R))
John McCall578b69b2009-12-16 08:11:27 +00001062 return ExprError();
1063
1064 assert(!R.empty() &&
1065 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001066
1067 // If we found an Objective-C instance variable, let
1068 // LookupInObjCMethod build the appropriate expression to
1069 // reference the ivar.
1070 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1071 R.clear();
1072 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1073 assert(E.isInvalid() || E.get());
1074 return move(E);
1075 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 }
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
John McCallf7a1a742009-11-24 19:00:30 +00001079 // This is guaranteed from this point on.
1080 assert(!R.empty() || ADL);
1081
1082 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001083 // Warn about constructs like:
1084 // if (void *X = foo()) { ... } else { X }.
1085 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Douglas Gregor751f9a42009-06-30 15:47:41 +00001087 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1088 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001089 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001090 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001091 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001092 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001093 << Var->getDeclName()
1094 << (Var->getType()->isPointerType()? 2 :
1095 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001096 break;
1097 }
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001099 // Move to the parent of this scope.
1100 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001101 }
1102 }
John McCallf7a1a742009-11-24 19:00:30 +00001103 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001104 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1105 // C99 DR 316 says that, if a function type comes from a
1106 // function definition (without a prototype), that type is only
1107 // used for checking compatibility. Therefore, when referencing
1108 // the function, we pretend that we don't have the full function
1109 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001110 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001111 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001112
Douglas Gregor751f9a42009-06-30 15:47:41 +00001113 QualType T = Func->getType();
1114 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001115 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001116 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001117 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001118 }
1119 }
Mike Stump1eb44332009-09-09 15:08:12 +00001120
John McCallaa81e162009-12-01 22:10:20 +00001121 // Check whether this might be a C++ implicit instance member access.
1122 // C++ [expr.prim.general]p6:
1123 // Within the definition of a non-static member function, an
1124 // identifier that names a non-static member is transformed to a
1125 // class member access expression.
1126 // But note that &SomeClass::foo is grammatically distinct, even
1127 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001128 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001129 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001130 if (!isAbstractMemberPointer)
1131 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001132 }
1133
John McCallf7a1a742009-11-24 19:00:30 +00001134 if (TemplateArgs)
1135 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001136
John McCallf7a1a742009-11-24 19:00:30 +00001137 return BuildDeclarationNameExpr(SS, R, ADL);
1138}
1139
John McCall3b4294e2009-12-16 12:17:52 +00001140/// Builds an expression which might be an implicit member expression.
1141Sema::OwningExprResult
1142Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1143 LookupResult &R,
1144 const TemplateArgumentListInfo *TemplateArgs) {
1145 switch (ClassifyImplicitMemberAccess(*this, R)) {
1146 case IMA_Instance:
1147 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1148
1149 case IMA_AnonymousMember:
1150 assert(R.isSingleResult());
1151 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1152 R.getAsSingle<FieldDecl>());
1153
1154 case IMA_Mixed:
1155 case IMA_Mixed_Unrelated:
1156 case IMA_Unresolved:
1157 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1158
1159 case IMA_Static:
1160 case IMA_Mixed_StaticContext:
1161 case IMA_Unresolved_StaticContext:
1162 if (TemplateArgs)
1163 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1164 return BuildDeclarationNameExpr(SS, R, false);
1165
1166 case IMA_Error_StaticContext:
1167 case IMA_Error_Unrelated:
1168 DiagnoseInstanceReference(*this, SS, R);
1169 return ExprError();
1170 }
1171
1172 llvm_unreachable("unexpected instance member access kind");
1173 return ExprError();
1174}
1175
John McCall129e2df2009-11-30 22:42:35 +00001176/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1177/// declaration name, generally during template instantiation.
1178/// There's a large number of things which don't need to be done along
1179/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001180Sema::OwningExprResult
1181Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1182 DeclarationName Name,
1183 SourceLocation NameLoc) {
1184 DeclContext *DC;
1185 if (!(DC = computeDeclContext(SS, false)) ||
1186 DC->isDependentContext() ||
1187 RequireCompleteDeclContext(SS))
1188 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1189
1190 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1191 LookupQualifiedName(R, DC);
1192
1193 if (R.isAmbiguous())
1194 return ExprError();
1195
1196 if (R.empty()) {
1197 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1198 return ExprError();
1199 }
1200
1201 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1202}
1203
1204/// LookupInObjCMethod - The parser has read a name in, and Sema has
1205/// detected that we're currently inside an ObjC method. Perform some
1206/// additional lookup.
1207///
1208/// Ideally, most of this would be done by lookup, but there's
1209/// actually quite a lot of extra work involved.
1210///
1211/// Returns a null sentinel to indicate trivial success.
1212Sema::OwningExprResult
1213Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1214 IdentifierInfo *II) {
1215 SourceLocation Loc = Lookup.getNameLoc();
1216
1217 // There are two cases to handle here. 1) scoped lookup could have failed,
1218 // in which case we should look for an ivar. 2) scoped lookup could have
1219 // found a decl, but that decl is outside the current instance method (i.e.
1220 // a global variable). In these two cases, we do a lookup for an ivar with
1221 // this name, if the lookup sucedes, we replace it our current decl.
1222
1223 // If we're in a class method, we don't normally want to look for
1224 // ivars. But if we don't find anything else, and there's an
1225 // ivar, that's an error.
1226 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1227
1228 bool LookForIvars;
1229 if (Lookup.empty())
1230 LookForIvars = true;
1231 else if (IsClassMethod)
1232 LookForIvars = false;
1233 else
1234 LookForIvars = (Lookup.isSingleResult() &&
1235 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1236
1237 if (LookForIvars) {
1238 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1239 ObjCInterfaceDecl *ClassDeclared;
1240 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1241 // Diagnose using an ivar in a class method.
1242 if (IsClassMethod)
1243 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1244 << IV->getDeclName());
1245
1246 // If we're referencing an invalid decl, just return this as a silent
1247 // error node. The error diagnostic was already emitted on the decl.
1248 if (IV->isInvalidDecl())
1249 return ExprError();
1250
1251 // Check if referencing a field with __attribute__((deprecated)).
1252 if (DiagnoseUseOfDecl(IV, Loc))
1253 return ExprError();
1254
1255 // Diagnose the use of an ivar outside of the declaring class.
1256 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1257 ClassDeclared != IFace)
1258 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1259
1260 // FIXME: This should use a new expr for a direct reference, don't
1261 // turn this into Self->ivar, just return a BareIVarExpr or something.
1262 IdentifierInfo &II = Context.Idents.get("self");
1263 UnqualifiedId SelfName;
1264 SelfName.setIdentifier(&II, SourceLocation());
1265 CXXScopeSpec SelfScopeSpec;
1266 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1267 SelfName, false, false);
1268 MarkDeclarationReferenced(Loc, IV);
1269 return Owned(new (Context)
1270 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1271 SelfExpr.takeAs<Expr>(), true, true));
1272 }
1273 } else if (getCurMethodDecl()->isInstanceMethod()) {
1274 // We should warn if a local variable hides an ivar.
1275 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1276 ObjCInterfaceDecl *ClassDeclared;
1277 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1278 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1279 IFace == ClassDeclared)
1280 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1281 }
1282 }
1283
1284 // Needed to implement property "super.method" notation.
1285 if (Lookup.empty() && II->isStr("super")) {
1286 QualType T;
1287
1288 if (getCurMethodDecl()->isInstanceMethod())
1289 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1290 getCurMethodDecl()->getClassInterface()));
1291 else
1292 T = Context.getObjCClassType();
1293 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1294 }
1295
1296 // Sentinel value saying that we didn't do anything special.
1297 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001298}
John McCallba135432009-11-21 08:51:07 +00001299
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001300/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001301bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001302Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1303 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001304 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001305 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001306 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001307 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001308 if (DestType->isDependentType() || From->getType()->isDependentType())
1309 return false;
1310 QualType FromRecordType = From->getType();
1311 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001312 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001313 DestType = Context.getPointerType(DestType);
1314 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001315 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001316 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1317 CheckDerivedToBaseConversion(FromRecordType,
1318 DestRecordType,
1319 From->getSourceRange().getBegin(),
1320 From->getSourceRange()))
1321 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001322 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1323 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001324 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001325 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001326}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001327
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001328/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001329static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001330 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001331 SourceLocation Loc, QualType Ty,
1332 const TemplateArgumentListInfo *TemplateArgs = 0) {
1333 NestedNameSpecifier *Qualifier = 0;
1334 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001335 if (SS.isSet()) {
1336 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1337 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
John McCallf7a1a742009-11-24 19:00:30 +00001340 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1341 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001342}
1343
John McCallaa81e162009-12-01 22:10:20 +00001344/// Builds an implicit member access expression. The current context
1345/// is known to be an instance method, and the given unqualified lookup
1346/// set is known to contain only instance members, at least one of which
1347/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001348Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001349Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1350 LookupResult &R,
1351 const TemplateArgumentListInfo *TemplateArgs,
1352 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001353 assert(!R.empty() && !R.isAmbiguous());
1354
John McCallba135432009-11-21 08:51:07 +00001355 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001356
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001357 // We may have found a field within an anonymous union or struct
1358 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001359 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001360 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001361 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001362 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001363 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001364
John McCallaa81e162009-12-01 22:10:20 +00001365 // If this is known to be an instance access, go ahead and build a
1366 // 'this' expression now.
1367 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1368 Expr *This = 0; // null signifies implicit access
1369 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001370 SourceLocation Loc = R.getNameLoc();
1371 if (SS.getRange().isValid())
1372 Loc = SS.getRange().getBegin();
1373 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001374 }
1375
John McCallaa81e162009-12-01 22:10:20 +00001376 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1377 /*OpLoc*/ SourceLocation(),
1378 /*IsArrow*/ true,
1379 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001380}
1381
John McCallf7a1a742009-11-24 19:00:30 +00001382bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001383 const LookupResult &R,
1384 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001385 // Only when used directly as the postfix-expression of a call.
1386 if (!HasTrailingLParen)
1387 return false;
1388
1389 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001390 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001391 return false;
1392
1393 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001394 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001395 return false;
1396
1397 // Turn off ADL when we find certain kinds of declarations during
1398 // normal lookup:
1399 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1400 NamedDecl *D = *I;
1401
1402 // C++0x [basic.lookup.argdep]p3:
1403 // -- a declaration of a class member
1404 // Since using decls preserve this property, we check this on the
1405 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001406 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001407 return false;
1408
1409 // C++0x [basic.lookup.argdep]p3:
1410 // -- a block-scope function declaration that is not a
1411 // using-declaration
1412 // NOTE: we also trigger this for function templates (in fact, we
1413 // don't check the decl type at all, since all other decl types
1414 // turn off ADL anyway).
1415 if (isa<UsingShadowDecl>(D))
1416 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1417 else if (D->getDeclContext()->isFunctionOrMethod())
1418 return false;
1419
1420 // C++0x [basic.lookup.argdep]p3:
1421 // -- a declaration that is neither a function or a function
1422 // template
1423 // And also for builtin functions.
1424 if (isa<FunctionDecl>(D)) {
1425 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1426
1427 // But also builtin functions.
1428 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1429 return false;
1430 } else if (!isa<FunctionTemplateDecl>(D))
1431 return false;
1432 }
1433
1434 return true;
1435}
1436
1437
John McCallba135432009-11-21 08:51:07 +00001438/// Diagnoses obvious problems with the use of the given declaration
1439/// as an expression. This is only actually called for lookups that
1440/// were not overloaded, and it doesn't promise that the declaration
1441/// will in fact be used.
1442static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1443 if (isa<TypedefDecl>(D)) {
1444 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1445 return true;
1446 }
1447
1448 if (isa<ObjCInterfaceDecl>(D)) {
1449 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1450 return true;
1451 }
1452
1453 if (isa<NamespaceDecl>(D)) {
1454 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1455 return true;
1456 }
1457
1458 return false;
1459}
1460
1461Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001462Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001463 LookupResult &R,
1464 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001465 // If this is a single, fully-resolved result and we don't need ADL,
1466 // just build an ordinary singleton decl ref.
1467 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001468 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001469
1470 // We only need to check the declaration if there's exactly one
1471 // result, because in the overloaded case the results can only be
1472 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001473 if (R.isSingleResult() &&
1474 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001475 return ExprError();
1476
John McCallf7a1a742009-11-24 19:00:30 +00001477 bool Dependent
1478 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001479 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001480 = UnresolvedLookupExpr::Create(Context, Dependent,
1481 (NestedNameSpecifier*) SS.getScopeRep(),
1482 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001483 R.getLookupName(), R.getNameLoc(),
1484 NeedsADL, R.isOverloadedResult());
1485 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1486 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001487
1488 return Owned(ULE);
1489}
1490
1491
1492/// \brief Complete semantic analysis for a reference to the given declaration.
1493Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001494Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001495 SourceLocation Loc, NamedDecl *D) {
1496 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001497 assert(!isa<FunctionTemplateDecl>(D) &&
1498 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001499
1500 if (CheckDeclInExpr(*this, Loc, D))
1501 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001502
Douglas Gregor9af2f522009-12-01 16:58:18 +00001503 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1504 // Specifically diagnose references to class templates that are missing
1505 // a template argument list.
1506 Diag(Loc, diag::err_template_decl_ref)
1507 << Template << SS.getRange();
1508 Diag(Template->getLocation(), diag::note_template_decl_here);
1509 return ExprError();
1510 }
1511
1512 // Make sure that we're referring to a value.
1513 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1514 if (!VD) {
1515 Diag(Loc, diag::err_ref_non_value)
1516 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001517 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001518 return ExprError();
1519 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001520
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001521 // Check whether this declaration can be used. Note that we suppress
1522 // this check when we're going to perform argument-dependent lookup
1523 // on this function name, because this might not be the function
1524 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001525 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001526 return ExprError();
1527
Steve Naroffdd972f22008-09-05 22:11:13 +00001528 // Only create DeclRefExpr's for valid Decl's.
1529 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001530 return ExprError();
1531
Chris Lattner639e2d32008-10-20 05:16:36 +00001532 // If the identifier reference is inside a block, and it refers to a value
1533 // that is outside the block, create a BlockDeclRefExpr instead of a
1534 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1535 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001536 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001537 // We do not do this for things like enum constants, global variables, etc,
1538 // as they do not get snapshotted.
1539 //
1540 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001541 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1542 Diag(Loc, diag::err_ref_vm_type);
1543 Diag(D->getLocation(), diag::note_declared_at);
1544 return ExprError();
1545 }
1546
Mike Stump28497342010-01-05 03:10:36 +00001547 if (VD->getType()->isArrayType()) {
1548 Diag(Loc, diag::err_ref_array_type);
1549 Diag(D->getLocation(), diag::note_declared_at);
1550 return ExprError();
1551 }
1552
Douglas Gregore0762c92009-06-19 23:52:42 +00001553 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001554 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001555 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001556 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001557 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001558 // This is to record that a 'const' was actually synthesize and added.
1559 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001560 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Eli Friedman5fdeae12009-03-22 23:00:19 +00001562 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001563 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001564 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001565 }
1566 // If this reference is not in a block or if the referenced variable is
1567 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001568
John McCallf7a1a742009-11-24 19:00:30 +00001569 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570}
1571
Sebastian Redlcd965b92009-01-18 18:53:16 +00001572Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1573 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001574 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001577 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001578 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1579 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1580 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001582
Chris Lattnerfa28b302008-01-12 08:14:25 +00001583 // Pre-defined identifiers are of type char[x], where x is the length of the
1584 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Anders Carlsson3a082d82009-09-08 18:24:21 +00001586 Decl *currentDecl = getCurFunctionOrMethodDecl();
1587 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001588 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001589 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001590 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001591
Anders Carlsson773f3972009-09-11 01:22:35 +00001592 QualType ResTy;
1593 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1594 ResTy = Context.DependentTy;
1595 } else {
1596 unsigned Length =
1597 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001598
Anders Carlsson773f3972009-09-11 01:22:35 +00001599 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001600 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001601 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1602 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001603 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001604}
1605
Sebastian Redlcd965b92009-01-18 18:53:16 +00001606Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 llvm::SmallString<16> CharBuffer;
1608 CharBuffer.resize(Tok.getLength());
1609 const char *ThisTokBegin = &CharBuffer[0];
1610 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001611
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1613 Tok.getLocation(), PP);
1614 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001615 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001616
Chris Lattnere8337df2009-12-30 21:19:39 +00001617 QualType Ty;
1618 if (!getLangOptions().CPlusPlus)
1619 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1620 else if (Literal.isWide())
1621 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1622 else
1623 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001624
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001625 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1626 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001627 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001628}
1629
Sebastian Redlcd965b92009-01-18 18:53:16 +00001630Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1631 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1633 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001634 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001635 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001636 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001637 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 }
Ted Kremenek28396602009-01-13 23:19:12 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001641 // Add padding so that NumericLiteralParser can overread by one character.
1642 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 // Get the spelling of the token, which eliminates trigraphs, etc.
1646 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001647
Mike Stump1eb44332009-09-09 15:08:12 +00001648 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 Tok.getLocation(), PP);
1650 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001651 return ExprError();
1652
Chris Lattner5d661452007-08-26 03:42:43 +00001653 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001654
Chris Lattner5d661452007-08-26 03:42:43 +00001655 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001656 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001657 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001658 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001659 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001660 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001661 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001662 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001663
1664 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1665
John McCall94c939d2009-12-24 09:08:04 +00001666 using llvm::APFloat;
1667 APFloat Val(Format);
1668
1669 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001670
1671 // Overflow is always an error, but underflow is only an error if
1672 // we underflowed to zero (APFloat reports denormals as underflow).
1673 if ((result & APFloat::opOverflow) ||
1674 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001675 unsigned diagnostic;
1676 llvm::SmallVector<char, 20> buffer;
1677 if (result & APFloat::opOverflow) {
1678 diagnostic = diag::err_float_overflow;
1679 APFloat::getLargest(Format).toString(buffer);
1680 } else {
1681 diagnostic = diag::err_float_underflow;
1682 APFloat::getSmallest(Format).toString(buffer);
1683 }
1684
1685 Diag(Tok.getLocation(), diagnostic)
1686 << Ty
1687 << llvm::StringRef(buffer.data(), buffer.size());
1688 }
1689
1690 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001691 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001692
Chris Lattner5d661452007-08-26 03:42:43 +00001693 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001694 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001695 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001696 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001697
Neil Boothb9449512007-08-29 22:00:19 +00001698 // long long is a C99 feature.
1699 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001700 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001701 Diag(Tok.getLocation(), diag::ext_longlong);
1702
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001704 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 if (Literal.GetIntegerValue(ResultVal)) {
1707 // If this value didn't fit into uintmax_t, warn and force to ull.
1708 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001709 Ty = Context.UnsignedLongLongTy;
1710 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001711 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 } else {
1713 // If this value fits into a ULL, try to figure out what else it fits into
1714 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001715
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1717 // be an unsigned int.
1718 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1719
1720 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001721 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001722 if (!Literal.isLong && !Literal.isLongLong) {
1723 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001724 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001725
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 // Does it fit in a unsigned int?
1727 if (ResultVal.isIntN(IntSize)) {
1728 // Does it fit in a signed int?
1729 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001730 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001732 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001733 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001736
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001738 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001739 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001740
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 // Does it fit in a unsigned long?
1742 if (ResultVal.isIntN(LongSize)) {
1743 // Does it fit in a signed long?
1744 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001745 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001747 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001748 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001750 }
1751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001753 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001754 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001755
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 // Does it fit in a unsigned long long?
1757 if (ResultVal.isIntN(LongLongSize)) {
1758 // Does it fit in a signed long long?
1759 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001760 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001762 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001763 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 }
1765 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001766
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 // If we still couldn't decide a type, we probably have something that
1768 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001769 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001771 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001772 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001774
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001775 if (ResultVal.getBitWidth() != Width)
1776 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001778 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001780
Chris Lattner5d661452007-08-26 03:42:43 +00001781 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1782 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001783 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001784 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001785
1786 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787}
1788
Sebastian Redlcd965b92009-01-18 18:53:16 +00001789Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1790 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001791 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001792 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001793 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001794}
1795
1796/// The UsualUnaryConversions() function is *not* called by this routine.
1797/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001798bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001799 SourceLocation OpLoc,
1800 const SourceRange &ExprRange,
1801 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001802 if (exprType->isDependentType())
1803 return false;
1804
Sebastian Redl5d484e82009-11-23 17:18:46 +00001805 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1806 // the result is the size of the referenced type."
1807 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1808 // result shall be the alignment of the referenced type."
1809 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1810 exprType = Ref->getPointeeType();
1811
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001813 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001814 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001815 if (isSizeof)
1816 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1817 return false;
1818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Chris Lattner1efaa952009-04-24 00:30:45 +00001820 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001821 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001822 Diag(OpLoc, diag::ext_sizeof_void_type)
1823 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001824 return false;
1825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Chris Lattner1efaa952009-04-24 00:30:45 +00001827 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00001828 PDiag(diag::err_sizeof_alignof_incomplete_type)
1829 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001830 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Chris Lattner1efaa952009-04-24 00:30:45 +00001832 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001833 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001834 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001835 << exprType << isSizeof << ExprRange;
1836 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001837 }
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Chris Lattner1efaa952009-04-24 00:30:45 +00001839 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001840}
1841
Chris Lattner31e21e02009-01-24 20:17:12 +00001842bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1843 const SourceRange &ExprRange) {
1844 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001845
Mike Stump1eb44332009-09-09 15:08:12 +00001846 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001847 if (isa<DeclRefExpr>(E))
1848 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001849
1850 // Cannot know anything else if the expression is dependent.
1851 if (E->isTypeDependent())
1852 return false;
1853
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001854 if (E->getBitField()) {
1855 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1856 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001857 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001858
1859 // Alignment of a field access is always okay, so long as it isn't a
1860 // bit-field.
1861 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001862 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001863 return false;
1864
Chris Lattner31e21e02009-01-24 20:17:12 +00001865 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1866}
1867
Douglas Gregorba498172009-03-13 21:01:28 +00001868/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001869Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001870Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001871 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001872 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001873 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001874 return ExprError();
1875
John McCalla93c9342009-12-07 02:54:59 +00001876 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001877
Douglas Gregorba498172009-03-13 21:01:28 +00001878 if (!T->isDependentType() &&
1879 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1880 return ExprError();
1881
1882 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001883 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001884 Context.getSizeType(), OpLoc,
1885 R.getEnd()));
1886}
1887
1888/// \brief Build a sizeof or alignof expression given an expression
1889/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001890Action::OwningExprResult
1891Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001892 bool isSizeOf, SourceRange R) {
1893 // Verify that the operand is valid.
1894 bool isInvalid = false;
1895 if (E->isTypeDependent()) {
1896 // Delay type-checking for type-dependent expressions.
1897 } else if (!isSizeOf) {
1898 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001899 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001900 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1901 isInvalid = true;
1902 } else {
1903 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1904 }
1905
1906 if (isInvalid)
1907 return ExprError();
1908
1909 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1910 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1911 Context.getSizeType(), OpLoc,
1912 R.getEnd()));
1913}
1914
Sebastian Redl05189992008-11-11 17:56:53 +00001915/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1916/// the same for @c alignof and @c __alignof
1917/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001918Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001919Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1920 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001922 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001923
Sebastian Redl05189992008-11-11 17:56:53 +00001924 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001925 TypeSourceInfo *TInfo;
1926 (void) GetTypeFromParser(TyOrEx, &TInfo);
1927 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001928 }
Sebastian Redl05189992008-11-11 17:56:53 +00001929
Douglas Gregorba498172009-03-13 21:01:28 +00001930 Expr *ArgEx = (Expr *)TyOrEx;
1931 Action::OwningExprResult Result
1932 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1933
1934 if (Result.isInvalid())
1935 DeleteExpr(ArgEx);
1936
1937 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001938}
1939
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001940QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001941 if (V->isTypeDependent())
1942 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Chris Lattnercc26ed72007-08-26 05:39:26 +00001944 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001945 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001946 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Chris Lattnercc26ed72007-08-26 05:39:26 +00001948 // Otherwise they pass through real integer and floating point types here.
1949 if (V->getType()->isArithmeticType())
1950 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Chris Lattnercc26ed72007-08-26 05:39:26 +00001952 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001953 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1954 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001955 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001956}
1957
1958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959
Sebastian Redl0eb23302009-01-19 00:08:26 +00001960Action::OwningExprResult
1961Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1962 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 UnaryOperator::Opcode Opc;
1964 switch (Kind) {
1965 default: assert(0 && "Unknown unary op!");
1966 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1967 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1968 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001969
Eli Friedmane4216e92009-11-18 03:38:04 +00001970 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001971}
1972
Sebastian Redl0eb23302009-01-19 00:08:26 +00001973Action::OwningExprResult
1974Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1975 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001976 // Since this might be a postfix expression, get rid of ParenListExprs.
1977 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1978
Sebastian Redl0eb23302009-01-19 00:08:26 +00001979 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1980 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregor337c6b92008-11-19 17:17:41 +00001982 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001983 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1984 Base.release();
1985 Idx.release();
1986 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1987 Context.DependentTy, RLoc));
1988 }
1989
Mike Stump1eb44332009-09-09 15:08:12 +00001990 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001991 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001992 LHSExp->getType()->isEnumeralType() ||
1993 RHSExp->getType()->isRecordType() ||
1994 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001995 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001996 }
1997
Sebastian Redlf322ed62009-10-29 20:17:01 +00001998 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1999}
2000
2001
2002Action::OwningExprResult
2003Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2004 ExprArg Idx, SourceLocation RLoc) {
2005 Expr *LHSExp = static_cast<Expr*>(Base.get());
2006 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2007
Chris Lattner12d9ff62007-07-16 00:14:47 +00002008 // Perform default conversions.
2009 DefaultFunctionArrayConversion(LHSExp);
2010 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002011
Chris Lattner12d9ff62007-07-16 00:14:47 +00002012 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002013
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002015 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002016 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002018 Expr *BaseExpr, *IndexExpr;
2019 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002020 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2021 BaseExpr = LHSExp;
2022 IndexExpr = RHSExp;
2023 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002024 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002025 BaseExpr = LHSExp;
2026 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002027 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002028 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002029 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002030 BaseExpr = RHSExp;
2031 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002032 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002033 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002034 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002035 BaseExpr = LHSExp;
2036 IndexExpr = RHSExp;
2037 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002038 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002039 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002040 // Handle the uncommon case of "123[Ptr]".
2041 BaseExpr = RHSExp;
2042 IndexExpr = LHSExp;
2043 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002044 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002045 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002046 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002047
Chris Lattner12d9ff62007-07-16 00:14:47 +00002048 // FIXME: need to deal with const...
2049 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002050 } else if (LHSTy->isArrayType()) {
2051 // If we see an array that wasn't promoted by
2052 // DefaultFunctionArrayConversion, it must be an array that
2053 // wasn't promoted because of the C90 rule that doesn't
2054 // allow promoting non-lvalue arrays. Warn, then
2055 // force the promotion here.
2056 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2057 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002058 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2059 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002060 LHSTy = LHSExp->getType();
2061
2062 BaseExpr = LHSExp;
2063 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002064 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002065 } else if (RHSTy->isArrayType()) {
2066 // Same as previous, except for 123[f().a] case
2067 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2068 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002069 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2070 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002071 RHSTy = RHSExp->getType();
2072
2073 BaseExpr = RHSExp;
2074 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002075 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002077 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2078 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002079 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002081 if (!(IndexExpr->getType()->isIntegerType() &&
2082 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002083 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2084 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002085
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002086 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002087 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2088 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002089 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2090
Douglas Gregore7450f52009-03-24 19:52:54 +00002091 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002092 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2093 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002094 // incomplete types are not object types.
2095 if (ResultType->isFunctionType()) {
2096 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2097 << ResultType << BaseExpr->getSourceRange();
2098 return ExprError();
2099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregore7450f52009-03-24 19:52:54 +00002101 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002102 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002103 PDiag(diag::err_subscript_incomplete_type)
2104 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002105 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Chris Lattner1efaa952009-04-24 00:30:45 +00002107 // Diagnose bad cases where we step over interface counts.
2108 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2109 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2110 << ResultType << BaseExpr->getSourceRange();
2111 return ExprError();
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Sebastian Redl0eb23302009-01-19 00:08:26 +00002114 Base.release();
2115 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002116 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002117 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002118}
2119
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002120QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002121CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002122 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002123 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002124 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2125 // see FIXME there.
2126 //
2127 // FIXME: This logic can be greatly simplified by splitting it along
2128 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002129 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002130
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002131 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002132 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002133
Mike Stumpeed9cac2009-02-19 03:04:26 +00002134 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002135 // special names that indicate a subset of exactly half the elements are
2136 // to be selected.
2137 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002138
Nate Begeman353417a2009-01-18 01:47:54 +00002139 // This flag determines whether or not CompName has an 's' char prefix,
2140 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002141 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002142
2143 // Check that we've found one of the special components, or that the component
2144 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002145 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002146 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2147 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002148 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002149 do
2150 compStr++;
2151 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002152 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002153 do
2154 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002155 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002156 }
Nate Begeman353417a2009-01-18 01:47:54 +00002157
Mike Stumpeed9cac2009-02-19 03:04:26 +00002158 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002159 // We didn't get to the end of the string. This means the component names
2160 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002161 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2162 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002163 return QualType();
2164 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002165
Nate Begeman353417a2009-01-18 01:47:54 +00002166 // Ensure no component accessor exceeds the width of the vector type it
2167 // operates on.
2168 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002169 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002170
2171 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002172 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002173
2174 while (*compStr) {
2175 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2176 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2177 << baseType << SourceRange(CompLoc);
2178 return QualType();
2179 }
2180 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002181 }
Nate Begeman8a997642008-05-09 06:41:27 +00002182
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002183 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002184 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002185 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002186 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002187 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002188 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002189 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002190 if (HexSwizzle)
2191 CompSize--;
2192
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002193 if (CompSize == 1)
2194 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002195
Nate Begeman213541a2008-04-18 23:10:10 +00002196 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002197 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002198 // diagostics look bad. We want extended vector types to appear built-in.
2199 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2200 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2201 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002202 }
2203 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002204}
2205
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002206static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002207 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002208 const Selector &Sel,
2209 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Anders Carlsson8f28f992009-08-26 18:25:21 +00002211 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002212 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002213 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002214 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002216 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2217 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002218 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002219 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002220 return D;
2221 }
2222 return 0;
2223}
2224
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002225static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002226 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002227 const Selector &Sel,
2228 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002229 // Check protocols on qualified interfaces.
2230 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002231 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002232 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002233 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002234 GDecl = PD;
2235 break;
2236 }
2237 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002238 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002239 GDecl = OMD;
2240 break;
2241 }
2242 }
2243 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002244 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002245 E = QIdTy->qual_end(); I != E; ++I) {
2246 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002247 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002248 if (GDecl)
2249 return GDecl;
2250 }
2251 }
2252 return GDecl;
2253}
Chris Lattner76a642f2009-02-15 22:43:40 +00002254
John McCall129e2df2009-11-30 22:42:35 +00002255Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002256Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2257 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002258 const CXXScopeSpec &SS,
2259 NamedDecl *FirstQualifierInScope,
2260 DeclarationName Name, SourceLocation NameLoc,
2261 const TemplateArgumentListInfo *TemplateArgs) {
2262 Expr *BaseExpr = Base.takeAs<Expr>();
2263
2264 // Even in dependent contexts, try to diagnose base expressions with
2265 // obviously wrong types, e.g.:
2266 //
2267 // T* t;
2268 // t.f;
2269 //
2270 // In Obj-C++, however, the above expression is valid, since it could be
2271 // accessing the 'f' property if T is an Obj-C interface. The extra check
2272 // allows this, while still reporting an error if T is a struct pointer.
2273 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002274 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002275 if (PT && (!getLangOptions().ObjC1 ||
2276 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002277 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002278 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002279 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002280 return ExprError();
2281 }
2282 }
2283
John McCallaa81e162009-12-01 22:10:20 +00002284 assert(BaseType->isDependentType());
John McCall129e2df2009-11-30 22:42:35 +00002285
2286 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2287 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002288 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002289 IsArrow, OpLoc,
2290 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2291 SS.getRange(),
2292 FirstQualifierInScope,
2293 Name, NameLoc,
2294 TemplateArgs));
2295}
2296
2297/// We know that the given qualified member reference points only to
2298/// declarations which do not belong to the static type of the base
2299/// expression. Diagnose the problem.
2300static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2301 Expr *BaseExpr,
2302 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002303 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002304 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002305 // If this is an implicit member access, use a different set of
2306 // diagnostics.
2307 if (!BaseExpr)
2308 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002309
2310 // FIXME: this is an exceedingly lame diagnostic for some of the more
2311 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002312 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002313 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002314 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002315}
2316
2317// Check whether the declarations we found through a nested-name
2318// specifier in a member expression are actually members of the base
2319// type. The restriction here is:
2320//
2321// C++ [expr.ref]p2:
2322// ... In these cases, the id-expression shall name a
2323// member of the class or of one of its base classes.
2324//
2325// So it's perfectly legitimate for the nested-name specifier to name
2326// an unrelated class, and for us to find an overload set including
2327// decls from classes which are not superclasses, as long as the decl
2328// we actually pick through overload resolution is from a superclass.
2329bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2330 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002331 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002332 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002333 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2334 if (!BaseRT) {
2335 // We can't check this yet because the base type is still
2336 // dependent.
2337 assert(BaseType->isDependentType());
2338 return false;
2339 }
2340 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002341
2342 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002343 // If this is an implicit member reference and we find a
2344 // non-instance member, it's not an error.
2345 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2346 return false;
John McCall129e2df2009-11-30 22:42:35 +00002347
John McCallaa81e162009-12-01 22:10:20 +00002348 // Note that we use the DC of the decl, not the underlying decl.
2349 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2350 while (RecordD->isAnonymousStructOrUnion())
2351 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2352
2353 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2354 MemberRecord.insert(RecordD->getCanonicalDecl());
2355
2356 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2357 return false;
2358 }
2359
John McCall2f841ba2009-12-02 03:53:29 +00002360 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002361 return true;
2362}
2363
2364static bool
2365LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2366 SourceRange BaseRange, const RecordType *RTy,
2367 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2368 RecordDecl *RDecl = RTy->getDecl();
2369 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2370 PDiag(diag::err_typecheck_incomplete_tag)
2371 << BaseRange))
2372 return true;
2373
2374 DeclContext *DC = RDecl;
2375 if (SS.isSet()) {
2376 // If the member name was a qualified-id, look into the
2377 // nested-name-specifier.
2378 DC = SemaRef.computeDeclContext(SS, false);
2379
John McCall2f841ba2009-12-02 03:53:29 +00002380 if (SemaRef.RequireCompleteDeclContext(SS)) {
2381 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2382 << SS.getRange() << DC;
2383 return true;
2384 }
2385
John McCallaa81e162009-12-01 22:10:20 +00002386 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2387
2388 if (!isa<TypeDecl>(DC)) {
2389 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2390 << DC << SS.getRange();
2391 return true;
John McCall129e2df2009-11-30 22:42:35 +00002392 }
2393 }
2394
John McCallaa81e162009-12-01 22:10:20 +00002395 // The record definition is complete, now look up the member.
2396 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002397
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002398 if (!R.empty())
2399 return false;
2400
2401 // We didn't find anything with the given name, so try to correct
2402 // for typos.
2403 DeclarationName Name = R.getLookupName();
2404 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2405 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2406 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2407 << Name << DC << R.getLookupName() << SS.getRange()
2408 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2409 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002410 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2411 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2412 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002413 return false;
2414 } else {
2415 R.clear();
2416 }
2417
John McCall129e2df2009-11-30 22:42:35 +00002418 return false;
2419}
2420
2421Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002422Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002423 SourceLocation OpLoc, bool IsArrow,
2424 const CXXScopeSpec &SS,
2425 NamedDecl *FirstQualifierInScope,
2426 DeclarationName Name, SourceLocation NameLoc,
2427 const TemplateArgumentListInfo *TemplateArgs) {
2428 Expr *Base = BaseArg.takeAs<Expr>();
2429
John McCall2f841ba2009-12-02 03:53:29 +00002430 if (BaseType->isDependentType() ||
2431 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002432 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002433 IsArrow, OpLoc,
2434 SS, FirstQualifierInScope,
2435 Name, NameLoc,
2436 TemplateArgs);
2437
2438 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002439
John McCallaa81e162009-12-01 22:10:20 +00002440 // Implicit member accesses.
2441 if (!Base) {
2442 QualType RecordTy = BaseType;
2443 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2444 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2445 RecordTy->getAs<RecordType>(),
2446 OpLoc, SS))
2447 return ExprError();
2448
2449 // Explicit member accesses.
2450 } else {
2451 OwningExprResult Result =
2452 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2453 SS, FirstQualifierInScope,
2454 /*ObjCImpDecl*/ DeclPtrTy());
2455
2456 if (Result.isInvalid()) {
2457 Owned(Base);
2458 return ExprError();
2459 }
2460
2461 if (Result.get())
2462 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002463 }
2464
John McCallaa81e162009-12-01 22:10:20 +00002465 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2466 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002467}
2468
2469Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002470Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2471 SourceLocation OpLoc, bool IsArrow,
2472 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002473 LookupResult &R,
2474 const TemplateArgumentListInfo *TemplateArgs) {
2475 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002476 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002477 if (IsArrow) {
2478 assert(BaseType->isPointerType());
2479 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2480 }
2481
2482 NestedNameSpecifier *Qualifier =
2483 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2484 DeclarationName MemberName = R.getLookupName();
2485 SourceLocation MemberLoc = R.getNameLoc();
2486
2487 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002488 return ExprError();
2489
John McCall129e2df2009-11-30 22:42:35 +00002490 if (R.empty()) {
2491 // Rederive where we looked up.
2492 DeclContext *DC = (SS.isSet()
2493 ? computeDeclContext(SS, false)
2494 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002495
John McCall129e2df2009-11-30 22:42:35 +00002496 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002497 << MemberName << DC
2498 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002499 return ExprError();
2500 }
2501
John McCall2f841ba2009-12-02 03:53:29 +00002502 // Diagnose qualified lookups that find only declarations from a
2503 // non-base type. Note that it's okay for lookup to find
2504 // declarations from a non-base type as long as those aren't the
2505 // ones picked by overload resolution.
2506 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002507 return ExprError();
2508
2509 // Construct an unresolved result if we in fact got an unresolved
2510 // result.
2511 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002512 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002513 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002514 R.isUnresolvableResult() ||
2515 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002516
2517 UnresolvedMemberExpr *MemExpr
2518 = UnresolvedMemberExpr::Create(Context, Dependent,
2519 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002520 BaseExpr, BaseExprType,
2521 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002522 Qualifier, SS.getRange(),
2523 MemberName, MemberLoc,
2524 TemplateArgs);
2525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2526 MemExpr->addDecl(*I);
2527
2528 return Owned(MemExpr);
2529 }
2530
2531 assert(R.isSingleResult());
2532 NamedDecl *MemberDecl = R.getFoundDecl();
2533
2534 // FIXME: diagnose the presence of template arguments now.
2535
2536 // If the decl being referenced had an error, return an error for this
2537 // sub-expr without emitting another error, in order to avoid cascading
2538 // error cases.
2539 if (MemberDecl->isInvalidDecl())
2540 return ExprError();
2541
John McCallaa81e162009-12-01 22:10:20 +00002542 // Handle the implicit-member-access case.
2543 if (!BaseExpr) {
2544 // If this is not an instance member, convert to a non-member access.
2545 if (!IsInstanceMember(MemberDecl))
2546 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2547
Douglas Gregor828a1972010-01-07 23:12:05 +00002548 SourceLocation Loc = R.getNameLoc();
2549 if (SS.getRange().isValid())
2550 Loc = SS.getRange().getBegin();
2551 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002552 }
2553
John McCall129e2df2009-11-30 22:42:35 +00002554 bool ShouldCheckUse = true;
2555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2556 // Don't diagnose the use of a virtual member function unless it's
2557 // explicitly qualified.
2558 if (MD->isVirtual() && !SS.isSet())
2559 ShouldCheckUse = false;
2560 }
2561
2562 // Check the use of this member.
2563 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2564 Owned(BaseExpr);
2565 return ExprError();
2566 }
2567
2568 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2569 // We may have found a field within an anonymous union or struct
2570 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002571 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2572 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002573 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2574 BaseExpr, OpLoc);
2575
2576 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2577 QualType MemberType = FD->getType();
2578 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2579 MemberType = Ref->getPointeeType();
2580 else {
2581 Qualifiers BaseQuals = BaseType.getQualifiers();
2582 BaseQuals.removeObjCGCAttr();
2583 if (FD->isMutable()) BaseQuals.removeConst();
2584
2585 Qualifiers MemberQuals
2586 = Context.getCanonicalType(MemberType).getQualifiers();
2587
2588 Qualifiers Combined = BaseQuals + MemberQuals;
2589 if (Combined != MemberQuals)
2590 MemberType = Context.getQualifiedType(MemberType, Combined);
2591 }
2592
2593 MarkDeclarationReferenced(MemberLoc, FD);
2594 if (PerformObjectMemberConversion(BaseExpr, FD))
2595 return ExprError();
2596 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2597 FD, MemberLoc, MemberType));
2598 }
2599
2600 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2601 MarkDeclarationReferenced(MemberLoc, Var);
2602 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2603 Var, MemberLoc,
2604 Var->getType().getNonReferenceType()));
2605 }
2606
2607 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2608 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2609 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2610 MemberFn, MemberLoc,
2611 MemberFn->getType()));
2612 }
2613
2614 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2615 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2616 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2617 Enum, MemberLoc, Enum->getType()));
2618 }
2619
2620 Owned(BaseExpr);
2621
2622 if (isa<TypeDecl>(MemberDecl))
2623 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2624 << MemberName << int(IsArrow));
2625
2626 // We found a declaration kind that we didn't expect. This is a
2627 // generic error message that tells the user that she can't refer
2628 // to this member with '.' or '->'.
2629 return ExprError(Diag(MemberLoc,
2630 diag::err_typecheck_member_reference_unknown)
2631 << MemberName << int(IsArrow));
2632}
2633
2634/// Look up the given member of the given non-type-dependent
2635/// expression. This can return in one of two ways:
2636/// * If it returns a sentinel null-but-valid result, the caller will
2637/// assume that lookup was performed and the results written into
2638/// the provided structure. It will take over from there.
2639/// * Otherwise, the returned expression will be produced in place of
2640/// an ordinary member expression.
2641///
2642/// The ObjCImpDecl bit is a gross hack that will need to be properly
2643/// fixed for ObjC++.
2644Sema::OwningExprResult
2645Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002646 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002647 const CXXScopeSpec &SS,
2648 NamedDecl *FirstQualifierInScope,
2649 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002650 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Steve Naroff3cc4af82007-12-16 21:42:28 +00002652 // Perform default conversions.
2653 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002654
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002655 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002656 assert(!BaseType->isDependentType());
2657
2658 DeclarationName MemberName = R.getLookupName();
2659 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002660
2661 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002662 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002663 // function. Suggest the addition of those parentheses, build the
2664 // call, and continue on.
2665 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2666 if (const FunctionProtoType *Fun
2667 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2668 QualType ResultTy = Fun->getResultType();
2669 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002670 ((!IsArrow && ResultTy->isRecordType()) ||
2671 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002672 ResultTy->getAs<PointerType>()->getPointeeType()
2673 ->isRecordType()))) {
2674 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2675 Diag(Loc, diag::err_member_reference_needs_call)
2676 << QualType(Fun, 0)
2677 << CodeModificationHint::CreateInsertion(Loc, "()");
2678
2679 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002680 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002681 MultiExprArg(*this, 0, 0), 0, Loc);
2682 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002683 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002684
2685 BaseExpr = NewBase.takeAs<Expr>();
2686 DefaultFunctionArrayConversion(BaseExpr);
2687 BaseType = BaseExpr->getType();
2688 }
2689 }
2690 }
2691
David Chisnall0f436562009-08-17 16:35:33 +00002692 // If this is an Objective-C pseudo-builtin and a definition is provided then
2693 // use that.
2694 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002695 if (IsArrow) {
2696 // Handle the following exceptional case PObj->isa.
2697 if (const ObjCObjectPointerType *OPT =
2698 BaseType->getAs<ObjCObjectPointerType>()) {
2699 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2700 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002701 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2702 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002703 }
2704 }
David Chisnall0f436562009-08-17 16:35:33 +00002705 // We have an 'id' type. Rather than fall through, we check if this
2706 // is a reference to 'isa'.
2707 if (BaseType != Context.ObjCIdRedefinitionType) {
2708 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002709 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002710 }
David Chisnall0f436562009-08-17 16:35:33 +00002711 }
John McCall129e2df2009-11-30 22:42:35 +00002712
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002713 // If this is an Objective-C pseudo-builtin and a definition is provided then
2714 // use that.
2715 if (Context.isObjCSelType(BaseType)) {
2716 // We have an 'SEL' type. Rather than fall through, we check if this
2717 // is a reference to 'sel_id'.
2718 if (BaseType != Context.ObjCSelRedefinitionType) {
2719 BaseType = Context.ObjCSelRedefinitionType;
2720 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2721 }
2722 }
John McCall129e2df2009-11-30 22:42:35 +00002723
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002724 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002725
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002726 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002727 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002728 // Also must look for a getter name which uses property syntax.
2729 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2730 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2731 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2732 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2733 ObjCMethodDecl *Getter;
2734 // FIXME: need to also look locally in the implementation.
2735 if ((Getter = IFace->lookupClassMethod(Sel))) {
2736 // Check the use of this method.
2737 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2738 return ExprError();
2739 }
2740 // If we found a getter then this may be a valid dot-reference, we
2741 // will look for the matching setter, in case it is needed.
2742 Selector SetterSel =
2743 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2744 PP.getSelectorTable(), Member);
2745 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2746 if (!Setter) {
2747 // If this reference is in an @implementation, also check for 'private'
2748 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002749 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002750 }
2751 // Look through local category implementations associated with the class.
2752 if (!Setter)
2753 Setter = IFace->getCategoryClassMethod(SetterSel);
2754
2755 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2756 return ExprError();
2757
2758 if (Getter || Setter) {
2759 QualType PType;
2760
2761 if (Getter)
2762 PType = Getter->getResultType();
2763 else
2764 // Get the expression type from Setter's incoming parameter.
2765 PType = (*(Setter->param_end() -1))->getType();
2766 // FIXME: we must check that the setter has property type.
2767 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2768 PType,
2769 Setter, MemberLoc, BaseExpr));
2770 }
2771 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2772 << MemberName << BaseType);
2773 }
2774 }
2775
2776 if (BaseType->isObjCClassType() &&
2777 BaseType != Context.ObjCClassRedefinitionType) {
2778 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002779 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002780 }
Mike Stump1eb44332009-09-09 15:08:12 +00002781
John McCall129e2df2009-11-30 22:42:35 +00002782 if (IsArrow) {
2783 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002784 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002785 else if (BaseType->isObjCObjectPointerType())
2786 ;
John McCall812c1542009-12-07 22:46:59 +00002787 else if (BaseType->isRecordType()) {
2788 // Recover from arrow accesses to records, e.g.:
2789 // struct MyRecord foo;
2790 // foo->bar
2791 // This is actually well-formed in C++ if MyRecord has an
2792 // overloaded operator->, but that should have been dealt with
2793 // by now.
2794 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2795 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2796 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2797 IsArrow = false;
2798 } else {
John McCall129e2df2009-11-30 22:42:35 +00002799 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2800 << BaseType << BaseExpr->getSourceRange();
2801 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002802 }
John McCall812c1542009-12-07 22:46:59 +00002803 } else {
2804 // Recover from dot accesses to pointers, e.g.:
2805 // type *foo;
2806 // foo.bar
2807 // This is actually well-formed in two cases:
2808 // - 'type' is an Objective C type
2809 // - 'bar' is a pseudo-destructor name which happens to refer to
2810 // the appropriate pointer type
2811 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2812 const PointerType *PT = BaseType->getAs<PointerType>();
2813 if (PT && PT->getPointeeType()->isRecordType()) {
2814 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2815 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2816 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2817 BaseType = PT->getPointeeType();
2818 IsArrow = true;
2819 }
2820 }
John McCall129e2df2009-11-30 22:42:35 +00002821 }
John McCall812c1542009-12-07 22:46:59 +00002822
John McCall129e2df2009-11-30 22:42:35 +00002823 // Handle field access to simple records. This also handles access
2824 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002825 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002826 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2827 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002828 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002829 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002830 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002831
Douglas Gregora71d8192009-09-04 17:36:40 +00002832 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2833 // into a record type was handled above, any destructor we see here is a
2834 // pseudo-destructor.
2835 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2836 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002837 // The left hand side of the dot operator shall be of scalar type. The
2838 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002839 // type.
2840 if (!BaseType->isScalarType())
2841 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2842 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Douglas Gregora71d8192009-09-04 17:36:40 +00002844 // [...] The type designated by the pseudo-destructor-name shall be the
2845 // same as the object type.
2846 if (!MemberName.getCXXNameType()->isDependentType() &&
2847 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2848 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2849 << BaseType << MemberName.getCXXNameType()
2850 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002851
2852 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002853 // the form
2854 //
Mike Stump1eb44332009-09-09 15:08:12 +00002855 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2856 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002857 // shall designate the same scalar type.
2858 //
2859 // FIXME: DPG can't see any way to trigger this particular clause, so it
2860 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Douglas Gregora71d8192009-09-04 17:36:40 +00002862 // FIXME: We've lost the precise spelling of the type by going through
2863 // DeclarationName. Can we do better?
2864 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002865 IsArrow, OpLoc,
2866 (NestedNameSpecifier *) SS.getScopeRep(),
2867 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002868 MemberName.getCXXNameType(),
2869 MemberLoc));
2870 }
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Chris Lattnera38e6b12008-07-21 04:59:05 +00002872 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2873 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002874 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2875 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002876 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002877 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002878 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002879 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002880 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2881
Steve Naroffc70e8d92009-07-16 00:25:06 +00002882 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2883 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002884 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002886 if (!IV) {
2887 // Attempt to correct for typos in ivar names.
2888 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2889 LookupMemberName);
2890 if (CorrectTypo(Res, 0, 0, IDecl) &&
2891 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2892 Diag(R.getNameLoc(),
2893 diag::err_typecheck_member_reference_ivar_suggest)
2894 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2895 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2896 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002897 Diag(IV->getLocation(), diag::note_previous_decl)
2898 << IV->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002899 }
2900 }
2901
Steve Naroffc70e8d92009-07-16 00:25:06 +00002902 if (IV) {
2903 // If the decl being referenced had an error, return an error for this
2904 // sub-expr without emitting another error, in order to avoid cascading
2905 // error cases.
2906 if (IV->isInvalidDecl())
2907 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002908
Steve Naroffc70e8d92009-07-16 00:25:06 +00002909 // Check whether we can reference this field.
2910 if (DiagnoseUseOfDecl(IV, MemberLoc))
2911 return ExprError();
2912 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2913 IV->getAccessControl() != ObjCIvarDecl::Package) {
2914 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2915 if (ObjCMethodDecl *MD = getCurMethodDecl())
2916 ClassOfMethodDecl = MD->getClassInterface();
2917 else if (ObjCImpDecl && getCurFunctionDecl()) {
2918 // Case of a c-function declared inside an objc implementation.
2919 // FIXME: For a c-style function nested inside an objc implementation
2920 // class, there is no implementation context available, so we pass
2921 // down the context as argument to this routine. Ideally, this context
2922 // need be passed down in the AST node and somehow calculated from the
2923 // AST for a function decl.
2924 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002925 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002926 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2927 ClassOfMethodDecl = IMPD->getClassInterface();
2928 else if (ObjCCategoryImplDecl* CatImplClass =
2929 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2930 ClassOfMethodDecl = CatImplClass->getClassInterface();
2931 }
Mike Stump1eb44332009-09-09 15:08:12 +00002932
2933 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2934 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002935 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002936 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002937 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002938 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2939 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002940 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002941 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002942 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002943
2944 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2945 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002946 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002947 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002948 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002949 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002950 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002951 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002952 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002953 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002954 if (!IsArrow && (BaseType->isObjCIdType() ||
2955 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002956 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002957 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Steve Naroff14108da2009-07-10 23:34:53 +00002959 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002960 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002961 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2962 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2963 // Check the use of this declaration
2964 if (DiagnoseUseOfDecl(PD, MemberLoc))
2965 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Steve Naroff14108da2009-07-10 23:34:53 +00002967 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2968 MemberLoc, BaseExpr));
2969 }
2970 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2971 // Check the use of this method.
2972 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2973 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Steve Naroff14108da2009-07-10 23:34:53 +00002975 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002976 OMD->getResultType(),
2977 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002978 NULL, 0));
2979 }
2980 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002981
Steve Naroff14108da2009-07-10 23:34:53 +00002982 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002983 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002984 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002985 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2986 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002987 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00002988 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00002989 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2990 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002991 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Daniel Dunbar2307d312008-09-03 01:05:41 +00002993 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002994 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002995 // Check whether we can reference this property.
2996 if (DiagnoseUseOfDecl(PD, MemberLoc))
2997 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002998 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002999 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003000 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00003001 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3002 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003003 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00003004 MemberLoc, BaseExpr));
3005 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003006 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003007 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3008 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003009 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003010 // Check whether we can reference this property.
3011 if (DiagnoseUseOfDecl(PD, MemberLoc))
3012 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00003013
Steve Naroff6ece14c2009-01-21 00:14:39 +00003014 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00003015 MemberLoc, BaseExpr));
3016 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003017 // If that failed, look for an "implicit" property by seeing if the nullary
3018 // selector is implemented.
3019
3020 // FIXME: The logic for looking up nullary and unary selectors should be
3021 // shared with the code in ActOnInstanceMessage.
3022
Anders Carlsson8f28f992009-08-26 18:25:21 +00003023 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003024 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003025
Daniel Dunbar2307d312008-09-03 01:05:41 +00003026 // If this reference is in an @implementation, check for 'private' methods.
3027 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00003028 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003029
Steve Naroff7692ed62008-10-22 19:16:27 +00003030 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003031 if (!Getter)
3032 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003033 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003034 // Check if we can reference this property.
3035 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3036 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00003037 }
3038 // If we found a getter then this may be a valid dot-reference, we
3039 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00003040 Selector SetterSel =
3041 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00003042 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003043 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003044 if (!Setter) {
3045 // If this reference is in an @implementation, also check for 'private'
3046 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003047 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003048 }
3049 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003050 if (!Setter)
3051 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003052
Steve Naroff1ca66942009-03-11 13:48:17 +00003053 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3054 return ExprError();
3055
3056 if (Getter || Setter) {
3057 QualType PType;
3058
3059 if (Getter)
3060 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00003061 else
3062 // Get the expression type from Setter's incoming parameter.
3063 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00003064 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00003065 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00003066 Setter, MemberLoc, BaseExpr));
3067 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003068
3069 // Attempt to correct for typos in property names.
3070 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3071 LookupOrdinaryName);
3072 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3073 Res.getAsSingle<ObjCPropertyDecl>()) {
3074 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3075 << MemberName << BaseType << Res.getLookupName()
3076 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3077 Res.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003078 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3079 Diag(Property->getLocation(), diag::note_previous_decl)
3080 << Property->getDeclName();
3081
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003082 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
3083 FirstQualifierInScope, ObjCImpDecl);
3084 }
3085
Sebastian Redl0eb23302009-01-19 00:08:26 +00003086 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003087 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00003088 }
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Steve Narofff242b1b2009-07-24 17:54:45 +00003090 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003091 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003092 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003093 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003094 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003095 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003096
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003097 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003098 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003099 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003100 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3101 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003102 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003103 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003104 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003105 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003106
Douglas Gregor214f31a2009-03-27 06:00:30 +00003107 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3108 << BaseType << BaseExpr->getSourceRange();
3109
Douglas Gregor214f31a2009-03-27 06:00:30 +00003110 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003111}
3112
John McCall129e2df2009-11-30 22:42:35 +00003113static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3114 SourceLocation NameLoc,
3115 Sema::ExprArg MemExpr) {
3116 Expr *E = (Expr *) MemExpr.get();
3117 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3118 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00003119 << isa<CXXPseudoDestructorExpr>(E)
3120 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3121
John McCall129e2df2009-11-30 22:42:35 +00003122 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3123 move(MemExpr),
3124 /*LPLoc*/ ExpectedLParenLoc,
3125 Sema::MultiExprArg(SemaRef, 0, 0),
3126 /*CommaLocs*/ 0,
3127 /*RPLoc*/ ExpectedLParenLoc);
3128}
3129
3130/// The main callback when the parser finds something like
3131/// expression . [nested-name-specifier] identifier
3132/// expression -> [nested-name-specifier] identifier
3133/// where 'identifier' encompasses a fairly broad spectrum of
3134/// possibilities, including destructor and operator references.
3135///
3136/// \param OpKind either tok::arrow or tok::period
3137/// \param HasTrailingLParen whether the next token is '(', which
3138/// is used to diagnose mis-uses of special members that can
3139/// only be called
3140/// \param ObjCImpDecl the current ObjC @implementation decl;
3141/// this is an ugly hack around the fact that ObjC @implementations
3142/// aren't properly put in the context chain
3143Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3144 SourceLocation OpLoc,
3145 tok::TokenKind OpKind,
3146 const CXXScopeSpec &SS,
3147 UnqualifiedId &Id,
3148 DeclPtrTy ObjCImpDecl,
3149 bool HasTrailingLParen) {
3150 if (SS.isSet() && SS.isInvalid())
3151 return ExprError();
3152
3153 TemplateArgumentListInfo TemplateArgsBuffer;
3154
3155 // Decompose the name into its component parts.
3156 DeclarationName Name;
3157 SourceLocation NameLoc;
3158 const TemplateArgumentListInfo *TemplateArgs;
3159 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3160 Name, NameLoc, TemplateArgs);
3161
3162 bool IsArrow = (OpKind == tok::arrow);
3163
3164 NamedDecl *FirstQualifierInScope
3165 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3166 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3167
3168 // This is a postfix expression, so get rid of ParenListExprs.
3169 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3170
3171 Expr *Base = BaseArg.takeAs<Expr>();
3172 OwningExprResult Result(*this);
3173 if (Base->getType()->isDependentType()) {
John McCallaa81e162009-12-01 22:10:20 +00003174 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003175 IsArrow, OpLoc,
3176 SS, FirstQualifierInScope,
3177 Name, NameLoc,
3178 TemplateArgs);
3179 } else {
3180 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3181 if (TemplateArgs) {
3182 // Re-use the lookup done for the template name.
3183 DecomposeTemplateName(R, Id);
3184 } else {
3185 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3186 SS, FirstQualifierInScope,
3187 ObjCImpDecl);
3188
3189 if (Result.isInvalid()) {
3190 Owned(Base);
3191 return ExprError();
3192 }
3193
3194 if (Result.get()) {
3195 // The only way a reference to a destructor can be used is to
3196 // immediately call it, which falls into this case. If the
3197 // next token is not a '(', produce a diagnostic and build the
3198 // call now.
3199 if (!HasTrailingLParen &&
3200 Id.getKind() == UnqualifiedId::IK_DestructorName)
3201 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3202
3203 return move(Result);
3204 }
3205 }
3206
John McCallaa81e162009-12-01 22:10:20 +00003207 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3208 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003209 }
3210
3211 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003212}
3213
Anders Carlsson56c5e332009-08-25 03:49:14 +00003214Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3215 FunctionDecl *FD,
3216 ParmVarDecl *Param) {
3217 if (Param->hasUnparsedDefaultArg()) {
3218 Diag (CallLoc,
3219 diag::err_use_of_default_argument_to_function_declared_later) <<
3220 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003221 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003222 diag::note_default_argument_declared_here);
3223 } else {
3224 if (Param->hasUninstantiatedDefaultArg()) {
3225 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3226
3227 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003228 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003229
Mike Stump1eb44332009-09-09 15:08:12 +00003230 InstantiatingTemplate Inst(*this, CallLoc, Param,
3231 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003232 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003233
John McCallce3ff2b2009-08-25 22:02:44 +00003234 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003235 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003236 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Douglas Gregor65222e82009-12-23 18:19:08 +00003238 // Check the expression as an initializer for the parameter.
3239 InitializedEntity Entity
3240 = InitializedEntity::InitializeParameter(Param);
3241 InitializationKind Kind
3242 = InitializationKind::CreateCopy(Param->getLocation(),
3243 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3244 Expr *ResultE = Result.takeAs<Expr>();
3245
3246 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3247 Result = InitSeq.Perform(*this, Entity, Kind,
3248 MultiExprArg(*this, (void**)&ResultE, 1));
3249 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003250 return ExprError();
Douglas Gregor65222e82009-12-23 18:19:08 +00003251
3252 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003253 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003254 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003255 }
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Anders Carlsson56c5e332009-08-25 03:49:14 +00003257 // If the default expression creates temporaries, we need to
3258 // push them to the current stack of expression temporaries so they'll
3259 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003260 // FIXME: We should really be rebuilding the default argument with new
3261 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003262 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3263 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003264 }
3265
3266 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003267 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003268}
3269
Douglas Gregor88a35142008-12-22 05:46:06 +00003270/// ConvertArgumentsForCall - Converts the arguments specified in
3271/// Args/NumArgs to the parameter types of the function FDecl with
3272/// function prototype Proto. Call is the call expression itself, and
3273/// Fn is the function expression. For a C++ member function, this
3274/// routine does not attempt to convert the object argument. Returns
3275/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003276bool
3277Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003278 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003279 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003280 Expr **Args, unsigned NumArgs,
3281 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003282 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003283 // assignment, to the types of the corresponding parameter, ...
3284 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003285 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003286
Douglas Gregor88a35142008-12-22 05:46:06 +00003287 // If too few arguments are available (and we don't have default
3288 // arguments for the remaining parameters), don't make the call.
3289 if (NumArgs < NumArgsInProto) {
3290 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3291 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3292 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003293 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003294 }
3295
3296 // If too many are passed and not variadic, error on the extras and drop
3297 // them.
3298 if (NumArgs > NumArgsInProto) {
3299 if (!Proto->isVariadic()) {
3300 Diag(Args[NumArgsInProto]->getLocStart(),
3301 diag::err_typecheck_call_too_many_args)
3302 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3303 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3304 Args[NumArgs-1]->getLocEnd());
3305 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003306 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003307 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003308 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003309 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003310 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003311 VariadicCallType CallType =
3312 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3313 if (Fn->getType()->isBlockPointerType())
3314 CallType = VariadicBlock; // Block
3315 else if (isa<MemberExpr>(Fn))
3316 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003317 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003318 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003319 if (Invalid)
3320 return true;
3321 unsigned TotalNumArgs = AllArgs.size();
3322 for (unsigned i = 0; i < TotalNumArgs; ++i)
3323 Call->setArg(i, AllArgs[i]);
3324
3325 return false;
3326}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003327
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003328bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3329 FunctionDecl *FDecl,
3330 const FunctionProtoType *Proto,
3331 unsigned FirstProtoArg,
3332 Expr **Args, unsigned NumArgs,
3333 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003334 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003335 unsigned NumArgsInProto = Proto->getNumArgs();
3336 unsigned NumArgsToCheck = NumArgs;
3337 bool Invalid = false;
3338 if (NumArgs != NumArgsInProto)
3339 // Use default arguments for missing arguments
3340 NumArgsToCheck = NumArgsInProto;
3341 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003342 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003343 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003344 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003345
Douglas Gregor88a35142008-12-22 05:46:06 +00003346 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003347 if (ArgIx < NumArgs) {
3348 Arg = Args[ArgIx++];
3349
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003350 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3351 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003352 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003353 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003354 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003355
Douglas Gregora188ff22009-12-22 16:09:06 +00003356 // Pass the argument
3357 ParmVarDecl *Param = 0;
3358 if (FDecl && i < FDecl->getNumParams())
3359 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003360
Douglas Gregora188ff22009-12-22 16:09:06 +00003361
3362 InitializedEntity Entity =
3363 Param? InitializedEntity::InitializeParameter(Param)
3364 : InitializedEntity::InitializeParameter(ProtoArgType);
3365 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3366 SourceLocation(),
3367 Owned(Arg));
3368 if (ArgE.isInvalid())
3369 return true;
3370
3371 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003372 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003373 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003374
Mike Stump1eb44332009-09-09 15:08:12 +00003375 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003376 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003377 if (ArgExpr.isInvalid())
3378 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003379
Anders Carlsson56c5e332009-08-25 03:49:14 +00003380 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003381 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003382 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003383 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003384
Douglas Gregor88a35142008-12-22 05:46:06 +00003385 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003386 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003387 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003388 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003389 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003390 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003391 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003392 }
3393 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003394 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003395}
3396
Steve Narofff69936d2007-09-16 03:34:24 +00003397/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003398/// This provides the location of the left/right parens and a list of comma
3399/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003400Action::OwningExprResult
3401Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3402 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003403 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003404 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003405
3406 // Since this might be a postfix expression, get rid of ParenListExprs.
3407 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003409 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003410 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003411 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Douglas Gregor88a35142008-12-22 05:46:06 +00003413 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003414 // If this is a pseudo-destructor expression, build the call immediately.
3415 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3416 if (NumArgs > 0) {
3417 // Pseudo-destructor calls should not have any arguments.
3418 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3419 << CodeModificationHint::CreateRemoval(
3420 SourceRange(Args[0]->getLocStart(),
3421 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Douglas Gregora71d8192009-09-04 17:36:40 +00003423 for (unsigned I = 0; I != NumArgs; ++I)
3424 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Douglas Gregora71d8192009-09-04 17:36:40 +00003426 NumArgs = 0;
3427 }
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Douglas Gregora71d8192009-09-04 17:36:40 +00003429 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3430 RParenLoc));
3431 }
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Douglas Gregor17330012009-02-04 15:01:18 +00003433 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003434 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003435 // FIXME: Will need to cache the results of name lookup (including ADL) in
3436 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003437 bool Dependent = false;
3438 if (Fn->isTypeDependent())
3439 Dependent = true;
3440 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3441 Dependent = true;
3442
3443 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003444 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003445 Context.DependentTy, RParenLoc));
3446
3447 // Determine whether this is a call to an object (C++ [over.call.object]).
3448 if (Fn->getType()->isRecordType())
3449 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3450 CommaLocs, RParenLoc));
3451
John McCall129e2df2009-11-30 22:42:35 +00003452 Expr *NakedFn = Fn->IgnoreParens();
3453
3454 // Determine whether this is a call to an unresolved member function.
3455 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3456 // If lookup was unresolved but not dependent (i.e. didn't find
3457 // an unresolved using declaration), it has to be an overloaded
3458 // function set, which means it must contain either multiple
3459 // declarations (all methods or method templates) or a single
3460 // method template.
3461 assert((MemE->getNumDecls() > 1) ||
3462 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003463 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003464
John McCallaa81e162009-12-01 22:10:20 +00003465 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3466 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003467 }
3468
Douglas Gregorfa047642009-02-04 00:32:51 +00003469 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003470 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003471 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003472 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003473 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3474 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003475 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003476
3477 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003478 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003479 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3480 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003481 if (const FunctionProtoType *FPT =
3482 dyn_cast<FunctionProtoType>(BO->getType())) {
3483 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003484
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003485 ExprOwningPtr<CXXMemberCallExpr>
3486 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3487 NumArgs, ResultTy,
3488 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003489
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003490 if (CheckCallReturnType(FPT->getResultType(),
3491 BO->getRHS()->getSourceRange().getBegin(),
3492 TheCall.get(), 0))
3493 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003494
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003495 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3496 RParenLoc))
3497 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003498
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003499 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3500 }
3501 return ExprError(Diag(Fn->getLocStart(),
3502 diag::err_typecheck_call_not_function)
3503 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003504 }
3505 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003506 }
3507
Douglas Gregorfa047642009-02-04 00:32:51 +00003508 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003509 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003510 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003511
Eli Friedmanefa42f72009-12-26 03:35:45 +00003512 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003513 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3514 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3515 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3516 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003517 }
Chris Lattner04421082008-04-08 04:40:51 +00003518
John McCall3b4294e2009-12-16 12:17:52 +00003519 NamedDecl *NDecl = 0;
3520 if (isa<DeclRefExpr>(NakedFn))
3521 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3522
John McCallaa81e162009-12-01 22:10:20 +00003523 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3524}
3525
John McCall3b4294e2009-12-16 12:17:52 +00003526/// BuildResolvedCallExpr - Build a call to a resolved expression,
3527/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003528/// unary-convert to an expression of function-pointer or
3529/// block-pointer type.
3530///
3531/// \param NDecl the declaration being called, if available
3532Sema::OwningExprResult
3533Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3534 SourceLocation LParenLoc,
3535 Expr **Args, unsigned NumArgs,
3536 SourceLocation RParenLoc) {
3537 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3538
Chris Lattner04421082008-04-08 04:40:51 +00003539 // Promote the function operand.
3540 UsualUnaryConversions(Fn);
3541
Chris Lattner925e60d2007-12-28 05:29:59 +00003542 // Make the call expr early, before semantic checks. This guarantees cleanup
3543 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003544 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3545 Args, NumArgs,
3546 Context.BoolTy,
3547 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003548
Steve Naroffdd972f22008-09-05 22:11:13 +00003549 const FunctionType *FuncT;
3550 if (!Fn->getType()->isBlockPointerType()) {
3551 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3552 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003553 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003554 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003555 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3556 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003557 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003558 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003559 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003560 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003561 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003562 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003563 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3564 << Fn->getType() << Fn->getSourceRange());
3565
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003566 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003567 if (CheckCallReturnType(FuncT->getResultType(),
3568 Fn->getSourceRange().getBegin(), TheCall.get(),
3569 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003570 return ExprError();
3571
Chris Lattner925e60d2007-12-28 05:29:59 +00003572 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003573 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003574
Douglas Gregor72564e72009-02-26 23:50:07 +00003575 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003576 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003577 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003578 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003579 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003580 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003581
Douglas Gregor74734d52009-04-02 15:37:10 +00003582 if (FDecl) {
3583 // Check if we have too few/too many template arguments, based
3584 // on our knowledge of the function definition.
3585 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003586 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003587 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003588 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003589 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3590 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3591 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3592 }
3593 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003594 }
3595
Steve Naroffb291ab62007-08-28 23:30:39 +00003596 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003597 for (unsigned i = 0; i != NumArgs; i++) {
3598 Expr *Arg = Args[i];
3599 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003600 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3601 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003602 PDiag(diag::err_call_incomplete_argument)
3603 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003604 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003605 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003606 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003607 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003608
Douglas Gregor88a35142008-12-22 05:46:06 +00003609 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3610 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003611 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3612 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003613
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003614 // Check for sentinels
3615 if (NDecl)
3616 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Chris Lattner59907c42007-08-10 20:18:51 +00003618 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003619 if (FDecl) {
3620 if (CheckFunctionCall(FDecl, TheCall.get()))
3621 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003623 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003624 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3625 } else if (NDecl) {
3626 if (CheckBlockCall(NDecl, TheCall.get()))
3627 return ExprError();
3628 }
Chris Lattner59907c42007-08-10 20:18:51 +00003629
Anders Carlssonec74c592009-08-16 03:06:32 +00003630 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003631}
3632
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003633Action::OwningExprResult
3634Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3635 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003636 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor99a2e602009-12-16 01:38:02 +00003637
Douglas Gregord6542d82009-12-22 15:35:07 +00003638 QualType literalType = GetTypeFromParser(Ty);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003639
Steve Naroffaff1edd2007-07-19 21:32:11 +00003640 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003641 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003642 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003643
Eli Friedman6223c222008-05-20 05:22:08 +00003644 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003645 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003646 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3647 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003648 } else if (!literalType->isDependentType() &&
3649 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003650 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003651 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003652 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003653 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003654
Douglas Gregor99a2e602009-12-16 01:38:02 +00003655 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003656 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003657 InitializationKind Kind
3658 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3659 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003660 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3661 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3662 MultiExprArg(*this, (void**)&literalExpr, 1),
3663 &literalType);
3664 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003665 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003666 InitExpr.release();
3667 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003668
Chris Lattner371f2582008-12-04 23:50:19 +00003669 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003670 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003671 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003672 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003673 }
Eli Friedman08544622009-12-22 02:35:53 +00003674
3675 Result.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003676
3677 // FIXME: Store the TInfo to preserve type information better.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003678 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003679 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003680}
3681
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003682Action::OwningExprResult
3683Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003684 SourceLocation RBraceLoc) {
3685 unsigned NumInit = initlist.size();
3686 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003687
Steve Naroff08d92e42007-09-15 18:49:24 +00003688 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003689 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003690
Mike Stumpeed9cac2009-02-19 03:04:26 +00003691 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003692 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003693 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003694 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003695}
3696
Anders Carlsson82debc72009-10-18 18:12:03 +00003697static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3698 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003699 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003700 return CastExpr::CK_NoOp;
3701
3702 if (SrcTy->hasPointerRepresentation()) {
3703 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003704 return DestTy->isObjCObjectPointerType() ?
3705 CastExpr::CK_AnyPointerToObjCPointerCast :
3706 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003707 if (DestTy->isIntegerType())
3708 return CastExpr::CK_PointerToIntegral;
3709 }
3710
3711 if (SrcTy->isIntegerType()) {
3712 if (DestTy->isIntegerType())
3713 return CastExpr::CK_IntegralCast;
3714 if (DestTy->hasPointerRepresentation())
3715 return CastExpr::CK_IntegralToPointer;
3716 if (DestTy->isRealFloatingType())
3717 return CastExpr::CK_IntegralToFloating;
3718 }
3719
3720 if (SrcTy->isRealFloatingType()) {
3721 if (DestTy->isRealFloatingType())
3722 return CastExpr::CK_FloatingCast;
3723 if (DestTy->isIntegerType())
3724 return CastExpr::CK_FloatingToIntegral;
3725 }
3726
3727 // FIXME: Assert here.
3728 // assert(false && "Unhandled cast combination!");
3729 return CastExpr::CK_Unknown;
3730}
3731
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003732/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003733bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003734 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003735 CXXMethodDecl *& ConversionDecl,
3736 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003737 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003738 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3739 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003740
Eli Friedman199ea952009-08-15 19:02:19 +00003741 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003742
3743 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3744 // type needs to be scalar.
3745 if (castType->isVoidType()) {
3746 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003747 Kind = CastExpr::CK_ToVoid;
3748 return false;
3749 }
3750
3751 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003752 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003753 (castType->isStructureType() || castType->isUnionType())) {
3754 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003755 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003756 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3757 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003758 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003759 return false;
3760 }
3761
3762 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003763 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003764 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003765 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003766 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003767 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003768 if (Context.hasSameUnqualifiedType(Field->getType(),
3769 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003770 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3771 << castExpr->getSourceRange();
3772 break;
3773 }
3774 }
3775 if (Field == FieldEnd)
3776 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3777 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003778 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003779 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003780 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003781
3782 // Reject any other conversions to non-scalar types.
3783 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3784 << castType << castExpr->getSourceRange();
3785 }
3786
3787 if (!castExpr->getType()->isScalarType() &&
3788 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003789 return Diag(castExpr->getLocStart(),
3790 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003791 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003792 }
3793
Anders Carlsson16a89042009-10-16 05:23:41 +00003794 if (castType->isExtVectorType())
3795 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3796
Anders Carlssonc3516322009-10-16 02:48:28 +00003797 if (castType->isVectorType())
3798 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3799 if (castExpr->getType()->isVectorType())
3800 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3801
3802 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003803 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003804
Anders Carlsson16a89042009-10-16 05:23:41 +00003805 if (isa<ObjCSelectorExpr>(castExpr))
3806 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3807
Anders Carlssonc3516322009-10-16 02:48:28 +00003808 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003809 QualType castExprType = castExpr->getType();
3810 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3811 return Diag(castExpr->getLocStart(),
3812 diag::err_cast_pointer_from_non_pointer_int)
3813 << castExprType << castExpr->getSourceRange();
3814 } else if (!castExpr->getType()->isArithmeticType()) {
3815 if (!castType->isIntegralType() && castType->isArithmeticType())
3816 return Diag(castExpr->getLocStart(),
3817 diag::err_cast_pointer_to_non_pointer_int)
3818 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003819 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003820
3821 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003822 return false;
3823}
3824
Anders Carlssonc3516322009-10-16 02:48:28 +00003825bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3826 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003827 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003828
Anders Carlssona64db8f2007-11-27 05:51:55 +00003829 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003830 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003831 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003832 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003833 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003834 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003835 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003836 } else
3837 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003838 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003839 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003840
Anders Carlssonc3516322009-10-16 02:48:28 +00003841 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003842 return false;
3843}
3844
Anders Carlsson16a89042009-10-16 05:23:41 +00003845bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3846 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003847 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003848
3849 QualType SrcTy = CastExpr->getType();
3850
Nate Begeman9b10da62009-06-27 22:05:55 +00003851 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3852 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003853 if (SrcTy->isVectorType()) {
3854 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3855 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3856 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003857 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003858 return false;
3859 }
3860
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003861 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003862 // conversion will take place first from scalar to elt type, and then
3863 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003864 if (SrcTy->isPointerType())
3865 return Diag(R.getBegin(),
3866 diag::err_invalid_conversion_between_vector_and_scalar)
3867 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003868
3869 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3870 ImpCastExprToType(CastExpr, DestElemTy,
3871 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003872
3873 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003874 return false;
3875}
3876
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003877Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003878Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003879 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003880 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003882 assert((Ty != 0) && (Op.get() != 0) &&
3883 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003884
Nate Begeman2ef13e52009-08-10 23:49:36 +00003885 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003886 //FIXME: Preserve type source info.
3887 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Nate Begeman2ef13e52009-08-10 23:49:36 +00003889 // If the Expr being casted is a ParenListExpr, handle it specially.
3890 if (isa<ParenListExpr>(castExpr))
3891 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003892 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003893 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003894 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003895 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003896
3897 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003898 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003899 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003900
Anders Carlsson0aebc812009-09-09 21:33:21 +00003901 if (CastArg.isInvalid())
3902 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003903
Anders Carlsson0aebc812009-09-09 21:33:21 +00003904 castExpr = CastArg.takeAs<Expr>();
3905 } else {
3906 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003907 }
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003909 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003910 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003911 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003912}
3913
Nate Begeman2ef13e52009-08-10 23:49:36 +00003914/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3915/// of comma binary operators.
3916Action::OwningExprResult
3917Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3918 Expr *expr = EA.takeAs<Expr>();
3919 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3920 if (!E)
3921 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003922
Nate Begeman2ef13e52009-08-10 23:49:36 +00003923 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003924
Nate Begeman2ef13e52009-08-10 23:49:36 +00003925 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3926 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3927 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Nate Begeman2ef13e52009-08-10 23:49:36 +00003929 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3930}
3931
3932Action::OwningExprResult
3933Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3934 SourceLocation RParenLoc, ExprArg Op,
3935 QualType Ty) {
3936 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003937
3938 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003939 // then handle it as such.
3940 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3941 if (PE->getNumExprs() == 0) {
3942 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3943 return ExprError();
3944 }
3945
3946 llvm::SmallVector<Expr *, 8> initExprs;
3947 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3948 initExprs.push_back(PE->getExpr(i));
3949
3950 // FIXME: This means that pretty-printing the final AST will produce curly
3951 // braces instead of the original commas.
3952 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003953 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003954 initExprs.size(), RParenLoc);
3955 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003956 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003957 Owned(E));
3958 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003959 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003960 // sequence of BinOp comma operators.
3961 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3962 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3963 }
3964}
3965
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003966Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003967 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003968 MultiExprArg Val,
3969 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003970 unsigned nexprs = Val.size();
3971 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003972 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3973 Expr *expr;
3974 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3975 expr = new (Context) ParenExpr(L, R, exprs[0]);
3976 else
3977 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003978 return Owned(expr);
3979}
3980
Sebastian Redl28507842009-02-26 14:39:58 +00003981/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3982/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003983/// C99 6.5.15
3984QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3985 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003986 // C++ is sufficiently different to merit its own checker.
3987 if (getLangOptions().CPlusPlus)
3988 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3989
John McCallb13c87f2009-11-05 09:23:39 +00003990 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3991
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003992 UsualUnaryConversions(Cond);
3993 UsualUnaryConversions(LHS);
3994 UsualUnaryConversions(RHS);
3995 QualType CondTy = Cond->getType();
3996 QualType LHSTy = LHS->getType();
3997 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003998
Reid Spencer5f016e22007-07-11 17:01:13 +00003999 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004000 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4001 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4002 << CondTy;
4003 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004004 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004005
Chris Lattner70d67a92008-01-06 22:42:25 +00004006 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004007 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4008 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004009
Chris Lattner70d67a92008-01-06 22:42:25 +00004010 // If both operands have arithmetic type, do the usual arithmetic conversions
4011 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004012 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4013 UsualArithmeticConversions(LHS, RHS);
4014 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004015 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004016
Chris Lattner70d67a92008-01-06 22:42:25 +00004017 // If both operands are the same structure or union type, the result is that
4018 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004019 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4020 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004021 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004022 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004023 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004024 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004025 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004026 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004027
Chris Lattner70d67a92008-01-06 22:42:25 +00004028 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004029 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004030 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4031 if (!LHSTy->isVoidType())
4032 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4033 << RHS->getSourceRange();
4034 if (!RHSTy->isVoidType())
4035 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4036 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004037 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4038 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004039 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004040 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004041 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4042 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004043 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004044 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004045 // promote the null to a pointer.
4046 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004047 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004048 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004049 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004050 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004051 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004052 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004053 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004054
4055 // All objective-c pointer type analysis is done here.
4056 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4057 QuestionLoc);
4058 if (!compositeType.isNull())
4059 return compositeType;
4060
4061
Steve Naroff7154a772009-07-01 14:36:47 +00004062 // Handle block pointer types.
4063 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4064 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4065 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4066 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004067 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4068 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004069 return destType;
4070 }
4071 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004072 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004073 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004074 }
Steve Naroff7154a772009-07-01 14:36:47 +00004075 // We have 2 block pointer types.
4076 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4077 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004078 return LHSTy;
4079 }
Steve Naroff7154a772009-07-01 14:36:47 +00004080 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004081 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4082 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004083
Steve Naroff7154a772009-07-01 14:36:47 +00004084 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4085 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004086 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004087 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004088 // In this situation, we assume void* type. No especially good
4089 // reason, but this is what gcc does, and we do have to pick
4090 // to get a consistent AST.
4091 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004092 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4093 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004094 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004095 }
Steve Naroff7154a772009-07-01 14:36:47 +00004096 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004097 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4098 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004099 return LHSTy;
4100 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004101
Steve Naroff7154a772009-07-01 14:36:47 +00004102 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4103 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4104 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004105 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4106 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004107
4108 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4109 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4110 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004111 QualType destPointee
4112 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004113 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004114 // Add qualifiers if necessary.
4115 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4116 // Promote to void*.
4117 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004118 return destType;
4119 }
4120 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004121 QualType destPointee
4122 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004123 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004124 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004125 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004126 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004127 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004128 return destType;
4129 }
4130
4131 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4132 // Two identical pointer types are always compatible.
4133 return LHSTy;
4134 }
4135 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4136 rhptee.getUnqualifiedType())) {
4137 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4138 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4139 // In this situation, we assume void* type. No especially good
4140 // reason, but this is what gcc does, and we do have to pick
4141 // to get a consistent AST.
4142 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004143 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4144 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004145 return incompatTy;
4146 }
4147 // The pointer types are compatible.
4148 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4149 // differently qualified versions of compatible types, the result type is
4150 // a pointer to an appropriately qualified version of the *composite*
4151 // type.
4152 // FIXME: Need to calculate the composite type.
4153 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004154 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4155 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004156 return LHSTy;
4157 }
Mike Stump1eb44332009-09-09 15:08:12 +00004158
Steve Naroff7154a772009-07-01 14:36:47 +00004159 // GCC compatibility: soften pointer/integer mismatch.
4160 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4161 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4162 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004163 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004164 return RHSTy;
4165 }
4166 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4167 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4168 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004169 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004170 return LHSTy;
4171 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004172
Chris Lattner70d67a92008-01-06 22:42:25 +00004173 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004174 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4175 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004176 return QualType();
4177}
4178
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004179/// FindCompositeObjCPointerType - Helper method to find composite type of
4180/// two objective-c pointer types of the two input expressions.
4181QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4182 SourceLocation QuestionLoc) {
4183 QualType LHSTy = LHS->getType();
4184 QualType RHSTy = RHS->getType();
4185
4186 // Handle things like Class and struct objc_class*. Here we case the result
4187 // to the pseudo-builtin, because that will be implicitly cast back to the
4188 // redefinition type if an attempt is made to access its fields.
4189 if (LHSTy->isObjCClassType() &&
4190 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4191 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4192 return LHSTy;
4193 }
4194 if (RHSTy->isObjCClassType() &&
4195 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4196 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4197 return RHSTy;
4198 }
4199 // And the same for struct objc_object* / id
4200 if (LHSTy->isObjCIdType() &&
4201 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4202 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4203 return LHSTy;
4204 }
4205 if (RHSTy->isObjCIdType() &&
4206 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4207 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4208 return RHSTy;
4209 }
4210 // And the same for struct objc_selector* / SEL
4211 if (Context.isObjCSelType(LHSTy) &&
4212 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4213 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4214 return LHSTy;
4215 }
4216 if (Context.isObjCSelType(RHSTy) &&
4217 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4218 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4219 return RHSTy;
4220 }
4221 // Check constraints for Objective-C object pointers types.
4222 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4223
4224 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4225 // Two identical object pointer types are always compatible.
4226 return LHSTy;
4227 }
4228 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4229 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4230 QualType compositeType = LHSTy;
4231
4232 // If both operands are interfaces and either operand can be
4233 // assigned to the other, use that type as the composite
4234 // type. This allows
4235 // xxx ? (A*) a : (B*) b
4236 // where B is a subclass of A.
4237 //
4238 // Additionally, as for assignment, if either type is 'id'
4239 // allow silent coercion. Finally, if the types are
4240 // incompatible then make sure to use 'id' as the composite
4241 // type so the result is acceptable for sending messages to.
4242
4243 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4244 // It could return the composite type.
4245 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4246 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4247 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4248 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4249 } else if ((LHSTy->isObjCQualifiedIdType() ||
4250 RHSTy->isObjCQualifiedIdType()) &&
4251 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4252 // Need to handle "id<xx>" explicitly.
4253 // GCC allows qualified id and any Objective-C type to devolve to
4254 // id. Currently localizing to here until clear this should be
4255 // part of ObjCQualifiedIdTypesAreCompatible.
4256 compositeType = Context.getObjCIdType();
4257 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4258 compositeType = Context.getObjCIdType();
4259 } else if (!(compositeType =
4260 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4261 ;
4262 else {
4263 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4264 << LHSTy << RHSTy
4265 << LHS->getSourceRange() << RHS->getSourceRange();
4266 QualType incompatTy = Context.getObjCIdType();
4267 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4268 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4269 return incompatTy;
4270 }
4271 // The object pointer types are compatible.
4272 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4273 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4274 return compositeType;
4275 }
4276 // Check Objective-C object pointer types and 'void *'
4277 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4278 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4279 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4280 QualType destPointee
4281 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4282 QualType destType = Context.getPointerType(destPointee);
4283 // Add qualifiers if necessary.
4284 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4285 // Promote to void*.
4286 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4287 return destType;
4288 }
4289 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4290 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4291 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4292 QualType destPointee
4293 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4294 QualType destType = Context.getPointerType(destPointee);
4295 // Add qualifiers if necessary.
4296 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4297 // Promote to void*.
4298 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4299 return destType;
4300 }
4301 return QualType();
4302}
4303
Steve Narofff69936d2007-09-16 03:34:24 +00004304/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004305/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004306Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4307 SourceLocation ColonLoc,
4308 ExprArg Cond, ExprArg LHS,
4309 ExprArg RHS) {
4310 Expr *CondExpr = (Expr *) Cond.get();
4311 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004312
4313 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4314 // was the condition.
4315 bool isLHSNull = LHSExpr == 0;
4316 if (isLHSNull)
4317 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004318
4319 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004320 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004321 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004322 return ExprError();
4323
4324 Cond.release();
4325 LHS.release();
4326 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004327 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004328 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004329 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004330}
4331
Reid Spencer5f016e22007-07-11 17:01:13 +00004332// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004333// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004334// routine is it effectively iqnores the qualifiers on the top level pointee.
4335// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4336// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004337Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004338Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4339 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004340
David Chisnall0f436562009-08-17 16:35:33 +00004341 if ((lhsType->isObjCClassType() &&
4342 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4343 (rhsType->isObjCClassType() &&
4344 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4345 return Compatible;
4346 }
4347
Reid Spencer5f016e22007-07-11 17:01:13 +00004348 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004349 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4350 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004351
Reid Spencer5f016e22007-07-11 17:01:13 +00004352 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004353 lhptee = Context.getCanonicalType(lhptee);
4354 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004355
Chris Lattner5cf216b2008-01-04 18:04:52 +00004356 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004357
4358 // C99 6.5.16.1p1: This following citation is common to constraints
4359 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4360 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004361 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004362 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004363 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004364
Mike Stumpeed9cac2009-02-19 03:04:26 +00004365 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4366 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004367 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004368 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004369 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004370 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004371
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004372 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004373 assert(rhptee->isFunctionType());
4374 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004375 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004376
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004377 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004378 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004379 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004380
4381 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004382 assert(lhptee->isFunctionType());
4383 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004384 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004385 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004386 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004387 lhptee = lhptee.getUnqualifiedType();
4388 rhptee = rhptee.getUnqualifiedType();
4389 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4390 // Check if the pointee types are compatible ignoring the sign.
4391 // We explicitly check for char so that we catch "char" vs
4392 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004393 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004394 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004395 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004396 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004397
4398 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004399 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004400 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004401 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004402
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004403 if (lhptee == rhptee) {
4404 // Types are compatible ignoring the sign. Qualifier incompatibility
4405 // takes priority over sign incompatibility because the sign
4406 // warning can be disabled.
4407 if (ConvTy != Compatible)
4408 return ConvTy;
4409 return IncompatiblePointerSign;
4410 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004411
4412 // If we are a multi-level pointer, it's possible that our issue is simply
4413 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4414 // the eventual target type is the same and the pointers have the same
4415 // level of indirection, this must be the issue.
4416 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4417 do {
4418 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4419 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4420
4421 lhptee = Context.getCanonicalType(lhptee);
4422 rhptee = Context.getCanonicalType(rhptee);
4423 } while (lhptee->isPointerType() && rhptee->isPointerType());
4424
Douglas Gregora4923eb2009-11-16 21:35:15 +00004425 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004426 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004427 }
4428
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004429 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004430 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004431 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004432 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004433}
4434
Steve Naroff1c7d0672008-09-04 15:10:53 +00004435/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4436/// block pointer types are compatible or whether a block and normal pointer
4437/// are compatible. It is more restrict than comparing two function pointer
4438// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004439Sema::AssignConvertType
4440Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004441 QualType rhsType) {
4442 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004443
Steve Naroff1c7d0672008-09-04 15:10:53 +00004444 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004445 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4446 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004447
Steve Naroff1c7d0672008-09-04 15:10:53 +00004448 // make sure we operate on the canonical type
4449 lhptee = Context.getCanonicalType(lhptee);
4450 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004451
Steve Naroff1c7d0672008-09-04 15:10:53 +00004452 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004453
Steve Naroff1c7d0672008-09-04 15:10:53 +00004454 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004455 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004456 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004457
Eli Friedman26784c12009-06-08 05:08:54 +00004458 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004459 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004460 return ConvTy;
4461}
4462
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004463/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4464/// for assignment compatibility.
4465Sema::AssignConvertType
4466Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4467 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4468 return Compatible;
4469 QualType lhptee =
4470 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4471 QualType rhptee =
4472 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4473 // make sure we operate on the canonical type
4474 lhptee = Context.getCanonicalType(lhptee);
4475 rhptee = Context.getCanonicalType(rhptee);
4476 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4477 return CompatiblePointerDiscardsQualifiers;
4478
4479 if (Context.typesAreCompatible(lhsType, rhsType))
4480 return Compatible;
4481 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4482 return IncompatibleObjCQualifiedId;
4483 return IncompatiblePointer;
4484}
4485
Mike Stumpeed9cac2009-02-19 03:04:26 +00004486/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4487/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004488/// pointers. Here are some objectionable examples that GCC considers warnings:
4489///
4490/// int a, *pint;
4491/// short *pshort;
4492/// struct foo *pfoo;
4493///
4494/// pint = pshort; // warning: assignment from incompatible pointer type
4495/// a = pint; // warning: assignment makes integer from pointer without a cast
4496/// pint = a; // warning: assignment makes pointer from integer without a cast
4497/// pint = pfoo; // warning: assignment from incompatible pointer type
4498///
4499/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004500/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004501///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004502Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004503Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004504 // Get canonical types. We're not formatting these types, just comparing
4505 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004506 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4507 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004508
4509 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004510 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004511
David Chisnall0f436562009-08-17 16:35:33 +00004512 if ((lhsType->isObjCClassType() &&
4513 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4514 (rhsType->isObjCClassType() &&
4515 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4516 return Compatible;
4517 }
4518
Douglas Gregor9d293df2008-10-28 00:22:11 +00004519 // If the left-hand side is a reference type, then we are in a
4520 // (rare!) case where we've allowed the use of references in C,
4521 // e.g., as a parameter type in a built-in function. In this case,
4522 // just make sure that the type referenced is compatible with the
4523 // right-hand side type. The caller is responsible for adjusting
4524 // lhsType so that the resulting expression does not have reference
4525 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004526 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004527 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004528 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004529 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004530 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004531 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4532 // to the same ExtVector type.
4533 if (lhsType->isExtVectorType()) {
4534 if (rhsType->isExtVectorType())
4535 return lhsType == rhsType ? Compatible : Incompatible;
4536 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4537 return Compatible;
4538 }
Mike Stump1eb44332009-09-09 15:08:12 +00004539
Nate Begemanbe2341d2008-07-14 18:02:46 +00004540 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004541 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004542 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004543 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004544 if (getLangOptions().LaxVectorConversions &&
4545 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004546 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004547 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004548 }
4549 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004550 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004551
Chris Lattnere8b3e962008-01-04 23:32:24 +00004552 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004553 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004554
Chris Lattner78eca282008-04-07 06:49:41 +00004555 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004556 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004557 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004558
Chris Lattner78eca282008-04-07 06:49:41 +00004559 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004560 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004561
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004562 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004563 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004564 if (lhsType->isVoidPointerType()) // an exception to the rule.
4565 return Compatible;
4566 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004567 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004568 if (rhsType->getAs<BlockPointerType>()) {
4569 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004570 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004571
4572 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004573 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004574 return Compatible;
4575 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004576 return Incompatible;
4577 }
4578
4579 if (isa<BlockPointerType>(lhsType)) {
4580 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004581 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004582
Steve Naroffb4406862008-09-29 18:10:17 +00004583 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004584 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004585 return Compatible;
4586
Steve Naroff1c7d0672008-09-04 15:10:53 +00004587 if (rhsType->isBlockPointerType())
4588 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004589
Ted Kremenek6217b802009-07-29 21:53:49 +00004590 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004591 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004592 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004593 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004594 return Incompatible;
4595 }
4596
Steve Naroff14108da2009-07-10 23:34:53 +00004597 if (isa<ObjCObjectPointerType>(lhsType)) {
4598 if (rhsType->isIntegerType())
4599 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004600
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004601 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004602 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004603 if (rhsType->isVoidPointerType()) // an exception to the rule.
4604 return Compatible;
4605 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004606 }
4607 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004608 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004609 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004610 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004611 if (RHSPT->getPointeeType()->isVoidType())
4612 return Compatible;
4613 }
4614 // Treat block pointers as objects.
4615 if (rhsType->isBlockPointerType())
4616 return Compatible;
4617 return Incompatible;
4618 }
Chris Lattner78eca282008-04-07 06:49:41 +00004619 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004620 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004621 if (lhsType == Context.BoolTy)
4622 return Compatible;
4623
4624 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004625 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004626
Mike Stumpeed9cac2009-02-19 03:04:26 +00004627 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004628 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004629
4630 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004631 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004632 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004633 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004634 }
Steve Naroff14108da2009-07-10 23:34:53 +00004635 if (isa<ObjCObjectPointerType>(rhsType)) {
4636 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4637 if (lhsType == Context.BoolTy)
4638 return Compatible;
4639
4640 if (lhsType->isIntegerType())
4641 return PointerToInt;
4642
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004643 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004644 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004645 if (lhsType->isVoidPointerType()) // an exception to the rule.
4646 return Compatible;
4647 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004648 }
4649 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004650 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004651 return Compatible;
4652 return Incompatible;
4653 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004654
Chris Lattnerfc144e22008-01-04 23:18:45 +00004655 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004656 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004657 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004658 }
4659 return Incompatible;
4660}
4661
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004662/// \brief Constructs a transparent union from an expression that is
4663/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004664static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004665 QualType UnionType, FieldDecl *Field) {
4666 // Build an initializer list that designates the appropriate member
4667 // of the transparent union.
4668 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4669 &E, 1,
4670 SourceLocation());
4671 Initializer->setType(UnionType);
4672 Initializer->setInitializedFieldInUnion(Field);
4673
4674 // Build a compound literal constructing a value of the transparent
4675 // union type from this initializer list.
4676 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4677 false);
4678}
4679
4680Sema::AssignConvertType
4681Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4682 QualType FromType = rExpr->getType();
4683
Mike Stump1eb44332009-09-09 15:08:12 +00004684 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004685 // transparent_union GCC extension.
4686 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004687 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004688 return Incompatible;
4689
4690 // The field to initialize within the transparent union.
4691 RecordDecl *UD = UT->getDecl();
4692 FieldDecl *InitField = 0;
4693 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004694 for (RecordDecl::field_iterator it = UD->field_begin(),
4695 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004696 it != itend; ++it) {
4697 if (it->getType()->isPointerType()) {
4698 // If the transparent union contains a pointer type, we allow:
4699 // 1) void pointer
4700 // 2) null pointer constant
4701 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004702 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004703 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004704 InitField = *it;
4705 break;
4706 }
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Douglas Gregorce940492009-09-25 04:25:58 +00004708 if (rExpr->isNullPointerConstant(Context,
4709 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004710 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004711 InitField = *it;
4712 break;
4713 }
4714 }
4715
4716 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4717 == Compatible) {
4718 InitField = *it;
4719 break;
4720 }
4721 }
4722
4723 if (!InitField)
4724 return Incompatible;
4725
4726 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4727 return Compatible;
4728}
4729
Chris Lattner5cf216b2008-01-04 18:04:52 +00004730Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004731Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004732 if (getLangOptions().CPlusPlus) {
4733 if (!lhsType->isRecordType()) {
4734 // C++ 5.17p3: If the left operand is not of class type, the
4735 // expression is implicitly converted (C++ 4) to the
4736 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004737 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004738 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004739 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004740 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004741 }
4742
4743 // FIXME: Currently, we fall through and treat C++ classes like C
4744 // structures.
4745 }
4746
Steve Naroff529a4ad2007-11-27 17:58:44 +00004747 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4748 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004749 if ((lhsType->isPointerType() ||
4750 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004751 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004752 && rExpr->isNullPointerConstant(Context,
4753 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004754 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004755 return Compatible;
4756 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004757
Chris Lattner943140e2007-10-16 02:55:40 +00004758 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004759 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004760 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004761 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004762 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004763 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004764 if (!lhsType->isReferenceType())
4765 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004766
Chris Lattner5cf216b2008-01-04 18:04:52 +00004767 Sema::AssignConvertType result =
4768 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004769
Steve Narofff1120de2007-08-24 22:33:52 +00004770 // C99 6.5.16.1p2: The value of the right operand is converted to the
4771 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004772 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4773 // so that we can use references in built-in functions even in C.
4774 // The getNonReferenceType() call makes sure that the resulting expression
4775 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004776 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004777 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4778 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004779 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004780}
4781
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004782QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004783 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004784 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004785 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004786 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004787}
4788
Mike Stumpeed9cac2009-02-19 03:04:26 +00004789inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004790 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004791 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004792 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004793 QualType lhsType =
4794 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4795 QualType rhsType =
4796 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004797
Nate Begemanbe2341d2008-07-14 18:02:46 +00004798 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004799 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004800 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004801
Nate Begemanbe2341d2008-07-14 18:02:46 +00004802 // Handle the case of a vector & extvector type of the same size and element
4803 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004804 if (getLangOptions().LaxVectorConversions) {
4805 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004806 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4807 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004808 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004809 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004810 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004811 }
4812 }
4813 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004814
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004815 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4816 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4817 bool swapped = false;
4818 if (rhsType->isExtVectorType()) {
4819 swapped = true;
4820 std::swap(rex, lex);
4821 std::swap(rhsType, lhsType);
4822 }
Mike Stump1eb44332009-09-09 15:08:12 +00004823
Nate Begemandde25982009-06-28 19:12:57 +00004824 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004825 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004826 QualType EltTy = LV->getElementType();
4827 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4828 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004829 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004830 if (swapped) std::swap(rex, lex);
4831 return lhsType;
4832 }
4833 }
4834 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4835 rhsType->isRealFloatingType()) {
4836 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004837 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004838 if (swapped) std::swap(rex, lex);
4839 return lhsType;
4840 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004841 }
4842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Nate Begemandde25982009-06-28 19:12:57 +00004844 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004845 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004846 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004847 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004848 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004849}
4850
Reid Spencer5f016e22007-07-11 17:01:13 +00004851inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004852 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004853 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004854 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004855
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004856 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004857
Steve Naroffa4332e22007-07-17 00:58:39 +00004858 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004859 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004860 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004861}
4862
4863inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004864 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004865 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4866 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4867 return CheckVectorOperands(Loc, lex, rex);
4868 return InvalidOperands(Loc, lex, rex);
4869 }
Steve Naroff90045e82007-07-13 23:32:42 +00004870
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004871 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004872
Steve Naroffa4332e22007-07-17 00:58:39 +00004873 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004874 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004875 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004876}
4877
4878inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004879 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004880 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4881 QualType compType = CheckVectorOperands(Loc, lex, rex);
4882 if (CompLHSTy) *CompLHSTy = compType;
4883 return compType;
4884 }
Steve Naroff49b45262007-07-13 16:58:59 +00004885
Eli Friedmanab3a8522009-03-28 01:22:36 +00004886 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004887
Reid Spencer5f016e22007-07-11 17:01:13 +00004888 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004889 if (lex->getType()->isArithmeticType() &&
4890 rex->getType()->isArithmeticType()) {
4891 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004892 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004893 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004894
Eli Friedmand72d16e2008-05-18 18:08:51 +00004895 // Put any potential pointer into PExp
4896 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004897 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004898 std::swap(PExp, IExp);
4899
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004900 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004901
Eli Friedmand72d16e2008-05-18 18:08:51 +00004902 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004903 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004904
Chris Lattnerb5f15622009-04-24 23:50:08 +00004905 // Check for arithmetic on pointers to incomplete types.
4906 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004907 if (getLangOptions().CPlusPlus) {
4908 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004909 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004910 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004911 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004912
4913 // GNU extension: arithmetic on pointer to void
4914 Diag(Loc, diag::ext_gnu_void_ptr)
4915 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004916 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004917 if (getLangOptions().CPlusPlus) {
4918 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4919 << lex->getType() << lex->getSourceRange();
4920 return QualType();
4921 }
4922
4923 // GNU extension: arithmetic on pointer to function
4924 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4925 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004926 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004927 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004928 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004929 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004930 PExp->getType()->isObjCObjectPointerType()) &&
4931 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004932 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4933 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004934 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004935 return QualType();
4936 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004937 // Diagnose bad cases where we step over interface counts.
4938 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4939 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4940 << PointeeTy << PExp->getSourceRange();
4941 return QualType();
4942 }
Mike Stump1eb44332009-09-09 15:08:12 +00004943
Eli Friedmanab3a8522009-03-28 01:22:36 +00004944 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004945 QualType LHSTy = Context.isPromotableBitField(lex);
4946 if (LHSTy.isNull()) {
4947 LHSTy = lex->getType();
4948 if (LHSTy->isPromotableIntegerType())
4949 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004950 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004951 *CompLHSTy = LHSTy;
4952 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004953 return PExp->getType();
4954 }
4955 }
4956
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004957 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004958}
4959
Chris Lattnereca7be62008-04-07 05:30:13 +00004960// C99 6.5.6
4961QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004962 SourceLocation Loc, QualType* CompLHSTy) {
4963 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4964 QualType compType = CheckVectorOperands(Loc, lex, rex);
4965 if (CompLHSTy) *CompLHSTy = compType;
4966 return compType;
4967 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004968
Eli Friedmanab3a8522009-03-28 01:22:36 +00004969 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004970
Chris Lattner6e4ab612007-12-09 21:53:25 +00004971 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004972
Chris Lattner6e4ab612007-12-09 21:53:25 +00004973 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004974 if (lex->getType()->isArithmeticType()
4975 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004976 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004977 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004978 }
Mike Stump1eb44332009-09-09 15:08:12 +00004979
Chris Lattner6e4ab612007-12-09 21:53:25 +00004980 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004981 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004982 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004983
Douglas Gregore7450f52009-03-24 19:52:54 +00004984 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004985
Douglas Gregore7450f52009-03-24 19:52:54 +00004986 bool ComplainAboutVoid = false;
4987 Expr *ComplainAboutFunc = 0;
4988 if (lpointee->isVoidType()) {
4989 if (getLangOptions().CPlusPlus) {
4990 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4991 << lex->getSourceRange() << rex->getSourceRange();
4992 return QualType();
4993 }
4994
4995 // GNU C extension: arithmetic on pointer to void
4996 ComplainAboutVoid = true;
4997 } else if (lpointee->isFunctionType()) {
4998 if (getLangOptions().CPlusPlus) {
4999 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005000 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005001 return QualType();
5002 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005003
5004 // GNU C extension: arithmetic on pointer to function
5005 ComplainAboutFunc = lex;
5006 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005007 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005008 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005009 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005010 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005011 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005012
Chris Lattnerb5f15622009-04-24 23:50:08 +00005013 // Diagnose bad cases where we step over interface counts.
5014 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5015 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5016 << lpointee << lex->getSourceRange();
5017 return QualType();
5018 }
Mike Stump1eb44332009-09-09 15:08:12 +00005019
Chris Lattner6e4ab612007-12-09 21:53:25 +00005020 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005021 if (rex->getType()->isIntegerType()) {
5022 if (ComplainAboutVoid)
5023 Diag(Loc, diag::ext_gnu_void_ptr)
5024 << lex->getSourceRange() << rex->getSourceRange();
5025 if (ComplainAboutFunc)
5026 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005027 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005028 << ComplainAboutFunc->getSourceRange();
5029
Eli Friedmanab3a8522009-03-28 01:22:36 +00005030 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005031 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005032 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005033
Chris Lattner6e4ab612007-12-09 21:53:25 +00005034 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005035 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005036 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005037
Douglas Gregore7450f52009-03-24 19:52:54 +00005038 // RHS must be a completely-type object type.
5039 // Handle the GNU void* extension.
5040 if (rpointee->isVoidType()) {
5041 if (getLangOptions().CPlusPlus) {
5042 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5043 << lex->getSourceRange() << rex->getSourceRange();
5044 return QualType();
5045 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005046
Douglas Gregore7450f52009-03-24 19:52:54 +00005047 ComplainAboutVoid = true;
5048 } else if (rpointee->isFunctionType()) {
5049 if (getLangOptions().CPlusPlus) {
5050 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005051 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005052 return QualType();
5053 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005054
5055 // GNU extension: arithmetic on pointer to function
5056 if (!ComplainAboutFunc)
5057 ComplainAboutFunc = rex;
5058 } else if (!rpointee->isDependentType() &&
5059 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005060 PDiag(diag::err_typecheck_sub_ptr_object)
5061 << rex->getSourceRange()
5062 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005063 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005064
Eli Friedman88d936b2009-05-16 13:54:38 +00005065 if (getLangOptions().CPlusPlus) {
5066 // Pointee types must be the same: C++ [expr.add]
5067 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5068 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5069 << lex->getType() << rex->getType()
5070 << lex->getSourceRange() << rex->getSourceRange();
5071 return QualType();
5072 }
5073 } else {
5074 // Pointee types must be compatible C99 6.5.6p3
5075 if (!Context.typesAreCompatible(
5076 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5077 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5078 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5079 << lex->getType() << rex->getType()
5080 << lex->getSourceRange() << rex->getSourceRange();
5081 return QualType();
5082 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005083 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005084
Douglas Gregore7450f52009-03-24 19:52:54 +00005085 if (ComplainAboutVoid)
5086 Diag(Loc, diag::ext_gnu_void_ptr)
5087 << lex->getSourceRange() << rex->getSourceRange();
5088 if (ComplainAboutFunc)
5089 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005090 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005091 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005092
5093 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005094 return Context.getPointerDiffType();
5095 }
5096 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005097
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005098 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005099}
5100
Chris Lattnereca7be62008-04-07 05:30:13 +00005101// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005102QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005103 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005104 // C99 6.5.7p2: Each of the operands shall have integer type.
5105 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005106 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005107
Nate Begeman2207d792009-10-25 02:26:48 +00005108 // Vector shifts promote their scalar inputs to vector type.
5109 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5110 return CheckVectorOperands(Loc, lex, rex);
5111
Chris Lattnerca5eede2007-12-12 05:47:28 +00005112 // Shifts don't perform usual arithmetic conversions, they just do integer
5113 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005114 QualType LHSTy = Context.isPromotableBitField(lex);
5115 if (LHSTy.isNull()) {
5116 LHSTy = lex->getType();
5117 if (LHSTy->isPromotableIntegerType())
5118 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005119 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005120 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005121 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005122
Chris Lattnerca5eede2007-12-12 05:47:28 +00005123 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005124
Ryan Flynnd0439682009-08-07 16:20:20 +00005125 // Sanity-check shift operands
5126 llvm::APSInt Right;
5127 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005128 if (!rex->isValueDependent() &&
5129 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005130 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005131 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5132 else {
5133 llvm::APInt LeftBits(Right.getBitWidth(),
5134 Context.getTypeSize(lex->getType()));
5135 if (Right.uge(LeftBits))
5136 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5137 }
5138 }
5139
Chris Lattnerca5eede2007-12-12 05:47:28 +00005140 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005141 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005142}
5143
Douglas Gregor0c6db942009-05-04 06:07:12 +00005144// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005145QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005146 unsigned OpaqueOpc, bool isRelational) {
5147 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5148
Chris Lattner02dd4b12009-12-05 05:40:13 +00005149 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005150 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005151 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005152
John McCall5dbad3d2009-11-06 08:49:08 +00005153 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5154 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005155
Chris Lattnera5937dd2007-08-26 01:18:55 +00005156 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005157 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5158 UsualArithmeticConversions(lex, rex);
5159 else {
5160 UsualUnaryConversions(lex);
5161 UsualUnaryConversions(rex);
5162 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005163 QualType lType = lex->getType();
5164 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005165
Mike Stumpaf199f32009-05-07 18:43:07 +00005166 if (!lType->isFloatingType()
5167 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005168 // For non-floating point types, check for self-comparisons of the form
5169 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5170 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005171 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005172 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005173 Expr *LHSStripped = lex->IgnoreParens();
5174 Expr *RHSStripped = rex->IgnoreParens();
5175 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5176 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005177 if (DRL->getDecl() == DRR->getDecl() &&
5178 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00005179 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00005180
Chris Lattner55660a72009-03-08 19:39:53 +00005181 if (isa<CastExpr>(LHSStripped))
5182 LHSStripped = LHSStripped->IgnoreParenCasts();
5183 if (isa<CastExpr>(RHSStripped))
5184 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Chris Lattner55660a72009-03-08 19:39:53 +00005186 // Warn about comparisons against a string constant (unless the other
5187 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005188 Expr *literalString = 0;
5189 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005190 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005191 !RHSStripped->isNullPointerConstant(Context,
5192 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005193 literalString = lex;
5194 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005195 } else if ((isa<StringLiteral>(RHSStripped) ||
5196 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005197 !LHSStripped->isNullPointerConstant(Context,
5198 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005199 literalString = rex;
5200 literalStringStripped = RHSStripped;
5201 }
5202
5203 if (literalString) {
5204 std::string resultComparison;
5205 switch (Opc) {
5206 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5207 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5208 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5209 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5210 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5211 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5212 default: assert(false && "Invalid comparison operator");
5213 }
5214 Diag(Loc, diag::warn_stringcompare)
5215 << isa<ObjCEncodeExpr>(literalStringStripped)
5216 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00005217 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5218 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5219 "strcmp(")
5220 << CodeModificationHint::CreateInsertion(
5221 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00005222 resultComparison);
5223 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005225
Douglas Gregor447b69e2008-11-19 03:25:36 +00005226 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005227 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005228
Chris Lattnera5937dd2007-08-26 01:18:55 +00005229 if (isRelational) {
5230 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005231 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005232 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005233 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005234 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005235 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005236
Chris Lattnera5937dd2007-08-26 01:18:55 +00005237 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005238 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005239 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005240
Douglas Gregorce940492009-09-25 04:25:58 +00005241 bool LHSIsNull = lex->isNullPointerConstant(Context,
5242 Expr::NPC_ValueDependentIsNull);
5243 bool RHSIsNull = rex->isNullPointerConstant(Context,
5244 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005245
Chris Lattnera5937dd2007-08-26 01:18:55 +00005246 // All of the following pointer related warnings are GCC extensions, except
5247 // when handling null pointer constants. One day, we can consider making them
5248 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005249 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005250 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005251 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005252 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005253 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005254
Douglas Gregor0c6db942009-05-04 06:07:12 +00005255 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005256 if (LCanPointeeTy == RCanPointeeTy)
5257 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005258 if (!isRelational &&
5259 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5260 // Valid unless comparison between non-null pointer and function pointer
5261 // This is a gcc extension compatibility comparison.
5262 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5263 && !LHSIsNull && !RHSIsNull) {
5264 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5265 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5266 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5267 return ResultTy;
5268 }
5269 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005270 // C++ [expr.rel]p2:
5271 // [...] Pointer conversions (4.10) and qualification
5272 // conversions (4.4) are performed on pointer operands (or on
5273 // a pointer operand and a null pointer constant) to bring
5274 // them to their composite pointer type. [...]
5275 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005276 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005277 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005278 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005279 if (T.isNull()) {
5280 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5281 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5282 return QualType();
5283 }
5284
Eli Friedman73c39ab2009-10-20 08:27:19 +00005285 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5286 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005287 return ResultTy;
5288 }
Eli Friedman3075e762009-08-23 00:27:47 +00005289 // C99 6.5.9p2 and C99 6.5.8p2
5290 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5291 RCanPointeeTy.getUnqualifiedType())) {
5292 // Valid unless a relational comparison of function pointers
5293 if (isRelational && LCanPointeeTy->isFunctionType()) {
5294 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5295 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5296 }
5297 } else if (!isRelational &&
5298 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5299 // Valid unless comparison between non-null pointer and function pointer
5300 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5301 && !LHSIsNull && !RHSIsNull) {
5302 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5303 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5304 }
5305 } else {
5306 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005307 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005308 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005309 }
Eli Friedman3075e762009-08-23 00:27:47 +00005310 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005311 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005312 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005313 }
Mike Stump1eb44332009-09-09 15:08:12 +00005314
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005315 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005316 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005317 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005318 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005319 (lType->isPointerType() ||
5320 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005321 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005322 return ResultTy;
5323 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005324 if (LHSIsNull &&
5325 (rType->isPointerType() ||
5326 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005327 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005328 return ResultTy;
5329 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005330
5331 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005332 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005333 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5334 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005335 // In addition, pointers to members can be compared, or a pointer to
5336 // member and a null pointer constant. Pointer to member conversions
5337 // (4.11) and qualification conversions (4.4) are performed to bring
5338 // them to a common type. If one operand is a null pointer constant,
5339 // the common type is the type of the other operand. Otherwise, the
5340 // common type is a pointer to member type similar (4.4) to the type
5341 // of one of the operands, with a cv-qualification signature (4.4)
5342 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005343 // types.
5344 QualType T = FindCompositePointerType(lex, rex);
5345 if (T.isNull()) {
5346 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5347 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5348 return QualType();
5349 }
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Eli Friedman73c39ab2009-10-20 08:27:19 +00005351 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5352 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005353 return ResultTy;
5354 }
Mike Stump1eb44332009-09-09 15:08:12 +00005355
Douglas Gregor20b3e992009-08-24 17:42:35 +00005356 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005357 if (lType->isNullPtrType() && rType->isNullPtrType())
5358 return ResultTy;
5359 }
Mike Stump1eb44332009-09-09 15:08:12 +00005360
Steve Naroff1c7d0672008-09-04 15:10:53 +00005361 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005362 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005363 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5364 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005365
Steve Naroff1c7d0672008-09-04 15:10:53 +00005366 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005367 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005368 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005369 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005370 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005371 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005372 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005373 }
Steve Naroff59f53942008-09-28 01:11:11 +00005374 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005375 if (!isRelational
5376 && ((lType->isBlockPointerType() && rType->isPointerType())
5377 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005378 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005379 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005380 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005381 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005382 ->getPointeeType()->isVoidType())))
5383 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5384 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005385 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005386 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005387 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005388 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005389
Steve Naroff14108da2009-07-10 23:34:53 +00005390 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005391 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005392 const PointerType *LPT = lType->getAs<PointerType>();
5393 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005394 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005395 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005396 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005397 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005398
Steve Naroffa8069f12008-11-17 19:49:16 +00005399 if (!LPtrToVoid && !RPtrToVoid &&
5400 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005401 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005402 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005403 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005404 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005405 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005406 }
Steve Naroff14108da2009-07-10 23:34:53 +00005407 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005408 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005409 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5410 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005411 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005412 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005413 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005414 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005415 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005416 unsigned DiagID = 0;
5417 if (RHSIsNull) {
5418 if (isRelational)
5419 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5420 } else if (isRelational)
5421 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5422 else
5423 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005425 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005426 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005427 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005428 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005429 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005430 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005431 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005432 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005433 unsigned DiagID = 0;
5434 if (LHSIsNull) {
5435 if (isRelational)
5436 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5437 } else if (isRelational)
5438 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5439 else
5440 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005441
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005442 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005443 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005444 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005445 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005446 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005447 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005448 }
Steve Naroff39218df2008-09-04 16:56:14 +00005449 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005450 if (!isRelational && RHSIsNull
5451 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005452 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005453 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005454 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005455 if (!isRelational && LHSIsNull
5456 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005457 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005458 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005459 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005460 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005461}
5462
Nate Begemanbe2341d2008-07-14 18:02:46 +00005463/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005464/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005465/// like a scalar comparison, a vector comparison produces a vector of integer
5466/// types.
5467QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005468 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005469 bool isRelational) {
5470 // Check to make sure we're operating on vectors of the same type and width,
5471 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005472 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005473 if (vType.isNull())
5474 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005475
Nate Begemanbe2341d2008-07-14 18:02:46 +00005476 QualType lType = lex->getType();
5477 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005478
Nate Begemanbe2341d2008-07-14 18:02:46 +00005479 // For non-floating point types, check for self-comparisons of the form
5480 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5481 // often indicate logic errors in the program.
5482 if (!lType->isFloatingType()) {
5483 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5484 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5485 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005486 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005487 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005488
Nate Begemanbe2341d2008-07-14 18:02:46 +00005489 // Check for comparisons of floating point operands using != and ==.
5490 if (!isRelational && lType->isFloatingType()) {
5491 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005492 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005493 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005494
Nate Begemanbe2341d2008-07-14 18:02:46 +00005495 // Return the type for the comparison, which is the same as vector type for
5496 // integer vectors, or an integer type of identical size and number of
5497 // elements for floating point vectors.
5498 if (lType->isIntegerType())
5499 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005500
John McCall183700f2009-09-21 23:43:11 +00005501 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005502 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005503 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005504 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005505 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005506 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5507
Mike Stumpeed9cac2009-02-19 03:04:26 +00005508 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005509 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005510 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5511}
5512
Reid Spencer5f016e22007-07-11 17:01:13 +00005513inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005514 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005515 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005516 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005517
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005518 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005519
Steve Naroffa4332e22007-07-17 00:58:39 +00005520 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005521 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005522 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005523}
5524
5525inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005526 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005527 if (!Context.getLangOptions().CPlusPlus) {
5528 UsualUnaryConversions(lex);
5529 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005530
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005531 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5532 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005533
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005534 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005535 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005536
5537 // C++ [expr.log.and]p1
5538 // C++ [expr.log.or]p1
5539 // The operands are both implicitly converted to type bool (clause 4).
5540 StandardConversionSequence LHS;
5541 if (!IsStandardConversion(lex, Context.BoolTy,
5542 /*InOverloadResolution=*/false, LHS))
5543 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005544
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005545 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005546 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005547 return InvalidOperands(Loc, lex, rex);
5548
5549 StandardConversionSequence RHS;
5550 if (!IsStandardConversion(rex, Context.BoolTy,
5551 /*InOverloadResolution=*/false, RHS))
5552 return InvalidOperands(Loc, lex, rex);
5553
5554 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005555 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005556 return InvalidOperands(Loc, lex, rex);
5557
5558 // C++ [expr.log.and]p2
5559 // C++ [expr.log.or]p2
5560 // The result is a bool.
5561 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005562}
5563
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005564/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5565/// is a read-only property; return true if so. A readonly property expression
5566/// depends on various declarations and thus must be treated specially.
5567///
Mike Stump1eb44332009-09-09 15:08:12 +00005568static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005569 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5570 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5571 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5572 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005573 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005574 BaseType->getAsObjCInterfacePointerType())
5575 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5576 if (S.isPropertyReadonly(PDecl, IFace))
5577 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005578 }
5579 }
5580 return false;
5581}
5582
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005583/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5584/// emit an error and return true. If so, return false.
5585static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005586 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005587 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005588 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005589 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5590 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005591 if (IsLV == Expr::MLV_Valid)
5592 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005593
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005594 unsigned Diag = 0;
5595 bool NeedType = false;
5596 switch (IsLV) { // C99 6.5.16p2
5597 default: assert(0 && "Unknown result from isModifiableLvalue!");
5598 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005599 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005600 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5601 NeedType = true;
5602 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005603 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005604 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5605 NeedType = true;
5606 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005607 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005608 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5609 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005610 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005611 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5612 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005613 case Expr::MLV_IncompleteType:
5614 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005615 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005616 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5617 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005618 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005619 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5620 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005621 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005622 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5623 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005624 case Expr::MLV_ReadonlyProperty:
5625 Diag = diag::error_readonly_property_assignment;
5626 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005627 case Expr::MLV_NoSetterProperty:
5628 Diag = diag::error_nosetter_property_assignment;
5629 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005630 case Expr::MLV_SubObjCPropertySetting:
5631 Diag = diag::error_no_subobject_property_setting;
5632 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005633 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005634
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005635 SourceRange Assign;
5636 if (Loc != OrigLoc)
5637 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005638 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005639 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005640 else
Mike Stump1eb44332009-09-09 15:08:12 +00005641 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005642 return true;
5643}
5644
5645
5646
5647// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005648QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5649 SourceLocation Loc,
5650 QualType CompoundType) {
5651 // Verify that LHS is a modifiable lvalue, and emit error if not.
5652 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005653 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005654
5655 QualType LHSType = LHS->getType();
5656 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005657
Chris Lattner5cf216b2008-01-04 18:04:52 +00005658 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005659 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005660 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005661 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005662 // Special case of NSObject attributes on c-style pointer types.
5663 if (ConvTy == IncompatiblePointer &&
5664 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005665 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005666 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005667 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005668 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005669
Chris Lattner2c156472008-08-21 18:04:13 +00005670 // If the RHS is a unary plus or minus, check to see if they = and + are
5671 // right next to each other. If so, the user may have typo'd "x =+ 4"
5672 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005673 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5675 RHSCheck = ICE->getSubExpr();
5676 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5677 if ((UO->getOpcode() == UnaryOperator::Plus ||
5678 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005679 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005680 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005681 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5682 // And there is a space or other character before the subexpr of the
5683 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005684 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5685 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005686 Diag(Loc, diag::warn_not_compound_assign)
5687 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5688 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005689 }
Chris Lattner2c156472008-08-21 18:04:13 +00005690 }
5691 } else {
5692 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005693 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005694 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005695
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005696 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005697 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005698 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005699
Reid Spencer5f016e22007-07-11 17:01:13 +00005700 // C99 6.5.16p3: The type of an assignment expression is the type of the
5701 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005702 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005703 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5704 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005705 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005706 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005707 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005708}
5709
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005710// C99 6.5.17
5711QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005712 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005713 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005714
5715 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5716 // incomplete in C++).
5717
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005718 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005719}
5720
Steve Naroff49b45262007-07-13 16:58:59 +00005721/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5722/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005723QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5724 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005725 if (Op->isTypeDependent())
5726 return Context.DependentTy;
5727
Chris Lattner3528d352008-11-21 07:05:48 +00005728 QualType ResType = Op->getType();
5729 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005730
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005731 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5732 // Decrement of bool is not allowed.
5733 if (!isInc) {
5734 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5735 return QualType();
5736 }
5737 // Increment of bool sets it to true, but is deprecated.
5738 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5739 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005740 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005741 } else if (ResType->isAnyPointerType()) {
5742 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Chris Lattner3528d352008-11-21 07:05:48 +00005744 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005745 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005746 if (getLangOptions().CPlusPlus) {
5747 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5748 << Op->getSourceRange();
5749 return QualType();
5750 }
5751
5752 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005753 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005754 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005755 if (getLangOptions().CPlusPlus) {
5756 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5757 << Op->getType() << Op->getSourceRange();
5758 return QualType();
5759 }
5760
5761 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005762 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005763 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005764 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005765 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005766 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005767 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005768 // Diagnose bad cases where we step over interface counts.
5769 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5770 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5771 << PointeeTy << Op->getSourceRange();
5772 return QualType();
5773 }
Eli Friedman5b088a12010-01-03 00:20:48 +00005774 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005775 // C99 does not support ++/-- on complex types, we allow as an extension.
5776 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005777 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005778 } else {
5779 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005780 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005781 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005782 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005783 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005784 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005785 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005786 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005787 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005788}
5789
Anders Carlsson369dee42008-02-01 07:15:58 +00005790/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005791/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005792/// where the declaration is needed for type checking. We only need to
5793/// handle cases when the expression references a function designator
5794/// or is an lvalue. Here are some examples:
5795/// - &(x) => x
5796/// - &*****f => f for f a function designator.
5797/// - &s.xx => s
5798/// - &s.zz[1].yy -> s, if zz is an array
5799/// - *(x + 1) -> x, if x is an array
5800/// - &"123"[2] -> 0
5801/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005802static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005803 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005804 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005805 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005806 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005807 // If this is an arrow operator, the address is an offset from
5808 // the base's value, so the object the base refers to is
5809 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005810 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005811 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005812 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005813 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005814 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005815 // FIXME: This code shouldn't be necessary! We should catch the implicit
5816 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005817 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5818 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5819 if (ICE->getSubExpr()->getType()->isArrayType())
5820 return getPrimaryDecl(ICE->getSubExpr());
5821 }
5822 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005823 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005824 case Stmt::UnaryOperatorClass: {
5825 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005826
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005827 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005828 case UnaryOperator::Real:
5829 case UnaryOperator::Imag:
5830 case UnaryOperator::Extension:
5831 return getPrimaryDecl(UO->getSubExpr());
5832 default:
5833 return 0;
5834 }
5835 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005836 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005837 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005838 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005839 // If the result of an implicit cast is an l-value, we care about
5840 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005841 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005842 default:
5843 return 0;
5844 }
5845}
5846
5847/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005848/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005849/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005850/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005851/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005852/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005853/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005854QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005855 // Make sure to ignore parentheses in subsequent checks
5856 op = op->IgnoreParens();
5857
Douglas Gregor9103bb22008-12-17 22:52:20 +00005858 if (op->isTypeDependent())
5859 return Context.DependentTy;
5860
Steve Naroff08f19672008-01-13 17:10:08 +00005861 if (getLangOptions().C99) {
5862 // Implement C99-only parts of addressof rules.
5863 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5864 if (uOp->getOpcode() == UnaryOperator::Deref)
5865 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5866 // (assuming the deref expression is valid).
5867 return uOp->getSubExpr()->getType();
5868 }
5869 // Technically, there should be a check for array subscript
5870 // expressions here, but the result of one is always an lvalue anyway.
5871 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005872 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005873 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005874
Eli Friedman441cf102009-05-16 23:27:50 +00005875 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5876 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005877 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005878 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005879 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005880 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5881 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005882 return QualType();
5883 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005884 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005885 // The operand cannot be a bit-field
5886 Diag(OpLoc, diag::err_typecheck_address_of)
5887 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005888 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005889 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5890 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005891 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005892 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005893 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005894 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005895 } else if (isa<ObjCPropertyRefExpr>(op)) {
5896 // cannot take address of a property expression.
5897 Diag(OpLoc, diag::err_typecheck_address_of)
5898 << "property expression" << op->getSourceRange();
5899 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005900 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5901 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005902 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5903 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005904 } else if (isa<UnresolvedLookupExpr>(op)) {
5905 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005906 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005907 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005908 // with the register storage-class specifier.
5909 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5910 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005911 Diag(OpLoc, diag::err_typecheck_address_of)
5912 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005913 return QualType();
5914 }
John McCallba135432009-11-21 08:51:07 +00005915 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005916 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005917 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005918 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005919 // Could be a pointer to member, though, if there is an explicit
5920 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005921 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005922 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005923 if (Ctx && Ctx->isRecord()) {
5924 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005925 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005926 diag::err_cannot_form_pointer_to_member_of_reference_type)
5927 << FD->getDeclName() << FD->getType();
5928 return QualType();
5929 }
Mike Stump1eb44332009-09-09 15:08:12 +00005930
Sebastian Redlebc07d52009-02-03 20:19:35 +00005931 return Context.getMemberPointerType(op->getType(),
5932 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005933 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005934 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005935 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005936 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005937 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005938 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5939 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005940 return Context.getMemberPointerType(op->getType(),
5941 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5942 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005943 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005944 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005945
Eli Friedman441cf102009-05-16 23:27:50 +00005946 if (lval == Expr::LV_IncompleteVoidType) {
5947 // Taking the address of a void variable is technically illegal, but we
5948 // allow it in cases which are otherwise valid.
5949 // Example: "extern void x; void* y = &x;".
5950 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5951 }
5952
Reid Spencer5f016e22007-07-11 17:01:13 +00005953 // If the operand has type "type", the result has type "pointer to type".
5954 return Context.getPointerType(op->getType());
5955}
5956
Chris Lattner22caddc2008-11-23 09:13:29 +00005957QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005958 if (Op->isTypeDependent())
5959 return Context.DependentTy;
5960
Chris Lattner22caddc2008-11-23 09:13:29 +00005961 UsualUnaryConversions(Op);
5962 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005963
Chris Lattner22caddc2008-11-23 09:13:29 +00005964 // Note that per both C89 and C99, this is always legal, even if ptype is an
5965 // incomplete type or void. It would be possible to warn about dereferencing
5966 // a void pointer, but it's completely well-defined, and such a warning is
5967 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005968 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005969 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005970
John McCall183700f2009-09-21 23:43:11 +00005971 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005972 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005973
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005974 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005975 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005976 return QualType();
5977}
5978
5979static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5980 tok::TokenKind Kind) {
5981 BinaryOperator::Opcode Opc;
5982 switch (Kind) {
5983 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005984 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5985 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005986 case tok::star: Opc = BinaryOperator::Mul; break;
5987 case tok::slash: Opc = BinaryOperator::Div; break;
5988 case tok::percent: Opc = BinaryOperator::Rem; break;
5989 case tok::plus: Opc = BinaryOperator::Add; break;
5990 case tok::minus: Opc = BinaryOperator::Sub; break;
5991 case tok::lessless: Opc = BinaryOperator::Shl; break;
5992 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5993 case tok::lessequal: Opc = BinaryOperator::LE; break;
5994 case tok::less: Opc = BinaryOperator::LT; break;
5995 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5996 case tok::greater: Opc = BinaryOperator::GT; break;
5997 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5998 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5999 case tok::amp: Opc = BinaryOperator::And; break;
6000 case tok::caret: Opc = BinaryOperator::Xor; break;
6001 case tok::pipe: Opc = BinaryOperator::Or; break;
6002 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6003 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6004 case tok::equal: Opc = BinaryOperator::Assign; break;
6005 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6006 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6007 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6008 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6009 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6010 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6011 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6012 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6013 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6014 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6015 case tok::comma: Opc = BinaryOperator::Comma; break;
6016 }
6017 return Opc;
6018}
6019
6020static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6021 tok::TokenKind Kind) {
6022 UnaryOperator::Opcode Opc;
6023 switch (Kind) {
6024 default: assert(0 && "Unknown unary op!");
6025 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6026 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6027 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6028 case tok::star: Opc = UnaryOperator::Deref; break;
6029 case tok::plus: Opc = UnaryOperator::Plus; break;
6030 case tok::minus: Opc = UnaryOperator::Minus; break;
6031 case tok::tilde: Opc = UnaryOperator::Not; break;
6032 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006033 case tok::kw___real: Opc = UnaryOperator::Real; break;
6034 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6035 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6036 }
6037 return Opc;
6038}
6039
Douglas Gregoreaebc752008-11-06 23:29:22 +00006040/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6041/// operator @p Opc at location @c TokLoc. This routine only supports
6042/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006043Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6044 unsigned Op,
6045 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006046 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006047 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006048 // The following two variables are used for compound assignment operators
6049 QualType CompLHSTy; // Type of LHS after promotions for computation
6050 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006051
6052 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006053 case BinaryOperator::Assign:
6054 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6055 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006056 case BinaryOperator::PtrMemD:
6057 case BinaryOperator::PtrMemI:
6058 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6059 Opc == BinaryOperator::PtrMemI);
6060 break;
6061 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006062 case BinaryOperator::Div:
6063 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6064 break;
6065 case BinaryOperator::Rem:
6066 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6067 break;
6068 case BinaryOperator::Add:
6069 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6070 break;
6071 case BinaryOperator::Sub:
6072 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6073 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006074 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006075 case BinaryOperator::Shr:
6076 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6077 break;
6078 case BinaryOperator::LE:
6079 case BinaryOperator::LT:
6080 case BinaryOperator::GE:
6081 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006082 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006083 break;
6084 case BinaryOperator::EQ:
6085 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006086 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006087 break;
6088 case BinaryOperator::And:
6089 case BinaryOperator::Xor:
6090 case BinaryOperator::Or:
6091 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6092 break;
6093 case BinaryOperator::LAnd:
6094 case BinaryOperator::LOr:
6095 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6096 break;
6097 case BinaryOperator::MulAssign:
6098 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006099 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6100 CompLHSTy = CompResultTy;
6101 if (!CompResultTy.isNull())
6102 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006103 break;
6104 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006105 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6106 CompLHSTy = CompResultTy;
6107 if (!CompResultTy.isNull())
6108 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006109 break;
6110 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006111 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6112 if (!CompResultTy.isNull())
6113 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006114 break;
6115 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006116 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6117 if (!CompResultTy.isNull())
6118 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006119 break;
6120 case BinaryOperator::ShlAssign:
6121 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006122 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6123 CompLHSTy = CompResultTy;
6124 if (!CompResultTy.isNull())
6125 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006126 break;
6127 case BinaryOperator::AndAssign:
6128 case BinaryOperator::XorAssign:
6129 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006130 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6131 CompLHSTy = CompResultTy;
6132 if (!CompResultTy.isNull())
6133 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006134 break;
6135 case BinaryOperator::Comma:
6136 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6137 break;
6138 }
6139 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006140 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006141 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006142 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6143 else
6144 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006145 CompLHSTy, CompResultTy,
6146 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006147}
6148
Sebastian Redlaee3c932009-10-27 12:10:02 +00006149/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6150/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006151static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6152 const PartialDiagnostic &PD,
Douglas Gregor827feec2010-01-08 00:20:23 +00006153 SourceRange ParenRange,
6154 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6155 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006156 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6157 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6158 // We can't display the parentheses, so just dig the
6159 // warning/error and return.
6160 Self.Diag(Loc, PD);
6161 return;
6162 }
6163
6164 Self.Diag(Loc, PD)
6165 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6166 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00006167
6168 if (!SecondPD.getDiagID())
6169 return;
6170
6171 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6172 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6173 // We can't display the parentheses, so just dig the
6174 // warning/error and return.
6175 Self.Diag(Loc, SecondPD);
6176 return;
6177 }
6178
6179 Self.Diag(Loc, SecondPD)
6180 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6181 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006182}
6183
Sebastian Redlaee3c932009-10-27 12:10:02 +00006184/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6185/// operators are mixed in a way that suggests that the programmer forgot that
6186/// comparison operators have higher precedence. The most typical example of
6187/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006188static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6189 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006190 typedef BinaryOperator BinOp;
6191 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6192 rhsopc = static_cast<BinOp::Opcode>(-1);
6193 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006194 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006195 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006196 rhsopc = BO->getOpcode();
6197
6198 // Subs are not binary operators.
6199 if (lhsopc == -1 && rhsopc == -1)
6200 return;
6201
6202 // Bitwise operations are sometimes used as eager logical ops.
6203 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006204 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6205 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006206 return;
6207
Sebastian Redlaee3c932009-10-27 12:10:02 +00006208 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006209 SuggestParentheses(Self, OpLoc,
6210 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006211 << SourceRange(lhs->getLocStart(), OpLoc)
6212 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006213 lhs->getSourceRange(),
6214 PDiag(diag::note_precedence_bitwise_first)
6215 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006216 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6217 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006218 SuggestParentheses(Self, OpLoc,
6219 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006220 << SourceRange(OpLoc, rhs->getLocEnd())
6221 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006222 rhs->getSourceRange(),
6223 PDiag(diag::note_precedence_bitwise_first)
6224 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006225 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006226}
6227
6228/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6229/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6230/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6231static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6232 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006233 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006234 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6235}
6236
Reid Spencer5f016e22007-07-11 17:01:13 +00006237// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006238Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6239 tok::TokenKind Kind,
6240 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006241 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006242 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006243
Steve Narofff69936d2007-09-16 03:34:24 +00006244 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6245 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006246
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006247 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6248 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6249
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006250 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6251}
6252
6253Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6254 BinaryOperator::Opcode Opc,
6255 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006256 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006257 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006258 rhs->getType()->isOverloadableType())) {
6259 // Find all of the overloaded operators visible from this
6260 // point. We perform both an operator-name lookup from the local
6261 // scope and an argument-dependent lookup based on the types of
6262 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006263 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006264 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6265 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006266 if (S)
6267 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6268 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006269 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006270 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006271 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006272 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006273 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006274
Douglas Gregor063daf62009-03-13 18:40:31 +00006275 // Build the (potentially-overloaded, potentially-dependent)
6276 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006277 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006278 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006279
Douglas Gregoreaebc752008-11-06 23:29:22 +00006280 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006281 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006282}
6283
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006284Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006285 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006286 ExprArg InputArg) {
6287 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006288
Mike Stump390b4cc2009-05-16 07:39:55 +00006289 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006290 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006291 QualType resultType;
6292 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006293 case UnaryOperator::OffsetOf:
6294 assert(false && "Invalid unary operator");
6295 break;
6296
Reid Spencer5f016e22007-07-11 17:01:13 +00006297 case UnaryOperator::PreInc:
6298 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006299 case UnaryOperator::PostInc:
6300 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006301 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006302 Opc == UnaryOperator::PreInc ||
6303 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006304 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006305 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006306 resultType = CheckAddressOfOperand(Input, OpLoc);
6307 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006308 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006309 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006310 resultType = CheckIndirectionOperand(Input, OpLoc);
6311 break;
6312 case UnaryOperator::Plus:
6313 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006314 UsualUnaryConversions(Input);
6315 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006316 if (resultType->isDependentType())
6317 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006318 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6319 break;
6320 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6321 resultType->isEnumeralType())
6322 break;
6323 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6324 Opc == UnaryOperator::Plus &&
6325 resultType->isPointerType())
6326 break;
6327
Sebastian Redl0eb23302009-01-19 00:08:26 +00006328 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6329 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006330 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006331 UsualUnaryConversions(Input);
6332 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006333 if (resultType->isDependentType())
6334 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006335 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6336 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6337 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006338 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006339 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006340 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006341 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6342 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006343 break;
6344 case UnaryOperator::LNot: // logical negation
6345 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006346 DefaultFunctionArrayConversion(Input);
6347 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006348 if (resultType->isDependentType())
6349 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006350 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006351 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6352 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006353 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006354 // In C++, it's bool. C++ 5.3.1p8
6355 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006356 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006357 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006358 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006359 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006360 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006361 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006362 resultType = Input->getType();
6363 break;
6364 }
6365 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006366 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006367
6368 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006369 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006370}
6371
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006372Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6373 UnaryOperator::Opcode Opc,
6374 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006375 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006376 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6377 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006378 // Find all of the overloaded operators visible from this
6379 // point. We perform both an operator-name lookup from the local
6380 // scope and an argument-dependent lookup based on the types of
6381 // the arguments.
6382 FunctionSet Functions;
6383 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6384 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006385 if (S)
6386 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6387 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006388 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006389 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006390 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006391 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006392
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006393 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6394 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006395
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006396 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6397}
6398
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006399// Unary Operators. 'Tok' is the token for the operator.
6400Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6401 tok::TokenKind Op, ExprArg input) {
6402 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6403}
6404
Steve Naroff1b273c42007-09-16 14:56:35 +00006405/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006406Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6407 SourceLocation LabLoc,
6408 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006409 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006410 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006411
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006412 // If we haven't seen this label yet, create a forward reference. It
6413 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006414 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006415 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006416
Reid Spencer5f016e22007-07-11 17:01:13 +00006417 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006418 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6419 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006420}
6421
Sebastian Redlf53597f2009-03-15 17:47:39 +00006422Sema::OwningExprResult
6423Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6424 SourceLocation RPLoc) { // "({..})"
6425 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006426 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6427 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6428
Eli Friedmandca2b732009-01-24 23:09:00 +00006429 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006430 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006431 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006432
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006433 // FIXME: there are a variety of strange constraints to enforce here, for
6434 // example, it is not possible to goto into a stmt expression apparently.
6435 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006436
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006437 // If there are sub stmts in the compound stmt, take the type of the last one
6438 // as the type of the stmtexpr.
6439 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006440
Chris Lattner611b2ec2008-07-26 19:51:01 +00006441 if (!Compound->body_empty()) {
6442 Stmt *LastStmt = Compound->body_back();
6443 // If LastStmt is a label, skip down through into the body.
6444 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6445 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006446
Chris Lattner611b2ec2008-07-26 19:51:01 +00006447 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006448 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006449 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006450
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006451 // FIXME: Check that expression type is complete/non-abstract; statement
6452 // expressions are not lvalues.
6453
Sebastian Redlf53597f2009-03-15 17:47:39 +00006454 substmt.release();
6455 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006456}
Steve Naroffd34e9152007-08-01 22:05:33 +00006457
Sebastian Redlf53597f2009-03-15 17:47:39 +00006458Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6459 SourceLocation BuiltinLoc,
6460 SourceLocation TypeLoc,
6461 TypeTy *argty,
6462 OffsetOfComponent *CompPtr,
6463 unsigned NumComponents,
6464 SourceLocation RPLoc) {
6465 // FIXME: This function leaks all expressions in the offset components on
6466 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006467 // FIXME: Preserve type source info.
6468 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006469 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006470
Sebastian Redl28507842009-02-26 14:39:58 +00006471 bool Dependent = ArgTy->isDependentType();
6472
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006473 // We must have at least one component that refers to the type, and the first
6474 // one is known to be a field designator. Verify that the ArgTy represents
6475 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006476 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006477 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006478
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006479 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6480 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006481
Eli Friedman35183ac2009-02-27 06:44:11 +00006482 // Otherwise, create a null pointer as the base, and iteratively process
6483 // the offsetof designators.
6484 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6485 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006486 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006487 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006488
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006489 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6490 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006491 // FIXME: This diagnostic isn't actually visible because the location is in
6492 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006493 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006494 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6495 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006496
Sebastian Redl28507842009-02-26 14:39:58 +00006497 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006498 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006499
John McCalld00f2002009-11-04 03:03:43 +00006500 if (RequireCompleteType(TypeLoc, Res->getType(),
6501 diag::err_offsetof_incomplete_type))
6502 return ExprError();
6503
Sebastian Redl28507842009-02-26 14:39:58 +00006504 // FIXME: Dependent case loses a lot of information here. And probably
6505 // leaks like a sieve.
6506 for (unsigned i = 0; i != NumComponents; ++i) {
6507 const OffsetOfComponent &OC = CompPtr[i];
6508 if (OC.isBrackets) {
6509 // Offset of an array sub-field. TODO: Should we allow vector elements?
6510 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6511 if (!AT) {
6512 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006513 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6514 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006515 }
6516
6517 // FIXME: C++: Verify that operator[] isn't overloaded.
6518
Eli Friedman35183ac2009-02-27 06:44:11 +00006519 // Promote the array so it looks more like a normal array subscript
6520 // expression.
6521 DefaultFunctionArrayConversion(Res);
6522
Sebastian Redl28507842009-02-26 14:39:58 +00006523 // C99 6.5.2.1p1
6524 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006525 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006526 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006527 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006528 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006529 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006530
6531 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6532 OC.LocEnd);
6533 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006534 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006535
Ted Kremenek6217b802009-07-29 21:53:49 +00006536 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006537 if (!RC) {
6538 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006539 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6540 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006541 }
Chris Lattner704fe352007-08-30 17:59:59 +00006542
Sebastian Redl28507842009-02-26 14:39:58 +00006543 // Get the decl corresponding to this.
6544 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006545 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006546 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6547 DiagRuntimeBehavior(BuiltinLoc,
6548 PDiag(diag::warn_offsetof_non_pod_type)
6549 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6550 << Res->getType()))
6551 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006552 }
Mike Stump1eb44332009-09-09 15:08:12 +00006553
John McCalla24dc2e2009-11-17 02:14:36 +00006554 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6555 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006556
John McCall1bcee0a2009-12-02 08:25:40 +00006557 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006558 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006559 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006560 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6561 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006562
Sebastian Redl28507842009-02-26 14:39:58 +00006563 // FIXME: C++: Verify that MemberDecl isn't a static field.
6564 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006565 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006566 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006567 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006568 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006569 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006570 // MemberDecl->getType() doesn't get the right qualifiers, but it
6571 // doesn't matter here.
6572 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6573 MemberDecl->getType().getNonReferenceType());
6574 }
Sebastian Redl28507842009-02-26 14:39:58 +00006575 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006576 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006577
Sebastian Redlf53597f2009-03-15 17:47:39 +00006578 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6579 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006580}
6581
6582
Sebastian Redlf53597f2009-03-15 17:47:39 +00006583Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6584 TypeTy *arg1,TypeTy *arg2,
6585 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006586 // FIXME: Preserve type source info.
6587 QualType argT1 = GetTypeFromParser(arg1);
6588 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006589
Steve Naroffd34e9152007-08-01 22:05:33 +00006590 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006591
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006592 if (getLangOptions().CPlusPlus) {
6593 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6594 << SourceRange(BuiltinLoc, RPLoc);
6595 return ExprError();
6596 }
6597
Sebastian Redlf53597f2009-03-15 17:47:39 +00006598 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6599 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006600}
6601
Sebastian Redlf53597f2009-03-15 17:47:39 +00006602Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6603 ExprArg cond,
6604 ExprArg expr1, ExprArg expr2,
6605 SourceLocation RPLoc) {
6606 Expr *CondExpr = static_cast<Expr*>(cond.get());
6607 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6608 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006609
Steve Naroffd04fdd52007-08-03 21:21:27 +00006610 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6611
Sebastian Redl28507842009-02-26 14:39:58 +00006612 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006613 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006614 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006615 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006616 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006617 } else {
6618 // The conditional expression is required to be a constant expression.
6619 llvm::APSInt condEval(32);
6620 SourceLocation ExpLoc;
6621 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006622 return ExprError(Diag(ExpLoc,
6623 diag::err_typecheck_choose_expr_requires_constant)
6624 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006625
Sebastian Redl28507842009-02-26 14:39:58 +00006626 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6627 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006628 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6629 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006630 }
6631
Sebastian Redlf53597f2009-03-15 17:47:39 +00006632 cond.release(); expr1.release(); expr2.release();
6633 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006634 resType, RPLoc,
6635 resType->isDependentType(),
6636 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006637}
6638
Steve Naroff4eb206b2008-09-03 18:15:37 +00006639//===----------------------------------------------------------------------===//
6640// Clang Extensions.
6641//===----------------------------------------------------------------------===//
6642
6643/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006644void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006645 // Analyze block parameters.
6646 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006647
Steve Naroff4eb206b2008-09-03 18:15:37 +00006648 // Add BSI to CurBlock.
6649 BSI->PrevBlockInfo = CurBlock;
6650 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006651
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006652 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006653 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006654 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006655 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006656 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6657 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006658
Steve Naroff090276f2008-10-10 01:28:17 +00006659 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006660 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006661 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006662}
6663
Mike Stump98eb8a72009-02-04 22:31:32 +00006664void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006665 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006666
6667 if (ParamInfo.getNumTypeObjects() == 0
6668 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006669 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006670 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6671
Mike Stump4eeab842009-04-28 01:10:27 +00006672 if (T->isArrayType()) {
6673 Diag(ParamInfo.getSourceRange().getBegin(),
6674 diag::err_block_returns_array);
6675 return;
6676 }
6677
Mike Stump98eb8a72009-02-04 22:31:32 +00006678 // The parameter list is optional, if there was none, assume ().
6679 if (!T->isFunctionType())
6680 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6681
6682 CurBlock->hasPrototype = true;
6683 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006684 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006685 if (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 }
John McCall183700f2009-09-21 23:43:11 +00006690 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006691
Chris Lattner9097af12009-04-11 19:27:54 +00006692 // Do not allow returning a objc interface by-value.
6693 if (RetTy->isObjCInterfaceType()) {
6694 Diag(ParamInfo.getSourceRange().getBegin(),
6695 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6696 return;
6697 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006698 return;
6699 }
6700
Steve Naroff4eb206b2008-09-03 18:15:37 +00006701 // Analyze arguments to block.
6702 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6703 "Not a function declarator!");
6704 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006705
Steve Naroff090276f2008-10-10 01:28:17 +00006706 CurBlock->hasPrototype = FTI.hasPrototype;
6707 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006708
Steve Naroff4eb206b2008-09-03 18:15:37 +00006709 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6710 // no arguments, not a function that takes a single void argument.
6711 if (FTI.hasPrototype &&
6712 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006713 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6714 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006715 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006716 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006717 } else if (FTI.hasPrototype) {
6718 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006719 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006720 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006721 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006722 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006723 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006724 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006725 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006726 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6727 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6728 // If this has an identifier, add it to the scope stack.
6729 if ((*AI)->getIdentifier())
6730 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006731
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006732 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006733 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006734 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006735 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006736 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006737 // FIXME: remove the attribute.
6738 }
Mike Stump1eb44332009-09-09 15:08:12 +00006739
Chris Lattner9097af12009-04-11 19:27:54 +00006740 // Analyze the return type.
6741 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006742 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006743
Chris Lattner9097af12009-04-11 19:27:54 +00006744 // Do not allow returning a objc interface by-value.
6745 if (RetTy->isObjCInterfaceType()) {
6746 Diag(ParamInfo.getSourceRange().getBegin(),
6747 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6748 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006749 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006750}
6751
6752/// ActOnBlockError - If there is an error parsing a block, this callback
6753/// is invoked to pop the information about the block from the action impl.
6754void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6755 // Ensure that CurBlock is deleted.
6756 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006757
Chris Lattner17a78302009-04-19 05:28:12 +00006758 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6759
Steve Naroff4eb206b2008-09-03 18:15:37 +00006760 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006761 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006762 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006763 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006764}
6765
6766/// ActOnBlockStmtExpr - This is called when the body of a block statement
6767/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006768Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6769 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006770 // If blocks are disabled, emit an error.
6771 if (!LangOpts.Blocks)
6772 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006773
Steve Naroff4eb206b2008-09-03 18:15:37 +00006774 // Ensure that CurBlock is deleted.
6775 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006776
Steve Naroff090276f2008-10-10 01:28:17 +00006777 PopDeclContext();
6778
Steve Naroff4eb206b2008-09-03 18:15:37 +00006779 // Pop off CurBlock, handle nested blocks.
6780 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006781
Steve Naroff4eb206b2008-09-03 18:15:37 +00006782 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006783 if (!BSI->ReturnType.isNull())
6784 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006785
Steve Naroff4eb206b2008-09-03 18:15:37 +00006786 llvm::SmallVector<QualType, 8> ArgTypes;
6787 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6788 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006789
Mike Stump56925862009-07-28 22:04:01 +00006790 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006791 QualType BlockTy;
6792 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006793 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6794 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006795 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006796 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006797 BSI->isVariadic, 0, false, false, 0, 0,
6798 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006799
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006800 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006801 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006802 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006803
Chris Lattner17a78302009-04-19 05:28:12 +00006804 // If needed, diagnose invalid gotos and switches in the block.
6805 if (CurFunctionNeedsScopeChecking)
6806 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6807 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006808
Anders Carlssone9146f22009-05-01 19:49:17 +00006809 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006810 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006811 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6812 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006813}
6814
Sebastian Redlf53597f2009-03-15 17:47:39 +00006815Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6816 ExprArg expr, TypeTy *type,
6817 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006818 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006819 Expr *E = static_cast<Expr*>(expr.get());
6820 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006821
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006822 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006823
6824 // Get the va_list type
6825 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006826 if (VaListType->isArrayType()) {
6827 // Deal with implicit array decay; for example, on x86-64,
6828 // va_list is an array, but it's supposed to decay to
6829 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006830 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006831 // Make sure the input expression also decays appropriately.
6832 UsualUnaryConversions(E);
6833 } else {
6834 // Otherwise, the va_list argument must be an l-value because
6835 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006836 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006837 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006838 return ExprError();
6839 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006840
Douglas Gregordd027302009-05-19 23:10:31 +00006841 if (!E->isTypeDependent() &&
6842 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006843 return ExprError(Diag(E->getLocStart(),
6844 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006845 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006846 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006847
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006848 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006849 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006850
Sebastian Redlf53597f2009-03-15 17:47:39 +00006851 expr.release();
6852 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6853 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006854}
6855
Sebastian Redlf53597f2009-03-15 17:47:39 +00006856Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006857 // The type of __null will be int or long, depending on the size of
6858 // pointers on the target.
6859 QualType Ty;
6860 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6861 Ty = Context.IntTy;
6862 else
6863 Ty = Context.LongTy;
6864
Sebastian Redlf53597f2009-03-15 17:47:39 +00006865 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006866}
6867
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006868static void
6869MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6870 QualType DstType,
6871 Expr *SrcExpr,
6872 CodeModificationHint &Hint) {
6873 if (!SemaRef.getLangOptions().ObjC1)
6874 return;
6875
6876 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6877 if (!PT)
6878 return;
6879
6880 // Check if the destination is of type 'id'.
6881 if (!PT->isObjCIdType()) {
6882 // Check if the destination is the 'NSString' interface.
6883 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6884 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6885 return;
6886 }
6887
6888 // Strip off any parens and casts.
6889 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6890 if (!SL || SL->isWide())
6891 return;
6892
6893 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6894}
6895
Chris Lattner5cf216b2008-01-04 18:04:52 +00006896bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6897 SourceLocation Loc,
6898 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00006899 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00006900 // Decode the result (notice that AST's are still created for extensions).
6901 bool isInvalid = false;
6902 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006903 CodeModificationHint Hint;
6904
Chris Lattner5cf216b2008-01-04 18:04:52 +00006905 switch (ConvTy) {
6906 default: assert(0 && "Unknown conversion type");
6907 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006908 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006909 DiagKind = diag::ext_typecheck_convert_pointer_int;
6910 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006911 case IntToPointer:
6912 DiagKind = diag::ext_typecheck_convert_int_pointer;
6913 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006914 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006915 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006916 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6917 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006918 case IncompatiblePointerSign:
6919 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6920 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006921 case FunctionVoidPointer:
6922 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6923 break;
6924 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006925 // If the qualifiers lost were because we were applying the
6926 // (deprecated) C++ conversion from a string literal to a char*
6927 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6928 // Ideally, this check would be performed in
6929 // CheckPointerTypesForAssignment. However, that would require a
6930 // bit of refactoring (so that the second argument is an
6931 // expression, rather than a type), which should be done as part
6932 // of a larger effort to fix CheckPointerTypesForAssignment for
6933 // C++ semantics.
6934 if (getLangOptions().CPlusPlus &&
6935 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6936 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006937 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6938 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006939 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006940 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006941 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006942 case IntToBlockPointer:
6943 DiagKind = diag::err_int_to_block_pointer;
6944 break;
6945 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006946 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006947 break;
Steve Naroff39579072008-10-14 22:18:38 +00006948 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006949 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006950 // it can give a more specific diagnostic.
6951 DiagKind = diag::warn_incompatible_qualified_id;
6952 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006953 case IncompatibleVectors:
6954 DiagKind = diag::warn_incompatible_vectors;
6955 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006956 case Incompatible:
6957 DiagKind = diag::err_typecheck_convert_incompatible;
6958 isInvalid = true;
6959 break;
6960 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006961
Douglas Gregor68647482009-12-16 03:45:30 +00006962 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006963 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006964 return isInvalid;
6965}
Anders Carlssone21555e2008-11-30 19:50:32 +00006966
Chris Lattner3bf68932009-04-25 21:59:05 +00006967bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006968 llvm::APSInt ICEResult;
6969 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6970 if (Result)
6971 *Result = ICEResult;
6972 return false;
6973 }
6974
Anders Carlssone21555e2008-11-30 19:50:32 +00006975 Expr::EvalResult EvalResult;
6976
Mike Stumpeed9cac2009-02-19 03:04:26 +00006977 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006978 EvalResult.HasSideEffects) {
6979 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6980
6981 if (EvalResult.Diag) {
6982 // We only show the note if it's not the usual "invalid subexpression"
6983 // or if it's actually in a subexpression.
6984 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6985 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6986 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6987 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006988
Anders Carlssone21555e2008-11-30 19:50:32 +00006989 return true;
6990 }
6991
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006992 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6993 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006994
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006995 if (EvalResult.Diag &&
6996 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6997 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006998
Anders Carlssone21555e2008-11-30 19:50:32 +00006999 if (Result)
7000 *Result = EvalResult.Val.getInt();
7001 return false;
7002}
Douglas Gregore0762c92009-06-19 23:52:42 +00007003
Douglas Gregor2afce722009-11-26 00:44:06 +00007004void
Mike Stump1eb44332009-09-09 15:08:12 +00007005Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007006 ExprEvalContexts.push_back(
7007 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007008}
7009
Mike Stump1eb44332009-09-09 15:08:12 +00007010void
Douglas Gregor2afce722009-11-26 00:44:06 +00007011Sema::PopExpressionEvaluationContext() {
7012 // Pop the current expression evaluation context off the stack.
7013 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7014 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007015
Douglas Gregor06d33692009-12-12 07:57:52 +00007016 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7017 if (Rec.PotentiallyReferenced) {
7018 // Mark any remaining declarations in the current position of the stack
7019 // as "referenced". If they were not meant to be referenced, semantic
7020 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7021 for (PotentiallyReferencedDecls::iterator
7022 I = Rec.PotentiallyReferenced->begin(),
7023 IEnd = Rec.PotentiallyReferenced->end();
7024 I != IEnd; ++I)
7025 MarkDeclarationReferenced(I->first, I->second);
7026 }
7027
7028 if (Rec.PotentiallyDiagnosed) {
7029 // Emit any pending diagnostics.
7030 for (PotentiallyEmittedDiagnostics::iterator
7031 I = Rec.PotentiallyDiagnosed->begin(),
7032 IEnd = Rec.PotentiallyDiagnosed->end();
7033 I != IEnd; ++I)
7034 Diag(I->first, I->second);
7035 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007036 }
7037
7038 // When are coming out of an unevaluated context, clear out any
7039 // temporaries that we may have created as part of the evaluation of
7040 // the expression in that context: they aren't relevant because they
7041 // will never be constructed.
7042 if (Rec.Context == Unevaluated &&
7043 ExprTemporaries.size() > Rec.NumTemporaries)
7044 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7045 ExprTemporaries.end());
7046
7047 // Destroy the popped expression evaluation record.
7048 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007049}
Douglas Gregore0762c92009-06-19 23:52:42 +00007050
7051/// \brief Note that the given declaration was referenced in the source code.
7052///
7053/// This routine should be invoke whenever a given declaration is referenced
7054/// in the source code, and where that reference occurred. If this declaration
7055/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7056/// C99 6.9p3), then the declaration will be marked as used.
7057///
7058/// \param Loc the location where the declaration was referenced.
7059///
7060/// \param D the declaration that has been referenced by the source code.
7061void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7062 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007063
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007064 if (D->isUsed())
7065 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007066
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007067 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7068 // template or not. The reason for this is that unevaluated expressions
7069 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7070 // -Wunused-parameters)
7071 if (isa<ParmVarDecl>(D) ||
7072 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007073 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007074
Douglas Gregore0762c92009-06-19 23:52:42 +00007075 // Do not mark anything as "used" within a dependent context; wait for
7076 // an instantiation.
7077 if (CurContext->isDependentContext())
7078 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007079
Douglas Gregor2afce722009-11-26 00:44:06 +00007080 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007081 case Unevaluated:
7082 // We are in an expression that is not potentially evaluated; do nothing.
7083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007084
Douglas Gregorac7610d2009-06-22 20:57:11 +00007085 case PotentiallyEvaluated:
7086 // We are in a potentially-evaluated expression, so this declaration is
7087 // "used"; handle this below.
7088 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007089
Douglas Gregorac7610d2009-06-22 20:57:11 +00007090 case PotentiallyPotentiallyEvaluated:
7091 // We are in an expression that may be potentially evaluated; queue this
7092 // declaration reference until we know whether the expression is
7093 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007094 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007095 return;
7096 }
Mike Stump1eb44332009-09-09 15:08:12 +00007097
Douglas Gregore0762c92009-06-19 23:52:42 +00007098 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007099 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007100 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007101 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7102 if (!Constructor->isUsed())
7103 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007104 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007105 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007106 if (!Constructor->isUsed())
7107 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7108 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007109
7110 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007111 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7112 if (Destructor->isImplicit() && !Destructor->isUsed())
7113 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007114
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007115 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7116 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7117 MethodDecl->getOverloadedOperator() == OO_Equal) {
7118 if (!MethodDecl->isUsed())
7119 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7120 }
7121 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007122 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007123 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007124 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007125 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007126 bool AlreadyInstantiated = false;
7127 if (FunctionTemplateSpecializationInfo *SpecInfo
7128 = Function->getTemplateSpecializationInfo()) {
7129 if (SpecInfo->getPointOfInstantiation().isInvalid())
7130 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007131 else if (SpecInfo->getTemplateSpecializationKind()
7132 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007133 AlreadyInstantiated = true;
7134 } else if (MemberSpecializationInfo *MSInfo
7135 = Function->getMemberSpecializationInfo()) {
7136 if (MSInfo->getPointOfInstantiation().isInvalid())
7137 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007138 else if (MSInfo->getTemplateSpecializationKind()
7139 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007140 AlreadyInstantiated = true;
7141 }
7142
7143 if (!AlreadyInstantiated)
7144 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7145 }
7146
Douglas Gregore0762c92009-06-19 23:52:42 +00007147 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007148 Function->setUsed(true);
7149 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007150 }
Mike Stump1eb44332009-09-09 15:08:12 +00007151
Douglas Gregore0762c92009-06-19 23:52:42 +00007152 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007153 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007154 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007155 Var->getInstantiatedFromStaticDataMember()) {
7156 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7157 assert(MSInfo && "Missing member specialization information?");
7158 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7159 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7160 MSInfo->setPointOfInstantiation(Loc);
7161 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7162 }
7163 }
Mike Stump1eb44332009-09-09 15:08:12 +00007164
Douglas Gregore0762c92009-06-19 23:52:42 +00007165 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007166
Douglas Gregore0762c92009-06-19 23:52:42 +00007167 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007168 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007169 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007170}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007171
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007172/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7173/// of the program being compiled.
7174///
7175/// This routine emits the given diagnostic when the code currently being
7176/// type-checked is "potentially evaluated", meaning that there is a
7177/// possibility that the code will actually be executable. Code in sizeof()
7178/// expressions, code used only during overload resolution, etc., are not
7179/// potentially evaluated. This routine will suppress such diagnostics or,
7180/// in the absolutely nutty case of potentially potentially evaluated
7181/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7182/// later.
7183///
7184/// This routine should be used for all diagnostics that describe the run-time
7185/// behavior of a program, such as passing a non-POD value through an ellipsis.
7186/// Failure to do so will likely result in spurious diagnostics or failures
7187/// during overload resolution or within sizeof/alignof/typeof/typeid.
7188bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7189 const PartialDiagnostic &PD) {
7190 switch (ExprEvalContexts.back().Context ) {
7191 case Unevaluated:
7192 // The argument will never be evaluated, so don't complain.
7193 break;
7194
7195 case PotentiallyEvaluated:
7196 Diag(Loc, PD);
7197 return true;
7198
7199 case PotentiallyPotentiallyEvaluated:
7200 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7201 break;
7202 }
7203
7204 return false;
7205}
7206
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007207bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7208 CallExpr *CE, FunctionDecl *FD) {
7209 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7210 return false;
7211
7212 PartialDiagnostic Note =
7213 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7214 << FD->getDeclName() : PDiag();
7215 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7216
7217 if (RequireCompleteType(Loc, ReturnType,
7218 FD ?
7219 PDiag(diag::err_call_function_incomplete_return)
7220 << CE->getSourceRange() << FD->getDeclName() :
7221 PDiag(diag::err_call_incomplete_return)
7222 << CE->getSourceRange(),
7223 std::make_pair(NoteLoc, Note)))
7224 return true;
7225
7226 return false;
7227}
7228
John McCall5a881bb2009-10-12 21:59:07 +00007229// Diagnose the common s/=/==/ typo. Note that adding parentheses
7230// will prevent this condition from triggering, which is what we want.
7231void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7232 SourceLocation Loc;
7233
John McCalla52ef082009-11-11 02:41:58 +00007234 unsigned diagnostic = diag::warn_condition_is_assignment;
7235
John McCall5a881bb2009-10-12 21:59:07 +00007236 if (isa<BinaryOperator>(E)) {
7237 BinaryOperator *Op = cast<BinaryOperator>(E);
7238 if (Op->getOpcode() != BinaryOperator::Assign)
7239 return;
7240
John McCallc8d8ac52009-11-12 00:06:05 +00007241 // Greylist some idioms by putting them into a warning subcategory.
7242 if (ObjCMessageExpr *ME
7243 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7244 Selector Sel = ME->getSelector();
7245
John McCallc8d8ac52009-11-12 00:06:05 +00007246 // self = [<foo> init...]
7247 if (isSelfExpr(Op->getLHS())
7248 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7249 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7250
7251 // <foo> = [<bar> nextObject]
7252 else if (Sel.isUnarySelector() &&
7253 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7254 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7255 }
John McCalla52ef082009-11-11 02:41:58 +00007256
John McCall5a881bb2009-10-12 21:59:07 +00007257 Loc = Op->getOperatorLoc();
7258 } else if (isa<CXXOperatorCallExpr>(E)) {
7259 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7260 if (Op->getOperator() != OO_Equal)
7261 return;
7262
7263 Loc = Op->getOperatorLoc();
7264 } else {
7265 // Not an assignment.
7266 return;
7267 }
7268
John McCall5a881bb2009-10-12 21:59:07 +00007269 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007270 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007271
John McCalla52ef082009-11-11 02:41:58 +00007272 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007273 << E->getSourceRange()
7274 << CodeModificationHint::CreateInsertion(Open, "(")
7275 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00007276 Diag(Loc, diag::note_condition_assign_to_comparison)
7277 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00007278}
7279
7280bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7281 DiagnoseAssignmentAsCondition(E);
7282
7283 if (!E->isTypeDependent()) {
7284 DefaultFunctionArrayConversion(E);
7285
7286 QualType T = E->getType();
7287
7288 if (getLangOptions().CPlusPlus) {
7289 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7290 return true;
7291 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7292 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7293 << T << E->getSourceRange();
7294 return true;
7295 }
7296 }
7297
7298 return false;
7299}