blob: 1d0374dcbb0620e9e8e27944c4b69d2c1c8da762 [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"
Ted Kremenek1309f9a2010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
David Chisnall0f436562009-08-17 16:35:33 +000034
Douglas Gregor48f3bb92009-02-18 21:56:37 +000035/// \brief Determine whether the use of this declaration is valid, and
36/// emit any corresponding diagnostics.
37///
38/// This routine diagnoses various problems with referencing
39/// declarations that can occur when using a declaration. For example,
40/// it might warn if a deprecated or unavailable declaration is being
41/// used, or produce an error (and return true) if a C++0x deleted
42/// function is being used.
43///
Chris Lattner52338262009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000049///
John McCall54abf7d2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000054 }
55
Chris Lattnerffb93682009-10-25 17:21:40 +000056 // See if the decl is unavailable
57 if (D->getAttr<UnavailableAttr>()) {
58 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
59 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
60 }
61
Douglas Gregor48f3bb92009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000064 if (FD->isDeleted()) {
65 Diag(Loc, diag::err_deleted_function_use);
66 Diag(D->getLocation(), diag::note_unavailable_here) << true;
67 return true;
68 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000069 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000070
Douglas Gregor48f3bb92009-02-18 21:56:37 +000071 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian5b530052009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000076/// attribute. It warns if call does not have the sentinel argument.
77///
78void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000082 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000083 int sentinelPos = attr->getSentinel();
84 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000085
Mike Stump390b4cc2009-05-16 07:39:55 +000086 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
87 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000088 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000089 bool warnNotEnoughArgs = false;
90 int isMethod = 0;
91 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
92 // skip over named parameters.
93 ObjCMethodDecl::param_iterator P, E = MD->param_end();
94 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
95 if (nullPos)
96 --nullPos;
97 else
98 ++i;
99 }
100 warnNotEnoughArgs = (P != E || i >= NumArgs);
101 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000103 // skip over named parameters.
104 ObjCMethodDecl::param_iterator P, E = FD->param_end();
105 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
106 if (nullPos)
107 --nullPos;
108 else
109 ++i;
110 }
111 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000113 // block or function pointer call.
114 QualType Ty = V->getType();
115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000116 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000119 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
120 unsigned NumArgsInProto = Proto->getNumArgs();
121 unsigned k;
122 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
123 if (nullPos)
124 --nullPos;
125 else
126 ++i;
127 }
128 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
129 }
130 if (Ty->isBlockPointerType())
131 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000132 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000133 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000134 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000135 return;
136
137 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000140 return;
141 }
142 int sentinel = i;
143 while (sentinelPos > 0 && i < NumArgs-1) {
144 --sentinelPos;
145 ++i;
146 }
147 if (sentinelPos > 0) {
148 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000150 return;
151 }
152 while (i < NumArgs-1) {
153 ++i;
154 ++sentinel;
155 }
156 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
158 (!sentinelExpr->getType()->isPointerType() ||
159 !sentinelExpr->isNullPointerConstant(Context,
160 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000161 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000163 }
164 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000165}
166
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000167SourceRange Sema::getExprRange(ExprTy *E) const {
168 Expr *Ex = (Expr *)E;
169 return Ex? Ex->getSourceRange() : SourceRange();
170}
171
Chris Lattnere7a2e912008-07-25 21:10:04 +0000172//===----------------------------------------------------------------------===//
173// Standard Promotions and Conversions
174//===----------------------------------------------------------------------===//
175
Chris Lattnere7a2e912008-07-25 21:10:04 +0000176/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
177void Sema::DefaultFunctionArrayConversion(Expr *&E) {
178 QualType Ty = E->getType();
179 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
180
Chris Lattnere7a2e912008-07-25 21:10:04 +0000181 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000182 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000183 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000184 else if (Ty->isArrayType()) {
185 // In C90 mode, arrays only promote to pointers if the array expression is
186 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
187 // type 'array of type' is converted to an expression that has type 'pointer
188 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
189 // that has type 'array of type' ...". The relevant change is "an lvalue"
190 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000191 //
192 // C++ 4.2p1:
193 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
194 // T" can be converted to an rvalue of type "pointer to T".
195 //
196 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
197 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
199 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000200 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201}
202
203/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000204/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000205/// sometimes surpressed. For example, the array->pointer conversion doesn't
206/// apply if the array is an argument to the sizeof or address (&) operators.
207/// In these instances, this routine should *not* be called.
208Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
209 QualType Ty = Expr->getType();
210 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregorfc24e442009-05-01 20:41:21 +0000212 // C99 6.3.1.1p2:
213 //
214 // The following may be used in an expression wherever an int or
215 // unsigned int may be used:
216 // - an object or expression with an integer type whose integer
217 // conversion rank is less than or equal to the rank of int
218 // and unsigned int.
219 // - A bit-field of type _Bool, int, signed int, or unsigned int.
220 //
221 // If an int can represent all values of the original type, the
222 // value is converted to an int; otherwise, it is converted to an
223 // unsigned int. These are called the integer promotions. All
224 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000225 QualType PTy = Context.isPromotableBitField(Expr);
226 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000227 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000228 return Expr;
229 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000230 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000231 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000232 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000233 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000234 }
235
Douglas Gregorfc24e442009-05-01 20:41:21 +0000236 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237 return Expr;
238}
239
Chris Lattner05faf172008-07-25 22:25:12 +0000240/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000241/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000242/// double. All other argument types are converted by UsualUnaryConversions().
243void Sema::DefaultArgumentPromotion(Expr *&Expr) {
244 QualType Ty = Expr->getType();
245 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner05faf172008-07-25 22:25:12 +0000247 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000248 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000249 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000250 return ImpCastExprToType(Expr, Context.DoubleTy,
251 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattner05faf172008-07-25 22:25:12 +0000253 UsualUnaryConversions(Expr);
254}
255
Chris Lattner312531a2009-04-12 08:11:20 +0000256/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
257/// will warn if the resulting type is not a POD type, and rejects ObjC
258/// interfaces passed by value. This returns true if the argument type is
259/// completely illegal.
260bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000261 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000263 if (Expr->getType()->isObjCInterfaceType() &&
264 DiagRuntimeBehavior(Expr->getLocStart(),
265 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
266 << Expr->getType() << CT))
267 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000268
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000269 if (!Expr->getType()->isPODType() &&
270 DiagRuntimeBehavior(Expr->getLocStart(),
271 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
272 << Expr->getType() << CT))
273 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000274
275 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000276}
277
278
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279/// UsualArithmeticConversions - Performs various conversions that are common to
280/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000281/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000282/// responsible for emitting appropriate error diagnostics.
283/// FIXME: verify the conversion rules for "complex int" are consistent with
284/// GCC.
285QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
286 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000287 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000288 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000289
290 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000291
Mike Stump1eb44332009-09-09 15:08:12 +0000292 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000293 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000294 QualType lhs =
295 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000296 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000297 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000298
299 // If both types are identical, no conversion is needed.
300 if (lhs == rhs)
301 return lhs;
302
303 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
304 // The caller can deal with this (e.g. pointer + int).
305 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
306 return lhs;
307
Douglas Gregor2d833e32009-05-02 00:36:19 +0000308 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000309 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000310 if (!LHSBitfieldPromoteTy.isNull())
311 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000312 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000313 if (!RHSBitfieldPromoteTy.isNull())
314 rhs = RHSBitfieldPromoteTy;
315
Eli Friedmana95d7572009-08-19 07:44:53 +0000316 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000317 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000318 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
319 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000320 return destType;
321}
322
Chris Lattnere7a2e912008-07-25 21:10:04 +0000323//===----------------------------------------------------------------------===//
324// Semantic Analysis for various Expression Types
325//===----------------------------------------------------------------------===//
326
327
Steve Narofff69936d2007-09-16 03:34:24 +0000328/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000329/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
330/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
331/// multiple tokens. However, the common case is that StringToks points to one
332/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000333///
334Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000335Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 assert(NumStringToks && "Must have at least one string!");
337
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000338 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000340 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000341
342 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
343 for (unsigned i = 0; i != NumStringToks; ++i)
344 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000345
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000346 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000347 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000348 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000349
350 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
351 if (getLangOptions().CPlusPlus)
352 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000353
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000354 // Get an array type for the string, according to C99 6.4.5. This includes
355 // the nul terminator character as well as the string length for pascal
356 // strings.
357 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000358 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000359 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000362 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000363 Literal.GetStringLength(),
364 Literal.AnyWide, StrTy,
365 &StringTokLocs[0],
366 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000367}
368
Chris Lattner639e2d32008-10-20 05:16:36 +0000369/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
370/// CurBlock to VD should cause it to be snapshotted (as we do for auto
371/// variables defined outside the block) or false if this is not needed (e.g.
372/// for values inside the block or for globals).
373///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000374/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
375/// up-to-date.
376///
Chris Lattner639e2d32008-10-20 05:16:36 +0000377static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
378 ValueDecl *VD) {
379 // If the value is defined inside the block, we couldn't snapshot it even if
380 // we wanted to.
381 if (CurBlock->TheDecl == VD->getDeclContext())
382 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner639e2d32008-10-20 05:16:36 +0000384 // If this is an enum constant or function, it is constant, don't snapshot.
385 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
386 return false;
387
388 // If this is a reference to an extern, static, or global variable, no need to
389 // snapshot it.
390 // FIXME: What about 'const' variables in C++?
391 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000392 if (!Var->hasLocalStorage())
393 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000395 // Blocks that have these can't be constant.
396 CurBlock->hasBlockDeclRefExprs = true;
397
398 // If we have nested blocks, the decl may be declared in an outer block (in
399 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
400 // be defined outside all of the current blocks (in which case the blocks do
401 // all get the bit). Walk the nesting chain.
402 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
403 NextBlock = NextBlock->PrevBlockInfo) {
404 // If we found the defining block for the variable, don't mark the block as
405 // having a reference outside it.
406 if (NextBlock->TheDecl == VD->getDeclContext())
407 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000409 // Otherwise, the DeclRef from the inner block causes the outer one to need
410 // a snapshot as well.
411 NextBlock->hasBlockDeclRefExprs = true;
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner639e2d32008-10-20 05:16:36 +0000414 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000415}
416
Chris Lattner639e2d32008-10-20 05:16:36 +0000417
418
Douglas Gregora2813ce2009-10-23 18:54:35 +0000419/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000420Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000421Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000422 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000423 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
424 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000425 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000426 << D->getDeclName();
427 return ExprError();
428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Anders Carlssone41590d2009-06-24 00:10:43 +0000430 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
431 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
432 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
433 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000435 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000436 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000437 << D->getIdentifier();
438 return ExprError();
439 }
440 }
441 }
442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregore0762c92009-06-19 23:52:42 +0000444 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Douglas Gregora2813ce2009-10-23 18:54:35 +0000446 return Owned(DeclRefExpr::Create(Context,
447 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
448 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000449 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000450}
451
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000452/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
453/// variable corresponding to the anonymous union or struct whose type
454/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000455static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
456 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000457 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000458 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Mike Stump390b4cc2009-05-16 07:39:55 +0000460 // FIXME: Once Decls are directly linked together, this will be an O(1)
461 // operation rather than a slow walk through DeclContext's vector (which
462 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000463 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000464 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000465 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000466 D != DEnd; ++D) {
467 if (*D == Record) {
468 // The object for the anonymous struct/union directly
469 // follows its type in the list of declarations.
470 ++D;
471 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000472 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000473 return *D;
474 }
475 }
476
477 assert(false && "Missing object for anonymous record");
478 return 0;
479}
480
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000481/// \brief Given a field that represents a member of an anonymous
482/// struct/union, build the path from that field's context to the
483/// actual member.
484///
485/// Construct the sequence of field member references we'll have to
486/// perform to get to the field in the anonymous union/struct. The
487/// list of members is built from the field outward, so traverse it
488/// backwards to go from an object in the current context to the field
489/// we found.
490///
491/// \returns The variable from which the field access should begin,
492/// for an anonymous struct/union that is not a member of another
493/// class. Otherwise, returns NULL.
494VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
495 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000496 assert(Field->getDeclContext()->isRecord() &&
497 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
498 && "Field must be stored inside an anonymous struct or union");
499
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000500 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000501 VarDecl *BaseObject = 0;
502 DeclContext *Ctx = Field->getDeclContext();
503 do {
504 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000505 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000506 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000507 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000508 else {
509 BaseObject = cast<VarDecl>(AnonObject);
510 break;
511 }
512 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000513 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000514 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000515
516 return BaseObject;
517}
518
519Sema::OwningExprResult
520Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
521 FieldDecl *Field,
522 Expr *BaseObjectExpr,
523 SourceLocation OpLoc) {
524 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000525 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 AnonFields);
527
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000528 // Build the expression that refers to the base object, from
529 // which we will build a sequence of member references to each
530 // of the anonymous union objects and, eventually, the field we
531 // found via name lookup.
532 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000533 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000534 if (BaseObject) {
535 // BaseObject is an anonymous struct/union variable (and is,
536 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000538 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000539 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000540 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000541 BaseQuals
542 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000543 } else if (BaseObjectExpr) {
544 // The caller provided the base object expression. Determine
545 // whether its a pointer and whether it adds any qualifiers to the
546 // anonymous struct/union fields we're looking into.
547 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000548 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000549 BaseObjectIsPointer = true;
550 ObjectType = ObjectPtr->getPointeeType();
551 }
John McCall0953e762009-09-24 19:53:00 +0000552 BaseQuals
553 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 } else {
555 // We've found a member of an anonymous struct/union that is
556 // inside a non-anonymous struct/union, so in a well-formed
557 // program our base object expression is "this".
558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
559 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000560 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000561 = Context.getTagDeclType(
562 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
563 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000564 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000565 == Context.getCanonicalType(ThisType)) ||
566 IsDerivedFrom(ThisType, AnonFieldType)) {
567 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000568 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000569 MD->getThisType(Context),
570 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 }
573 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000574 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
575 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000576 }
John McCall0953e762009-09-24 19:53:00 +0000577 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000578 }
579
Mike Stump1eb44332009-09-09 15:08:12 +0000580 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000581 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
582 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000583 }
584
585 // Build the implicit member references to the field of the
586 // anonymous struct/union.
587 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000588 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000589 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
590 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
591 FI != FIEnd; ++FI) {
592 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000593 Qualifiers MemberTypeQuals =
594 Context.getCanonicalType(MemberType).getQualifiers();
595
596 // CVR attributes from the base are picked up by members,
597 // except that 'mutable' members don't pick up 'const'.
598 if ((*FI)->isMutable())
599 ResultQuals.removeConst();
600
601 // GC attributes are never picked up by members.
602 ResultQuals.removeObjCGCAttr();
603
604 // TR 18037 does not allow fields to be declared with address spaces.
605 assert(!MemberTypeQuals.hasAddressSpace());
606
607 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
608 if (NewQuals != MemberTypeQuals)
609 MemberType = Context.getQualifiedType(MemberType, NewQuals);
610
Douglas Gregore0762c92009-06-19 23:52:42 +0000611 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000612 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000613 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000614 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
615 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000617 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000618 }
619
Sebastian Redlcd965b92009-01-18 18:53:16 +0000620 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000621}
622
John McCall129e2df2009-11-30 22:42:35 +0000623/// Decomposes the given name into a DeclarationName, its location, and
624/// possibly a list of template arguments.
625///
626/// If this produces template arguments, it is permitted to call
627/// DecomposeTemplateName.
628///
629/// This actually loses a lot of source location information for
630/// non-standard name kinds; we should consider preserving that in
631/// some way.
632static void DecomposeUnqualifiedId(Sema &SemaRef,
633 const UnqualifiedId &Id,
634 TemplateArgumentListInfo &Buffer,
635 DeclarationName &Name,
636 SourceLocation &NameLoc,
637 const TemplateArgumentListInfo *&TemplateArgs) {
638 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
639 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
640 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
641
642 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
643 Id.TemplateId->getTemplateArgs(),
644 Id.TemplateId->NumArgs);
645 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
646 TemplateArgsPtr.release();
647
648 TemplateName TName =
649 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
650
651 Name = SemaRef.Context.getNameForTemplate(TName);
652 NameLoc = Id.TemplateId->TemplateNameLoc;
653 TemplateArgs = &Buffer;
654 } else {
655 Name = SemaRef.GetNameFromUnqualifiedId(Id);
656 NameLoc = Id.StartLocation;
657 TemplateArgs = 0;
658 }
659}
660
661/// Decompose the given template name into a list of lookup results.
662///
663/// The unqualified ID must name a non-dependent template, which can
664/// be more easily tested by checking whether DecomposeUnqualifiedId
665/// found template arguments.
666static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
667 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
668 TemplateName TName =
669 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
670
John McCallf7a1a742009-11-24 19:00:30 +0000671 if (TemplateDecl *TD = TName.getAsTemplateDecl())
672 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000673 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
674 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
675 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000676 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000677
John McCallf7a1a742009-11-24 19:00:30 +0000678 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000679}
680
John McCall129e2df2009-11-30 22:42:35 +0000681static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
682 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
683 E = Record->bases_end(); I != E; ++I) {
684 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
685 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
686 if (!BaseRT) return false;
687
688 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
689 if (!BaseRecord->isDefinition() ||
690 !IsFullyFormedScope(SemaRef, BaseRecord))
691 return false;
692 }
693
694 return true;
695}
696
John McCalle1599ce2009-11-30 23:50:49 +0000697/// Determines whether we can lookup this id-expression now or whether
698/// we have to wait until template instantiation is complete.
699static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000700 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000701
John McCalle1599ce2009-11-30 23:50:49 +0000702 // If the qualifier scope isn't computable, it's definitely dependent.
703 if (!DC) return true;
704
705 // If the qualifier scope doesn't name a record, we can always look into it.
706 if (!isa<CXXRecordDecl>(DC)) return false;
707
708 // We can't look into record types unless they're fully-formed.
709 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
710
John McCallaa81e162009-12-01 22:10:20 +0000711 return false;
712}
John McCalle1599ce2009-11-30 23:50:49 +0000713
John McCallaa81e162009-12-01 22:10:20 +0000714/// Determines if the given class is provably not derived from all of
715/// the prospective base classes.
716static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
717 CXXRecordDecl *Record,
718 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000719 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000720 return false;
721
John McCallb1b42562009-12-01 22:28:41 +0000722 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
723 if (!RD) return false;
724 Record = cast<CXXRecordDecl>(RD);
725
John McCallaa81e162009-12-01 22:10:20 +0000726 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
727 E = Record->bases_end(); I != E; ++I) {
728 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
729 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
730 if (!BaseRT) return false;
731
732 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000733 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
734 return false;
735 }
736
737 return true;
738}
739
John McCall144238e2009-12-02 20:26:00 +0000740/// Determines if this is an instance member of a class.
741static bool IsInstanceMember(NamedDecl *D) {
John McCall3b4294e2009-12-16 12:17:52 +0000742 assert(D->isCXXClassMember() &&
John McCallaa81e162009-12-01 22:10:20 +0000743 "checking whether non-member is instance member");
744
745 if (isa<FieldDecl>(D)) return true;
746
747 if (isa<CXXMethodDecl>(D))
748 return !cast<CXXMethodDecl>(D)->isStatic();
749
750 if (isa<FunctionTemplateDecl>(D)) {
751 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
752 return !cast<CXXMethodDecl>(D)->isStatic();
753 }
754
755 return false;
756}
757
758enum IMAKind {
759 /// The reference is definitely not an instance member access.
760 IMA_Static,
761
762 /// The reference may be an implicit instance member access.
763 IMA_Mixed,
764
765 /// The reference may be to an instance member, but it is invalid if
766 /// so, because the context is not an instance method.
767 IMA_Mixed_StaticContext,
768
769 /// The reference may be to an instance member, but it is invalid if
770 /// so, because the context is from an unrelated class.
771 IMA_Mixed_Unrelated,
772
773 /// The reference is definitely an implicit instance member access.
774 IMA_Instance,
775
776 /// The reference may be to an unresolved using declaration.
777 IMA_Unresolved,
778
779 /// The reference may be to an unresolved using declaration and the
780 /// context is not an instance method.
781 IMA_Unresolved_StaticContext,
782
783 /// The reference is to a member of an anonymous structure in a
784 /// non-class context.
785 IMA_AnonymousMember,
786
787 /// All possible referrents are instance members and the current
788 /// context is not an instance method.
789 IMA_Error_StaticContext,
790
791 /// All possible referrents are instance members of an unrelated
792 /// class.
793 IMA_Error_Unrelated
794};
795
796/// The given lookup names class member(s) and is not being used for
797/// an address-of-member expression. Classify the type of access
798/// according to whether it's possible that this reference names an
799/// instance member. This is best-effort; it is okay to
800/// conservatively answer "yes", in which case some errors will simply
801/// not be caught until template-instantiation.
802static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
803 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000804 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000805
806 bool isStaticContext =
807 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
808 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
809
810 if (R.isUnresolvableResult())
811 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
812
813 // Collect all the declaring classes of instance members we find.
814 bool hasNonInstance = false;
815 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
816 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
817 NamedDecl *D = (*I)->getUnderlyingDecl();
818 if (IsInstanceMember(D)) {
819 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
820
821 // If this is a member of an anonymous record, move out to the
822 // innermost non-anonymous struct or union. If there isn't one,
823 // that's a special case.
824 while (R->isAnonymousStructOrUnion()) {
825 R = dyn_cast<CXXRecordDecl>(R->getParent());
826 if (!R) return IMA_AnonymousMember;
827 }
828 Classes.insert(R->getCanonicalDecl());
829 }
830 else
831 hasNonInstance = true;
832 }
833
834 // If we didn't find any instance members, it can't be an implicit
835 // member reference.
836 if (Classes.empty())
837 return IMA_Static;
838
839 // If the current context is not an instance method, it can't be
840 // an implicit member reference.
841 if (isStaticContext)
842 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
843
844 // If we can prove that the current context is unrelated to all the
845 // declaring classes, it can't be an implicit member reference (in
846 // which case it's an error if any of those members are selected).
847 if (IsProvablyNotDerivedFrom(SemaRef,
848 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
849 Classes))
850 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
851
852 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
853}
854
855/// Diagnose a reference to a field with no object available.
856static void DiagnoseInstanceReference(Sema &SemaRef,
857 const CXXScopeSpec &SS,
858 const LookupResult &R) {
859 SourceLocation Loc = R.getNameLoc();
860 SourceRange Range(Loc);
861 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
862
863 if (R.getAsSingle<FieldDecl>()) {
864 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
865 if (MD->isStatic()) {
866 // "invalid use of member 'x' in static member function"
867 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
868 << Range << R.getLookupName();
869 return;
870 }
871 }
872
873 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
874 << R.getLookupName() << Range;
875 return;
876 }
877
878 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000879}
880
John McCall578b69b2009-12-16 08:11:27 +0000881/// Diagnose an empty lookup.
882///
883/// \return false if new lookup candidates were found
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000884bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCall578b69b2009-12-16 08:11:27 +0000885 LookupResult &R) {
886 DeclarationName Name = R.getLookupName();
887
John McCall578b69b2009-12-16 08:11:27 +0000888 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000889 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000890 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
891 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000892 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000893 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000894 diagnostic_suggest = diag::err_undeclared_use_suggest;
895 }
John McCall578b69b2009-12-16 08:11:27 +0000896
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000897 // If the original lookup was an unqualified lookup, fake an
898 // unqualified lookup. This is useful when (for example) the
899 // original lookup would not have found something because it was a
900 // dependent name.
901 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
902 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000903 if (isa<CXXRecordDecl>(DC)) {
904 LookupQualifiedName(R, DC);
905
906 if (!R.empty()) {
907 // Don't give errors about ambiguities in this lookup.
908 R.suppressDiagnostics();
909
910 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
911 bool isInstance = CurMethod &&
912 CurMethod->isInstance() &&
913 DC == CurMethod->getParent();
914
915 // Give a code modification hint to insert 'this->'.
916 // TODO: fixit for inserting 'Base<T>::' in the other cases.
917 // Actually quite difficult!
918 if (isInstance)
919 Diag(R.getNameLoc(), diagnostic) << Name
920 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
921 "this->");
922 else
923 Diag(R.getNameLoc(), diagnostic) << Name;
924
925 // Do we really want to note all of these?
926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
927 Diag((*I)->getLocation(), diag::note_dependent_var_use);
928
929 // Tell the callee to try to recover.
930 return false;
931 }
932 }
933 }
934
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000935 // We didn't find anything, so try to correct for a typo.
Douglas Gregord203a162010-01-01 00:15:04 +0000936 if (S && CorrectTypo(R, S, &SS)) {
937 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
938 if (SS.isEmpty())
939 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
940 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000941 R.getLookupName().getAsString());
Douglas Gregord203a162010-01-01 00:15:04 +0000942 else
943 Diag(R.getNameLoc(), diag::err_no_member_suggest)
944 << Name << computeDeclContext(SS, false) << R.getLookupName()
945 << SS.getRange()
946 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000947 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000948 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
949 Diag(ND->getLocation(), diag::note_previous_decl)
950 << ND->getDeclName();
951
Douglas Gregord203a162010-01-01 00:15:04 +0000952 // Tell the callee to try to recover.
953 return false;
954 }
955
956 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
957 // FIXME: If we ended up with a typo for a type name or
958 // Objective-C class name, we're in trouble because the parser
959 // is in the wrong place to recover. Suggest the typo
960 // correction, but don't make it a fix-it since we're not going
961 // to recover well anyway.
962 if (SS.isEmpty())
963 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
964 else
965 Diag(R.getNameLoc(), diag::err_no_member_suggest)
966 << Name << computeDeclContext(SS, false) << R.getLookupName()
967 << SS.getRange();
968
969 // Don't try to recover; it won't work.
970 return true;
971 }
972
973 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000974 }
975
976 // Emit a special diagnostic for failed member lookups.
977 // FIXME: computing the declaration context might fail here (?)
978 if (!SS.isEmpty()) {
979 Diag(R.getNameLoc(), diag::err_no_member)
980 << Name << computeDeclContext(SS, false)
981 << SS.getRange();
982 return true;
983 }
984
John McCall578b69b2009-12-16 08:11:27 +0000985 // Give up, we can't recover.
986 Diag(R.getNameLoc(), diagnostic) << Name;
987 return true;
988}
989
John McCallf7a1a742009-11-24 19:00:30 +0000990Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
991 const CXXScopeSpec &SS,
992 UnqualifiedId &Id,
993 bool HasTrailingLParen,
994 bool isAddressOfOperand) {
995 assert(!(isAddressOfOperand && HasTrailingLParen) &&
996 "cannot be direct & operand and have a trailing lparen");
997
998 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000999 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001000
John McCall129e2df2009-11-30 22:42:35 +00001001 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001002
1003 // Decompose the UnqualifiedId into the following data.
1004 DeclarationName Name;
1005 SourceLocation NameLoc;
1006 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +00001007 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1008 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001009
Douglas Gregor10c42622008-11-18 15:03:34 +00001010 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +00001011
John McCallf7a1a742009-11-24 19:00:30 +00001012 // C++ [temp.dep.expr]p3:
1013 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001014 // -- an identifier that was declared with a dependent type,
1015 // (note: handled after lookup)
1016 // -- a template-id that is dependent,
1017 // (note: handled in BuildTemplateIdExpr)
1018 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001019 // -- a nested-name-specifier that contains a class-name that
1020 // names a dependent type.
1021 // Determine whether this is a member of an unknown specialization;
1022 // we need to handle these differently.
Douglas Gregor48026d22010-01-11 18:40:55 +00001023 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1024 Name.getCXXNameType()->isDependentType()) ||
1025 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCallf7a1a742009-11-24 19:00:30 +00001026 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +00001027 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001028 TemplateArgs);
1029 }
John McCallba135432009-11-21 08:51:07 +00001030
John McCallf7a1a742009-11-24 19:00:30 +00001031 // Perform the required lookup.
1032 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1033 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001034 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001035 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001036 } else {
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001037 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1038 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
John McCallf7a1a742009-11-24 19:00:30 +00001040 // If this reference is in an Objective-C method, then we need to do
1041 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001042 if (IvarLookupFollowUp) {
1043 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001044 if (E.isInvalid())
1045 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001046
John McCallf7a1a742009-11-24 19:00:30 +00001047 Expr *Ex = E.takeAs<Expr>();
1048 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001049 }
Chris Lattner8a934232008-03-31 00:36:02 +00001050 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001051
John McCallf7a1a742009-11-24 19:00:30 +00001052 if (R.isAmbiguous())
1053 return ExprError();
1054
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001055 // Determine whether this name might be a candidate for
1056 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001057 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001058
John McCallf7a1a742009-11-24 19:00:30 +00001059 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001061 // in C90, extension in C99, forbidden in C++).
1062 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1063 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1064 if (D) R.addDecl(D);
1065 }
1066
1067 // If this name wasn't predeclared and if this is not a function
1068 // call, diagnose the problem.
1069 if (R.empty()) {
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001070 if (DiagnoseEmptyLookup(S, SS, R))
John McCall578b69b2009-12-16 08:11:27 +00001071 return ExprError();
1072
1073 assert(!R.empty() &&
1074 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001075
1076 // If we found an Objective-C instance variable, let
1077 // LookupInObjCMethod build the appropriate expression to
1078 // reference the ivar.
1079 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1080 R.clear();
1081 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1082 assert(E.isInvalid() || E.get());
1083 return move(E);
1084 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 }
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
John McCallf7a1a742009-11-24 19:00:30 +00001088 // This is guaranteed from this point on.
1089 assert(!R.empty() || ADL);
1090
1091 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001092 // Warn about constructs like:
1093 // if (void *X = foo()) { ... } else { X }.
1094 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregor751f9a42009-06-30 15:47:41 +00001096 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1097 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001098 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001099 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001100 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001101 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001102 << Var->getDeclName()
1103 << (Var->getType()->isPointerType()? 2 :
1104 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001105 break;
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001108 // Move to the parent of this scope.
1109 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001110 }
1111 }
John McCallf7a1a742009-11-24 19:00:30 +00001112 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001113 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1114 // C99 DR 316 says that, if a function type comes from a
1115 // function definition (without a prototype), that type is only
1116 // used for checking compatibility. Therefore, when referencing
1117 // the function, we pretend that we don't have the full function
1118 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001119 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001120 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001121
Douglas Gregor751f9a42009-06-30 15:47:41 +00001122 QualType T = Func->getType();
1123 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001124 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001125 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001126 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001127 }
1128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCallaa81e162009-12-01 22:10:20 +00001130 // Check whether this might be a C++ implicit instance member access.
1131 // C++ [expr.prim.general]p6:
1132 // Within the definition of a non-static member function, an
1133 // identifier that names a non-static member is transformed to a
1134 // class member access expression.
1135 // But note that &SomeClass::foo is grammatically distinct, even
1136 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001137 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001138 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001139 if (!isAbstractMemberPointer)
1140 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001141 }
1142
John McCallf7a1a742009-11-24 19:00:30 +00001143 if (TemplateArgs)
1144 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001145
John McCallf7a1a742009-11-24 19:00:30 +00001146 return BuildDeclarationNameExpr(SS, R, ADL);
1147}
1148
John McCall3b4294e2009-12-16 12:17:52 +00001149/// Builds an expression which might be an implicit member expression.
1150Sema::OwningExprResult
1151Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1152 LookupResult &R,
1153 const TemplateArgumentListInfo *TemplateArgs) {
1154 switch (ClassifyImplicitMemberAccess(*this, R)) {
1155 case IMA_Instance:
1156 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1157
1158 case IMA_AnonymousMember:
1159 assert(R.isSingleResult());
1160 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1161 R.getAsSingle<FieldDecl>());
1162
1163 case IMA_Mixed:
1164 case IMA_Mixed_Unrelated:
1165 case IMA_Unresolved:
1166 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1167
1168 case IMA_Static:
1169 case IMA_Mixed_StaticContext:
1170 case IMA_Unresolved_StaticContext:
1171 if (TemplateArgs)
1172 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1173 return BuildDeclarationNameExpr(SS, R, false);
1174
1175 case IMA_Error_StaticContext:
1176 case IMA_Error_Unrelated:
1177 DiagnoseInstanceReference(*this, SS, R);
1178 return ExprError();
1179 }
1180
1181 llvm_unreachable("unexpected instance member access kind");
1182 return ExprError();
1183}
1184
John McCall129e2df2009-11-30 22:42:35 +00001185/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1186/// declaration name, generally during template instantiation.
1187/// There's a large number of things which don't need to be done along
1188/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001189Sema::OwningExprResult
1190Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1191 DeclarationName Name,
1192 SourceLocation NameLoc) {
1193 DeclContext *DC;
1194 if (!(DC = computeDeclContext(SS, false)) ||
1195 DC->isDependentContext() ||
1196 RequireCompleteDeclContext(SS))
1197 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1198
1199 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1200 LookupQualifiedName(R, DC);
1201
1202 if (R.isAmbiguous())
1203 return ExprError();
1204
1205 if (R.empty()) {
1206 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1207 return ExprError();
1208 }
1209
1210 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1211}
1212
1213/// LookupInObjCMethod - The parser has read a name in, and Sema has
1214/// detected that we're currently inside an ObjC method. Perform some
1215/// additional lookup.
1216///
1217/// Ideally, most of this would be done by lookup, but there's
1218/// actually quite a lot of extra work involved.
1219///
1220/// Returns a null sentinel to indicate trivial success.
1221Sema::OwningExprResult
1222Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001223 IdentifierInfo *II,
1224 bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001225 SourceLocation Loc = Lookup.getNameLoc();
1226
1227 // There are two cases to handle here. 1) scoped lookup could have failed,
1228 // in which case we should look for an ivar. 2) scoped lookup could have
1229 // found a decl, but that decl is outside the current instance method (i.e.
1230 // a global variable). In these two cases, we do a lookup for an ivar with
1231 // this name, if the lookup sucedes, we replace it our current decl.
1232
1233 // If we're in a class method, we don't normally want to look for
1234 // ivars. But if we don't find anything else, and there's an
1235 // ivar, that's an error.
1236 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1237
1238 bool LookForIvars;
1239 if (Lookup.empty())
1240 LookForIvars = true;
1241 else if (IsClassMethod)
1242 LookForIvars = false;
1243 else
1244 LookForIvars = (Lookup.isSingleResult() &&
1245 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1246
1247 if (LookForIvars) {
1248 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1249 ObjCInterfaceDecl *ClassDeclared;
1250 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1251 // Diagnose using an ivar in a class method.
1252 if (IsClassMethod)
1253 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1254 << IV->getDeclName());
1255
1256 // If we're referencing an invalid decl, just return this as a silent
1257 // error node. The error diagnostic was already emitted on the decl.
1258 if (IV->isInvalidDecl())
1259 return ExprError();
1260
1261 // Check if referencing a field with __attribute__((deprecated)).
1262 if (DiagnoseUseOfDecl(IV, Loc))
1263 return ExprError();
1264
1265 // Diagnose the use of an ivar outside of the declaring class.
1266 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1267 ClassDeclared != IFace)
1268 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1269
1270 // FIXME: This should use a new expr for a direct reference, don't
1271 // turn this into Self->ivar, just return a BareIVarExpr or something.
1272 IdentifierInfo &II = Context.Idents.get("self");
1273 UnqualifiedId SelfName;
1274 SelfName.setIdentifier(&II, SourceLocation());
1275 CXXScopeSpec SelfScopeSpec;
1276 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1277 SelfName, false, false);
1278 MarkDeclarationReferenced(Loc, IV);
1279 return Owned(new (Context)
1280 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1281 SelfExpr.takeAs<Expr>(), true, true));
1282 }
1283 } else if (getCurMethodDecl()->isInstanceMethod()) {
1284 // We should warn if a local variable hides an ivar.
1285 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1286 ObjCInterfaceDecl *ClassDeclared;
1287 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1288 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1289 IFace == ClassDeclared)
1290 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1291 }
1292 }
1293
1294 // Needed to implement property "super.method" notation.
1295 if (Lookup.empty() && II->isStr("super")) {
1296 QualType T;
1297
1298 if (getCurMethodDecl()->isInstanceMethod())
1299 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1300 getCurMethodDecl()->getClassInterface()));
1301 else
1302 T = Context.getObjCClassType();
1303 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1304 }
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001305 if (Lookup.empty() && II && AllowBuiltinCreation) {
1306 // FIXME. Consolidate this with similar code in LookupName.
1307 if (unsigned BuiltinID = II->getBuiltinID()) {
1308 if (!(getLangOptions().CPlusPlus &&
1309 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1310 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1311 S, Lookup.isForRedeclaration(),
1312 Lookup.getNameLoc());
1313 if (D) Lookup.addDecl(D);
1314 }
1315 }
1316 }
John McCallf7a1a742009-11-24 19:00:30 +00001317 // Sentinel value saying that we didn't do anything special.
1318 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001319}
John McCallba135432009-11-21 08:51:07 +00001320
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001321/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001322bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001323Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1324 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001325 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001326 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001327 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001328 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001329 if (DestType->isDependentType() || From->getType()->isDependentType())
1330 return false;
1331 QualType FromRecordType = From->getType();
1332 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001333 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001334 DestType = Context.getPointerType(DestType);
1335 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001336 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001337 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1338 CheckDerivedToBaseConversion(FromRecordType,
1339 DestRecordType,
1340 From->getSourceRange().getBegin(),
1341 From->getSourceRange()))
1342 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001343 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1344 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001345 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001346 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001347}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001348
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001349/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001350static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001351 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001352 SourceLocation Loc, QualType Ty,
1353 const TemplateArgumentListInfo *TemplateArgs = 0) {
1354 NestedNameSpecifier *Qualifier = 0;
1355 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001356 if (SS.isSet()) {
1357 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1358 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001359 }
Mike Stump1eb44332009-09-09 15:08:12 +00001360
John McCallf7a1a742009-11-24 19:00:30 +00001361 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1362 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001363}
1364
John McCallaa81e162009-12-01 22:10:20 +00001365/// Builds an implicit member access expression. The current context
1366/// is known to be an instance method, and the given unqualified lookup
1367/// set is known to contain only instance members, at least one of which
1368/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001369Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001370Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1371 LookupResult &R,
1372 const TemplateArgumentListInfo *TemplateArgs,
1373 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001374 assert(!R.empty() && !R.isAmbiguous());
1375
John McCallba135432009-11-21 08:51:07 +00001376 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001377
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001378 // We may have found a field within an anonymous union or struct
1379 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001380 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001381 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001382 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001383 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001384 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001385
John McCallaa81e162009-12-01 22:10:20 +00001386 // If this is known to be an instance access, go ahead and build a
1387 // 'this' expression now.
1388 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1389 Expr *This = 0; // null signifies implicit access
1390 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001391 SourceLocation Loc = R.getNameLoc();
1392 if (SS.getRange().isValid())
1393 Loc = SS.getRange().getBegin();
1394 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001395 }
1396
John McCallaa81e162009-12-01 22:10:20 +00001397 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1398 /*OpLoc*/ SourceLocation(),
1399 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001400 SS,
1401 /*FirstQualifierInScope*/ 0,
1402 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001403}
1404
John McCallf7a1a742009-11-24 19:00:30 +00001405bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001406 const LookupResult &R,
1407 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001408 // Only when used directly as the postfix-expression of a call.
1409 if (!HasTrailingLParen)
1410 return false;
1411
1412 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001413 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001414 return false;
1415
1416 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001417 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001418 return false;
1419
1420 // Turn off ADL when we find certain kinds of declarations during
1421 // normal lookup:
1422 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1423 NamedDecl *D = *I;
1424
1425 // C++0x [basic.lookup.argdep]p3:
1426 // -- a declaration of a class member
1427 // Since using decls preserve this property, we check this on the
1428 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001429 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001430 return false;
1431
1432 // C++0x [basic.lookup.argdep]p3:
1433 // -- a block-scope function declaration that is not a
1434 // using-declaration
1435 // NOTE: we also trigger this for function templates (in fact, we
1436 // don't check the decl type at all, since all other decl types
1437 // turn off ADL anyway).
1438 if (isa<UsingShadowDecl>(D))
1439 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1440 else if (D->getDeclContext()->isFunctionOrMethod())
1441 return false;
1442
1443 // C++0x [basic.lookup.argdep]p3:
1444 // -- a declaration that is neither a function or a function
1445 // template
1446 // And also for builtin functions.
1447 if (isa<FunctionDecl>(D)) {
1448 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1449
1450 // But also builtin functions.
1451 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1452 return false;
1453 } else if (!isa<FunctionTemplateDecl>(D))
1454 return false;
1455 }
1456
1457 return true;
1458}
1459
1460
John McCallba135432009-11-21 08:51:07 +00001461/// Diagnoses obvious problems with the use of the given declaration
1462/// as an expression. This is only actually called for lookups that
1463/// were not overloaded, and it doesn't promise that the declaration
1464/// will in fact be used.
1465static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1466 if (isa<TypedefDecl>(D)) {
1467 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1468 return true;
1469 }
1470
1471 if (isa<ObjCInterfaceDecl>(D)) {
1472 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1473 return true;
1474 }
1475
1476 if (isa<NamespaceDecl>(D)) {
1477 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1478 return true;
1479 }
1480
1481 return false;
1482}
1483
1484Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001485Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001486 LookupResult &R,
1487 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001488 // If this is a single, fully-resolved result and we don't need ADL,
1489 // just build an ordinary singleton decl ref.
1490 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001491 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001492
1493 // We only need to check the declaration if there's exactly one
1494 // result, because in the overloaded case the results can only be
1495 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001496 if (R.isSingleResult() &&
1497 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001498 return ExprError();
1499
John McCallf7a1a742009-11-24 19:00:30 +00001500 bool Dependent
1501 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001502 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001503 = UnresolvedLookupExpr::Create(Context, Dependent,
1504 (NestedNameSpecifier*) SS.getScopeRep(),
1505 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001506 R.getLookupName(), R.getNameLoc(),
1507 NeedsADL, R.isOverloadedResult());
1508 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1509 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001510
1511 return Owned(ULE);
1512}
1513
1514
1515/// \brief Complete semantic analysis for a reference to the given declaration.
1516Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001517Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001518 SourceLocation Loc, NamedDecl *D) {
1519 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001520 assert(!isa<FunctionTemplateDecl>(D) &&
1521 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001522
1523 if (CheckDeclInExpr(*this, Loc, D))
1524 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001525
Douglas Gregor9af2f522009-12-01 16:58:18 +00001526 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1527 // Specifically diagnose references to class templates that are missing
1528 // a template argument list.
1529 Diag(Loc, diag::err_template_decl_ref)
1530 << Template << SS.getRange();
1531 Diag(Template->getLocation(), diag::note_template_decl_here);
1532 return ExprError();
1533 }
1534
1535 // Make sure that we're referring to a value.
1536 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1537 if (!VD) {
1538 Diag(Loc, diag::err_ref_non_value)
1539 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001540 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001541 return ExprError();
1542 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001543
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001544 // Check whether this declaration can be used. Note that we suppress
1545 // this check when we're going to perform argument-dependent lookup
1546 // on this function name, because this might not be the function
1547 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001548 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001549 return ExprError();
1550
Steve Naroffdd972f22008-09-05 22:11:13 +00001551 // Only create DeclRefExpr's for valid Decl's.
1552 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001553 return ExprError();
1554
Chris Lattner639e2d32008-10-20 05:16:36 +00001555 // If the identifier reference is inside a block, and it refers to a value
1556 // that is outside the block, create a BlockDeclRefExpr instead of a
1557 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1558 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001559 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001560 // We do not do this for things like enum constants, global variables, etc,
1561 // as they do not get snapshotted.
1562 //
1563 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001564 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1565 Diag(Loc, diag::err_ref_vm_type);
1566 Diag(D->getLocation(), diag::note_declared_at);
1567 return ExprError();
1568 }
1569
Mike Stump28497342010-01-05 03:10:36 +00001570 if (VD->getType()->isArrayType()) {
1571 Diag(Loc, diag::err_ref_array_type);
1572 Diag(D->getLocation(), diag::note_declared_at);
1573 return ExprError();
1574 }
1575
Douglas Gregore0762c92009-06-19 23:52:42 +00001576 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001577 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001578 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001579 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001580 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001581 // This is to record that a 'const' was actually synthesize and added.
1582 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001583 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Eli Friedman5fdeae12009-03-22 23:00:19 +00001585 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001586 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001587 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001588 }
1589 // If this reference is not in a block or if the referenced variable is
1590 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001591
John McCallf7a1a742009-11-24 19:00:30 +00001592 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593}
1594
Sebastian Redlcd965b92009-01-18 18:53:16 +00001595Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1596 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001597 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001598
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001600 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001601 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1602 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1603 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001605
Chris Lattnerfa28b302008-01-12 08:14:25 +00001606 // Pre-defined identifiers are of type char[x], where x is the length of the
1607 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Anders Carlsson3a082d82009-09-08 18:24:21 +00001609 Decl *currentDecl = getCurFunctionOrMethodDecl();
1610 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001611 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001612 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001613 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001614
Anders Carlsson773f3972009-09-11 01:22:35 +00001615 QualType ResTy;
1616 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1617 ResTy = Context.DependentTy;
1618 } else {
1619 unsigned Length =
1620 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001621
Anders Carlsson773f3972009-09-11 01:22:35 +00001622 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001623 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001624 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1625 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001626 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001627}
1628
Sebastian Redlcd965b92009-01-18 18:53:16 +00001629Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 llvm::SmallString<16> CharBuffer;
1631 CharBuffer.resize(Tok.getLength());
1632 const char *ThisTokBegin = &CharBuffer[0];
1633 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1636 Tok.getLocation(), PP);
1637 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001638 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001639
Chris Lattnere8337df2009-12-30 21:19:39 +00001640 QualType Ty;
1641 if (!getLangOptions().CPlusPlus)
1642 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1643 else if (Literal.isWide())
1644 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1645 else
1646 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001647
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001648 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1649 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001650 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001651}
1652
Sebastian Redlcd965b92009-01-18 18:53:16 +00001653Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1654 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1656 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001657 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001658 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001659 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001660 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 }
Ted Kremenek28396602009-01-13 23:19:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001664 // Add padding so that NumericLiteralParser can overread by one character.
1665 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // Get the spelling of the token, which eliminates trigraphs, etc.
1669 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001670
Mike Stump1eb44332009-09-09 15:08:12 +00001671 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 Tok.getLocation(), PP);
1673 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001674 return ExprError();
1675
Chris Lattner5d661452007-08-26 03:42:43 +00001676 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001677
Chris Lattner5d661452007-08-26 03:42:43 +00001678 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001679 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001680 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001681 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001682 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001683 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001684 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001685 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001686
1687 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1688
John McCall94c939d2009-12-24 09:08:04 +00001689 using llvm::APFloat;
1690 APFloat Val(Format);
1691
1692 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001693
1694 // Overflow is always an error, but underflow is only an error if
1695 // we underflowed to zero (APFloat reports denormals as underflow).
1696 if ((result & APFloat::opOverflow) ||
1697 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001698 unsigned diagnostic;
1699 llvm::SmallVector<char, 20> buffer;
1700 if (result & APFloat::opOverflow) {
1701 diagnostic = diag::err_float_overflow;
1702 APFloat::getLargest(Format).toString(buffer);
1703 } else {
1704 diagnostic = diag::err_float_underflow;
1705 APFloat::getSmallest(Format).toString(buffer);
1706 }
1707
1708 Diag(Tok.getLocation(), diagnostic)
1709 << Ty
1710 << llvm::StringRef(buffer.data(), buffer.size());
1711 }
1712
1713 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001714 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001715
Chris Lattner5d661452007-08-26 03:42:43 +00001716 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001717 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001718 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001719 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001720
Neil Boothb9449512007-08-29 22:00:19 +00001721 // long long is a C99 feature.
1722 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001723 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001724 Diag(Tok.getLocation(), diag::ext_longlong);
1725
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001727 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001728
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 if (Literal.GetIntegerValue(ResultVal)) {
1730 // If this value didn't fit into uintmax_t, warn and force to ull.
1731 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001732 Ty = Context.UnsignedLongLongTy;
1733 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001734 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 } else {
1736 // If this value fits into a ULL, try to figure out what else it fits into
1737 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001738
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1740 // be an unsigned int.
1741 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1742
1743 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001744 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001745 if (!Literal.isLong && !Literal.isLongLong) {
1746 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001747 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001748
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // Does it fit in a unsigned int?
1750 if (ResultVal.isIntN(IntSize)) {
1751 // Does it fit in a signed int?
1752 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001753 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001755 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001756 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001759
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001761 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001762 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001763
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 // Does it fit in a unsigned long?
1765 if (ResultVal.isIntN(LongSize)) {
1766 // Does it fit in a signed long?
1767 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001768 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001770 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001771 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001773 }
1774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001776 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001777 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // Does it fit in a unsigned long long?
1780 if (ResultVal.isIntN(LongLongSize)) {
1781 // Does it fit in a signed long long?
1782 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001783 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001785 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001786 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 }
1788 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001789
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 // If we still couldn't decide a type, we probably have something that
1791 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001792 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001794 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001795 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001797
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001798 if (ResultVal.getBitWidth() != Width)
1799 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001801 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001803
Chris Lattner5d661452007-08-26 03:42:43 +00001804 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1805 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001806 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001807 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001808
1809 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001810}
1811
Sebastian Redlcd965b92009-01-18 18:53:16 +00001812Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1813 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001814 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001815 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001816 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001817}
1818
1819/// The UsualUnaryConversions() function is *not* called by this routine.
1820/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001821bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001822 SourceLocation OpLoc,
1823 const SourceRange &ExprRange,
1824 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001825 if (exprType->isDependentType())
1826 return false;
1827
Sebastian Redl5d484e82009-11-23 17:18:46 +00001828 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1829 // the result is the size of the referenced type."
1830 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1831 // result shall be the alignment of the referenced type."
1832 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1833 exprType = Ref->getPointeeType();
1834
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001836 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001837 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001838 if (isSizeof)
1839 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1840 return false;
1841 }
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Chris Lattner1efaa952009-04-24 00:30:45 +00001843 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001844 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001845 Diag(OpLoc, diag::ext_sizeof_void_type)
1846 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001847 return false;
1848 }
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Chris Lattner1efaa952009-04-24 00:30:45 +00001850 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00001851 PDiag(diag::err_sizeof_alignof_incomplete_type)
1852 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001853 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Chris Lattner1efaa952009-04-24 00:30:45 +00001855 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001856 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001857 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001858 << exprType << isSizeof << ExprRange;
1859 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001860 }
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Chris Lattner1efaa952009-04-24 00:30:45 +00001862 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001863}
1864
Chris Lattner31e21e02009-01-24 20:17:12 +00001865bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1866 const SourceRange &ExprRange) {
1867 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001868
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001870 if (isa<DeclRefExpr>(E))
1871 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001872
1873 // Cannot know anything else if the expression is dependent.
1874 if (E->isTypeDependent())
1875 return false;
1876
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001877 if (E->getBitField()) {
1878 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1879 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001880 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001881
1882 // Alignment of a field access is always okay, so long as it isn't a
1883 // bit-field.
1884 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001885 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001886 return false;
1887
Chris Lattner31e21e02009-01-24 20:17:12 +00001888 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1889}
1890
Douglas Gregorba498172009-03-13 21:01:28 +00001891/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001892Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001893Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001894 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001895 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001896 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001897 return ExprError();
1898
John McCalla93c9342009-12-07 02:54:59 +00001899 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001900
Douglas Gregorba498172009-03-13 21:01:28 +00001901 if (!T->isDependentType() &&
1902 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1903 return ExprError();
1904
1905 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001906 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001907 Context.getSizeType(), OpLoc,
1908 R.getEnd()));
1909}
1910
1911/// \brief Build a sizeof or alignof expression given an expression
1912/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001913Action::OwningExprResult
1914Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001915 bool isSizeOf, SourceRange R) {
1916 // Verify that the operand is valid.
1917 bool isInvalid = false;
1918 if (E->isTypeDependent()) {
1919 // Delay type-checking for type-dependent expressions.
1920 } else if (!isSizeOf) {
1921 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001922 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001923 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1924 isInvalid = true;
1925 } else {
1926 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1927 }
1928
1929 if (isInvalid)
1930 return ExprError();
1931
1932 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1933 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1934 Context.getSizeType(), OpLoc,
1935 R.getEnd()));
1936}
1937
Sebastian Redl05189992008-11-11 17:56:53 +00001938/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1939/// the same for @c alignof and @c __alignof
1940/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001941Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001942Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1943 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001945 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001946
Sebastian Redl05189992008-11-11 17:56:53 +00001947 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001948 TypeSourceInfo *TInfo;
1949 (void) GetTypeFromParser(TyOrEx, &TInfo);
1950 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001951 }
Sebastian Redl05189992008-11-11 17:56:53 +00001952
Douglas Gregorba498172009-03-13 21:01:28 +00001953 Expr *ArgEx = (Expr *)TyOrEx;
1954 Action::OwningExprResult Result
1955 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1956
1957 if (Result.isInvalid())
1958 DeleteExpr(ArgEx);
1959
1960 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001961}
1962
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001963QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001964 if (V->isTypeDependent())
1965 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Chris Lattnercc26ed72007-08-26 05:39:26 +00001967 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001968 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001969 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattnercc26ed72007-08-26 05:39:26 +00001971 // Otherwise they pass through real integer and floating point types here.
1972 if (V->getType()->isArithmeticType())
1973 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Chris Lattnercc26ed72007-08-26 05:39:26 +00001975 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001976 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1977 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001978 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001979}
1980
1981
Reid Spencer5f016e22007-07-11 17:01:13 +00001982
Sebastian Redl0eb23302009-01-19 00:08:26 +00001983Action::OwningExprResult
1984Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1985 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 UnaryOperator::Opcode Opc;
1987 switch (Kind) {
1988 default: assert(0 && "Unknown unary op!");
1989 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1990 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1991 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001992
Eli Friedmane4216e92009-11-18 03:38:04 +00001993 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001994}
1995
Sebastian Redl0eb23302009-01-19 00:08:26 +00001996Action::OwningExprResult
1997Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1998 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001999 // Since this might be a postfix expression, get rid of ParenListExprs.
2000 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2001
Sebastian Redl0eb23302009-01-19 00:08:26 +00002002 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2003 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor337c6b92008-11-19 17:17:41 +00002005 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002006 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2007 Base.release();
2008 Idx.release();
2009 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2010 Context.DependentTy, RLoc));
2011 }
2012
Mike Stump1eb44332009-09-09 15:08:12 +00002013 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002014 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002015 LHSExp->getType()->isEnumeralType() ||
2016 RHSExp->getType()->isRecordType() ||
2017 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002018 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002019 }
2020
Sebastian Redlf322ed62009-10-29 20:17:01 +00002021 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2022}
2023
2024
2025Action::OwningExprResult
2026Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2027 ExprArg Idx, SourceLocation RLoc) {
2028 Expr *LHSExp = static_cast<Expr*>(Base.get());
2029 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2030
Chris Lattner12d9ff62007-07-16 00:14:47 +00002031 // Perform default conversions.
2032 DefaultFunctionArrayConversion(LHSExp);
2033 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002034
Chris Lattner12d9ff62007-07-16 00:14:47 +00002035 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002036
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002038 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002039 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002041 Expr *BaseExpr, *IndexExpr;
2042 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002043 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2044 BaseExpr = LHSExp;
2045 IndexExpr = RHSExp;
2046 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002047 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002048 BaseExpr = LHSExp;
2049 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002050 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002051 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002052 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002053 BaseExpr = RHSExp;
2054 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002055 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002056 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002057 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002058 BaseExpr = LHSExp;
2059 IndexExpr = RHSExp;
2060 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002061 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002062 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002063 // Handle the uncommon case of "123[Ptr]".
2064 BaseExpr = RHSExp;
2065 IndexExpr = LHSExp;
2066 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002067 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002068 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002069 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002070
Chris Lattner12d9ff62007-07-16 00:14:47 +00002071 // FIXME: need to deal with const...
2072 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002073 } else if (LHSTy->isArrayType()) {
2074 // If we see an array that wasn't promoted by
2075 // DefaultFunctionArrayConversion, it must be an array that
2076 // wasn't promoted because of the C90 rule that doesn't
2077 // allow promoting non-lvalue arrays. Warn, then
2078 // force the promotion here.
2079 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2080 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002081 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2082 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002083 LHSTy = LHSExp->getType();
2084
2085 BaseExpr = LHSExp;
2086 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002087 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002088 } else if (RHSTy->isArrayType()) {
2089 // Same as previous, except for 123[f().a] case
2090 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2091 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002092 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2093 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002094 RHSTy = RHSExp->getType();
2095
2096 BaseExpr = RHSExp;
2097 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002098 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002100 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2101 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002102 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002104 if (!(IndexExpr->getType()->isIntegerType() &&
2105 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002106 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2107 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002108
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002109 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002110 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2111 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002112 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2113
Douglas Gregore7450f52009-03-24 19:52:54 +00002114 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002115 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2116 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002117 // incomplete types are not object types.
2118 if (ResultType->isFunctionType()) {
2119 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2120 << ResultType << BaseExpr->getSourceRange();
2121 return ExprError();
2122 }
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Douglas Gregore7450f52009-03-24 19:52:54 +00002124 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002125 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002126 PDiag(diag::err_subscript_incomplete_type)
2127 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002128 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Chris Lattner1efaa952009-04-24 00:30:45 +00002130 // Diagnose bad cases where we step over interface counts.
2131 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2132 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2133 << ResultType << BaseExpr->getSourceRange();
2134 return ExprError();
2135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Sebastian Redl0eb23302009-01-19 00:08:26 +00002137 Base.release();
2138 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002139 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002140 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002141}
2142
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002143QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002144CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002145 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002146 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002147 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2148 // see FIXME there.
2149 //
2150 // FIXME: This logic can be greatly simplified by splitting it along
2151 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002152 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002153
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002154 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002155 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002156
Mike Stumpeed9cac2009-02-19 03:04:26 +00002157 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002158 // special names that indicate a subset of exactly half the elements are
2159 // to be selected.
2160 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002161
Nate Begeman353417a2009-01-18 01:47:54 +00002162 // This flag determines whether or not CompName has an 's' char prefix,
2163 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002164 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002165
2166 // Check that we've found one of the special components, or that the component
2167 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002168 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002169 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2170 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002171 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002172 do
2173 compStr++;
2174 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002175 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002176 do
2177 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002178 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002179 }
Nate Begeman353417a2009-01-18 01:47:54 +00002180
Mike Stumpeed9cac2009-02-19 03:04:26 +00002181 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002182 // We didn't get to the end of the string. This means the component names
2183 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002184 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2185 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002186 return QualType();
2187 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002188
Nate Begeman353417a2009-01-18 01:47:54 +00002189 // Ensure no component accessor exceeds the width of the vector type it
2190 // operates on.
2191 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002192 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002193
2194 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002195 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002196
2197 while (*compStr) {
2198 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2199 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2200 << baseType << SourceRange(CompLoc);
2201 return QualType();
2202 }
2203 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002204 }
Nate Begeman8a997642008-05-09 06:41:27 +00002205
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002206 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002207 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002208 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002209 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002210 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002211 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002212 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002213 if (HexSwizzle)
2214 CompSize--;
2215
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002216 if (CompSize == 1)
2217 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002218
Nate Begeman213541a2008-04-18 23:10:10 +00002219 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002220 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002221 // diagostics look bad. We want extended vector types to appear built-in.
2222 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2223 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2224 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002225 }
2226 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002227}
2228
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002229static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002230 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002231 const Selector &Sel,
2232 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Anders Carlsson8f28f992009-08-26 18:25:21 +00002234 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002235 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002236 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002237 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002239 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2240 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002241 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002242 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002243 return D;
2244 }
2245 return 0;
2246}
2247
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002248static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002249 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002250 const Selector &Sel,
2251 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002252 // Check protocols on qualified interfaces.
2253 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002254 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002255 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002256 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002257 GDecl = PD;
2258 break;
2259 }
2260 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002261 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002262 GDecl = OMD;
2263 break;
2264 }
2265 }
2266 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002267 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002268 E = QIdTy->qual_end(); I != E; ++I) {
2269 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002270 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002271 if (GDecl)
2272 return GDecl;
2273 }
2274 }
2275 return GDecl;
2276}
Chris Lattner76a642f2009-02-15 22:43:40 +00002277
John McCall129e2df2009-11-30 22:42:35 +00002278Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002279Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2280 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002281 const CXXScopeSpec &SS,
2282 NamedDecl *FirstQualifierInScope,
2283 DeclarationName Name, SourceLocation NameLoc,
2284 const TemplateArgumentListInfo *TemplateArgs) {
2285 Expr *BaseExpr = Base.takeAs<Expr>();
2286
2287 // Even in dependent contexts, try to diagnose base expressions with
2288 // obviously wrong types, e.g.:
2289 //
2290 // T* t;
2291 // t.f;
2292 //
2293 // In Obj-C++, however, the above expression is valid, since it could be
2294 // accessing the 'f' property if T is an Obj-C interface. The extra check
2295 // allows this, while still reporting an error if T is a struct pointer.
2296 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002297 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002298 if (PT && (!getLangOptions().ObjC1 ||
2299 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002300 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002301 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002302 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002303 return ExprError();
2304 }
2305 }
2306
Douglas Gregor48026d22010-01-11 18:40:55 +00002307 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall129e2df2009-11-30 22:42:35 +00002308
2309 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2310 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002311 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002312 IsArrow, OpLoc,
2313 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2314 SS.getRange(),
2315 FirstQualifierInScope,
2316 Name, NameLoc,
2317 TemplateArgs));
2318}
2319
2320/// We know that the given qualified member reference points only to
2321/// declarations which do not belong to the static type of the base
2322/// expression. Diagnose the problem.
2323static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2324 Expr *BaseExpr,
2325 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002326 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002327 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002328 // If this is an implicit member access, use a different set of
2329 // diagnostics.
2330 if (!BaseExpr)
2331 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002332
2333 // FIXME: this is an exceedingly lame diagnostic for some of the more
2334 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002335 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002336 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002337 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002338}
2339
2340// Check whether the declarations we found through a nested-name
2341// specifier in a member expression are actually members of the base
2342// type. The restriction here is:
2343//
2344// C++ [expr.ref]p2:
2345// ... In these cases, the id-expression shall name a
2346// member of the class or of one of its base classes.
2347//
2348// So it's perfectly legitimate for the nested-name specifier to name
2349// an unrelated class, and for us to find an overload set including
2350// decls from classes which are not superclasses, as long as the decl
2351// we actually pick through overload resolution is from a superclass.
2352bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2353 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002354 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002355 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002356 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2357 if (!BaseRT) {
2358 // We can't check this yet because the base type is still
2359 // dependent.
2360 assert(BaseType->isDependentType());
2361 return false;
2362 }
2363 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002364
2365 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002366 // If this is an implicit member reference and we find a
2367 // non-instance member, it's not an error.
2368 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2369 return false;
John McCall129e2df2009-11-30 22:42:35 +00002370
John McCallaa81e162009-12-01 22:10:20 +00002371 // Note that we use the DC of the decl, not the underlying decl.
2372 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2373 while (RecordD->isAnonymousStructOrUnion())
2374 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2375
2376 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2377 MemberRecord.insert(RecordD->getCanonicalDecl());
2378
2379 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2380 return false;
2381 }
2382
John McCall2f841ba2009-12-02 03:53:29 +00002383 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002384 return true;
2385}
2386
2387static bool
2388LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2389 SourceRange BaseRange, const RecordType *RTy,
2390 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2391 RecordDecl *RDecl = RTy->getDecl();
2392 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2393 PDiag(diag::err_typecheck_incomplete_tag)
2394 << BaseRange))
2395 return true;
2396
2397 DeclContext *DC = RDecl;
2398 if (SS.isSet()) {
2399 // If the member name was a qualified-id, look into the
2400 // nested-name-specifier.
2401 DC = SemaRef.computeDeclContext(SS, false);
2402
John McCall2f841ba2009-12-02 03:53:29 +00002403 if (SemaRef.RequireCompleteDeclContext(SS)) {
2404 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2405 << SS.getRange() << DC;
2406 return true;
2407 }
2408
John McCallaa81e162009-12-01 22:10:20 +00002409 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2410
2411 if (!isa<TypeDecl>(DC)) {
2412 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2413 << DC << SS.getRange();
2414 return true;
John McCall129e2df2009-11-30 22:42:35 +00002415 }
2416 }
2417
John McCallaa81e162009-12-01 22:10:20 +00002418 // The record definition is complete, now look up the member.
2419 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002420
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002421 if (!R.empty())
2422 return false;
2423
2424 // We didn't find anything with the given name, so try to correct
2425 // for typos.
2426 DeclarationName Name = R.getLookupName();
2427 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2428 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2429 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2430 << Name << DC << R.getLookupName() << SS.getRange()
2431 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2432 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002433 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2434 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2435 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002436 return false;
2437 } else {
2438 R.clear();
2439 }
2440
John McCall129e2df2009-11-30 22:42:35 +00002441 return false;
2442}
2443
2444Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002445Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002446 SourceLocation OpLoc, bool IsArrow,
2447 const CXXScopeSpec &SS,
2448 NamedDecl *FirstQualifierInScope,
2449 DeclarationName Name, SourceLocation NameLoc,
2450 const TemplateArgumentListInfo *TemplateArgs) {
2451 Expr *Base = BaseArg.takeAs<Expr>();
2452
John McCall2f841ba2009-12-02 03:53:29 +00002453 if (BaseType->isDependentType() ||
2454 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002455 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002456 IsArrow, OpLoc,
2457 SS, FirstQualifierInScope,
2458 Name, NameLoc,
2459 TemplateArgs);
2460
2461 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002462
John McCallaa81e162009-12-01 22:10:20 +00002463 // Implicit member accesses.
2464 if (!Base) {
2465 QualType RecordTy = BaseType;
2466 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2467 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2468 RecordTy->getAs<RecordType>(),
2469 OpLoc, SS))
2470 return ExprError();
2471
2472 // Explicit member accesses.
2473 } else {
2474 OwningExprResult Result =
2475 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00002476 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCallaa81e162009-12-01 22:10:20 +00002477
2478 if (Result.isInvalid()) {
2479 Owned(Base);
2480 return ExprError();
2481 }
2482
2483 if (Result.get())
2484 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002485 }
2486
John McCallaa81e162009-12-01 22:10:20 +00002487 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002488 OpLoc, IsArrow, SS, FirstQualifierInScope,
2489 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002490}
2491
2492Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002493Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2494 SourceLocation OpLoc, bool IsArrow,
2495 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002496 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002497 LookupResult &R,
2498 const TemplateArgumentListInfo *TemplateArgs) {
2499 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002500 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002501 if (IsArrow) {
2502 assert(BaseType->isPointerType());
2503 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2504 }
2505
2506 NestedNameSpecifier *Qualifier =
2507 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2508 DeclarationName MemberName = R.getLookupName();
2509 SourceLocation MemberLoc = R.getNameLoc();
2510
2511 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002512 return ExprError();
2513
John McCall129e2df2009-11-30 22:42:35 +00002514 if (R.empty()) {
2515 // Rederive where we looked up.
2516 DeclContext *DC = (SS.isSet()
2517 ? computeDeclContext(SS, false)
2518 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002519
John McCall129e2df2009-11-30 22:42:35 +00002520 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002521 << MemberName << DC
2522 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002523 return ExprError();
2524 }
2525
John McCallc2233c52010-01-15 08:34:02 +00002526 // Diagnose lookups that find only declarations from a non-base
2527 // type. This is possible for either qualified lookups (which may
2528 // have been qualified with an unrelated type) or implicit member
2529 // expressions (which were found with unqualified lookup and thus
2530 // may have come from an enclosing scope). Note that it's okay for
2531 // lookup to find declarations from a non-base type as long as those
2532 // aren't the ones picked by overload resolution.
2533 if ((SS.isSet() || !BaseExpr ||
2534 (isa<CXXThisExpr>(BaseExpr) &&
2535 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2536 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002537 return ExprError();
2538
2539 // Construct an unresolved result if we in fact got an unresolved
2540 // result.
2541 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002542 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002543 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002544 R.isUnresolvableResult() ||
2545 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002546
2547 UnresolvedMemberExpr *MemExpr
2548 = UnresolvedMemberExpr::Create(Context, Dependent,
2549 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002550 BaseExpr, BaseExprType,
2551 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002552 Qualifier, SS.getRange(),
2553 MemberName, MemberLoc,
2554 TemplateArgs);
2555 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2556 MemExpr->addDecl(*I);
2557
2558 return Owned(MemExpr);
2559 }
2560
2561 assert(R.isSingleResult());
2562 NamedDecl *MemberDecl = R.getFoundDecl();
2563
2564 // FIXME: diagnose the presence of template arguments now.
2565
2566 // If the decl being referenced had an error, return an error for this
2567 // sub-expr without emitting another error, in order to avoid cascading
2568 // error cases.
2569 if (MemberDecl->isInvalidDecl())
2570 return ExprError();
2571
John McCallaa81e162009-12-01 22:10:20 +00002572 // Handle the implicit-member-access case.
2573 if (!BaseExpr) {
2574 // If this is not an instance member, convert to a non-member access.
2575 if (!IsInstanceMember(MemberDecl))
2576 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2577
Douglas Gregor828a1972010-01-07 23:12:05 +00002578 SourceLocation Loc = R.getNameLoc();
2579 if (SS.getRange().isValid())
2580 Loc = SS.getRange().getBegin();
2581 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002582 }
2583
John McCall129e2df2009-11-30 22:42:35 +00002584 bool ShouldCheckUse = true;
2585 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2586 // Don't diagnose the use of a virtual member function unless it's
2587 // explicitly qualified.
2588 if (MD->isVirtual() && !SS.isSet())
2589 ShouldCheckUse = false;
2590 }
2591
2592 // Check the use of this member.
2593 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2594 Owned(BaseExpr);
2595 return ExprError();
2596 }
2597
2598 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2599 // We may have found a field within an anonymous union or struct
2600 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002601 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2602 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002603 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2604 BaseExpr, OpLoc);
2605
2606 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2607 QualType MemberType = FD->getType();
2608 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2609 MemberType = Ref->getPointeeType();
2610 else {
2611 Qualifiers BaseQuals = BaseType.getQualifiers();
2612 BaseQuals.removeObjCGCAttr();
2613 if (FD->isMutable()) BaseQuals.removeConst();
2614
2615 Qualifiers MemberQuals
2616 = Context.getCanonicalType(MemberType).getQualifiers();
2617
2618 Qualifiers Combined = BaseQuals + MemberQuals;
2619 if (Combined != MemberQuals)
2620 MemberType = Context.getQualifiedType(MemberType, Combined);
2621 }
2622
2623 MarkDeclarationReferenced(MemberLoc, FD);
2624 if (PerformObjectMemberConversion(BaseExpr, FD))
2625 return ExprError();
2626 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2627 FD, MemberLoc, MemberType));
2628 }
2629
2630 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2631 MarkDeclarationReferenced(MemberLoc, Var);
2632 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2633 Var, MemberLoc,
2634 Var->getType().getNonReferenceType()));
2635 }
2636
2637 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2638 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2639 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2640 MemberFn, MemberLoc,
2641 MemberFn->getType()));
2642 }
2643
2644 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2645 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2646 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2647 Enum, MemberLoc, Enum->getType()));
2648 }
2649
2650 Owned(BaseExpr);
2651
2652 if (isa<TypeDecl>(MemberDecl))
2653 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2654 << MemberName << int(IsArrow));
2655
2656 // We found a declaration kind that we didn't expect. This is a
2657 // generic error message that tells the user that she can't refer
2658 // to this member with '.' or '->'.
2659 return ExprError(Diag(MemberLoc,
2660 diag::err_typecheck_member_reference_unknown)
2661 << MemberName << int(IsArrow));
2662}
2663
2664/// Look up the given member of the given non-type-dependent
2665/// expression. This can return in one of two ways:
2666/// * If it returns a sentinel null-but-valid result, the caller will
2667/// assume that lookup was performed and the results written into
2668/// the provided structure. It will take over from there.
2669/// * Otherwise, the returned expression will be produced in place of
2670/// an ordinary member expression.
2671///
2672/// The ObjCImpDecl bit is a gross hack that will need to be properly
2673/// fixed for ObjC++.
2674Sema::OwningExprResult
2675Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002676 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002677 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002678 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002679 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Steve Naroff3cc4af82007-12-16 21:42:28 +00002681 // Perform default conversions.
2682 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002683
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002684 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002685 assert(!BaseType->isDependentType());
2686
2687 DeclarationName MemberName = R.getLookupName();
2688 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002689
2690 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002691 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002692 // function. Suggest the addition of those parentheses, build the
2693 // call, and continue on.
2694 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2695 if (const FunctionProtoType *Fun
2696 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2697 QualType ResultTy = Fun->getResultType();
2698 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002699 ((!IsArrow && ResultTy->isRecordType()) ||
2700 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002701 ResultTy->getAs<PointerType>()->getPointeeType()
2702 ->isRecordType()))) {
2703 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2704 Diag(Loc, diag::err_member_reference_needs_call)
2705 << QualType(Fun, 0)
2706 << CodeModificationHint::CreateInsertion(Loc, "()");
2707
2708 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002709 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002710 MultiExprArg(*this, 0, 0), 0, Loc);
2711 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002712 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002713
2714 BaseExpr = NewBase.takeAs<Expr>();
2715 DefaultFunctionArrayConversion(BaseExpr);
2716 BaseType = BaseExpr->getType();
2717 }
2718 }
2719 }
2720
David Chisnall0f436562009-08-17 16:35:33 +00002721 // If this is an Objective-C pseudo-builtin and a definition is provided then
2722 // use that.
2723 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002724 if (IsArrow) {
2725 // Handle the following exceptional case PObj->isa.
2726 if (const ObjCObjectPointerType *OPT =
2727 BaseType->getAs<ObjCObjectPointerType>()) {
2728 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2729 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002730 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2731 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002732 }
2733 }
David Chisnall0f436562009-08-17 16:35:33 +00002734 // We have an 'id' type. Rather than fall through, we check if this
2735 // is a reference to 'isa'.
2736 if (BaseType != Context.ObjCIdRedefinitionType) {
2737 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002738 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002739 }
David Chisnall0f436562009-08-17 16:35:33 +00002740 }
John McCall129e2df2009-11-30 22:42:35 +00002741
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002742 // If this is an Objective-C pseudo-builtin and a definition is provided then
2743 // use that.
2744 if (Context.isObjCSelType(BaseType)) {
2745 // We have an 'SEL' type. Rather than fall through, we check if this
2746 // is a reference to 'sel_id'.
2747 if (BaseType != Context.ObjCSelRedefinitionType) {
2748 BaseType = Context.ObjCSelRedefinitionType;
2749 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2750 }
2751 }
John McCall129e2df2009-11-30 22:42:35 +00002752
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002753 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002754
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002755 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002756 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002757 // Also must look for a getter name which uses property syntax.
2758 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2759 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2760 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2761 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2762 ObjCMethodDecl *Getter;
2763 // FIXME: need to also look locally in the implementation.
2764 if ((Getter = IFace->lookupClassMethod(Sel))) {
2765 // Check the use of this method.
2766 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2767 return ExprError();
2768 }
2769 // If we found a getter then this may be a valid dot-reference, we
2770 // will look for the matching setter, in case it is needed.
2771 Selector SetterSel =
2772 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2773 PP.getSelectorTable(), Member);
2774 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2775 if (!Setter) {
2776 // If this reference is in an @implementation, also check for 'private'
2777 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002778 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002779 }
2780 // Look through local category implementations associated with the class.
2781 if (!Setter)
2782 Setter = IFace->getCategoryClassMethod(SetterSel);
2783
2784 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2785 return ExprError();
2786
2787 if (Getter || Setter) {
2788 QualType PType;
2789
2790 if (Getter)
2791 PType = Getter->getResultType();
2792 else
2793 // Get the expression type from Setter's incoming parameter.
2794 PType = (*(Setter->param_end() -1))->getType();
2795 // FIXME: we must check that the setter has property type.
2796 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2797 PType,
2798 Setter, MemberLoc, BaseExpr));
2799 }
2800 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2801 << MemberName << BaseType);
2802 }
2803 }
2804
2805 if (BaseType->isObjCClassType() &&
2806 BaseType != Context.ObjCClassRedefinitionType) {
2807 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002808 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002809 }
Mike Stump1eb44332009-09-09 15:08:12 +00002810
John McCall129e2df2009-11-30 22:42:35 +00002811 if (IsArrow) {
2812 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002813 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002814 else if (BaseType->isObjCObjectPointerType())
2815 ;
John McCall812c1542009-12-07 22:46:59 +00002816 else if (BaseType->isRecordType()) {
2817 // Recover from arrow accesses to records, e.g.:
2818 // struct MyRecord foo;
2819 // foo->bar
2820 // This is actually well-formed in C++ if MyRecord has an
2821 // overloaded operator->, but that should have been dealt with
2822 // by now.
2823 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2824 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2825 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2826 IsArrow = false;
2827 } else {
John McCall129e2df2009-11-30 22:42:35 +00002828 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2829 << BaseType << BaseExpr->getSourceRange();
2830 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002831 }
John McCall812c1542009-12-07 22:46:59 +00002832 } else {
2833 // Recover from dot accesses to pointers, e.g.:
2834 // type *foo;
2835 // foo.bar
2836 // This is actually well-formed in two cases:
2837 // - 'type' is an Objective C type
2838 // - 'bar' is a pseudo-destructor name which happens to refer to
2839 // the appropriate pointer type
2840 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2841 const PointerType *PT = BaseType->getAs<PointerType>();
2842 if (PT && PT->getPointeeType()->isRecordType()) {
2843 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2844 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2845 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2846 BaseType = PT->getPointeeType();
2847 IsArrow = true;
2848 }
2849 }
John McCall129e2df2009-11-30 22:42:35 +00002850 }
John McCall812c1542009-12-07 22:46:59 +00002851
John McCall129e2df2009-11-30 22:42:35 +00002852 // Handle field access to simple records. This also handles access
2853 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002854 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002855 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2856 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002857 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002858 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002859 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002860
Douglas Gregora71d8192009-09-04 17:36:40 +00002861 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2862 // into a record type was handled above, any destructor we see here is a
2863 // pseudo-destructor.
2864 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2865 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002866 // The left hand side of the dot operator shall be of scalar type. The
2867 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002868 // type.
2869 if (!BaseType->isScalarType())
2870 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2871 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002872
Douglas Gregora71d8192009-09-04 17:36:40 +00002873 // [...] The type designated by the pseudo-destructor-name shall be the
2874 // same as the object type.
2875 if (!MemberName.getCXXNameType()->isDependentType() &&
2876 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2877 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2878 << BaseType << MemberName.getCXXNameType()
2879 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002880
2881 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002882 // the form
2883 //
Mike Stump1eb44332009-09-09 15:08:12 +00002884 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2885 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002886 // shall designate the same scalar type.
2887 //
2888 // FIXME: DPG can't see any way to trigger this particular clause, so it
2889 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Douglas Gregora71d8192009-09-04 17:36:40 +00002891 // FIXME: We've lost the precise spelling of the type by going through
2892 // DeclarationName. Can we do better?
2893 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002894 IsArrow, OpLoc,
2895 (NestedNameSpecifier *) SS.getScopeRep(),
2896 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002897 MemberName.getCXXNameType(),
2898 MemberLoc));
2899 }
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Chris Lattnera38e6b12008-07-21 04:59:05 +00002901 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2902 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002903 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2904 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002905 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002906 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002907 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002908 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002909 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2910
Steve Naroffc70e8d92009-07-16 00:25:06 +00002911 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2912 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002913 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002914
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002915 if (!IV) {
2916 // Attempt to correct for typos in ivar names.
2917 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2918 LookupMemberName);
2919 if (CorrectTypo(Res, 0, 0, IDecl) &&
2920 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2921 Diag(R.getNameLoc(),
2922 diag::err_typecheck_member_reference_ivar_suggest)
2923 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2924 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2925 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002926 Diag(IV->getLocation(), diag::note_previous_decl)
2927 << IV->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002928 }
2929 }
2930
Steve Naroffc70e8d92009-07-16 00:25:06 +00002931 if (IV) {
2932 // If the decl being referenced had an error, return an error for this
2933 // sub-expr without emitting another error, in order to avoid cascading
2934 // error cases.
2935 if (IV->isInvalidDecl())
2936 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002937
Steve Naroffc70e8d92009-07-16 00:25:06 +00002938 // Check whether we can reference this field.
2939 if (DiagnoseUseOfDecl(IV, MemberLoc))
2940 return ExprError();
2941 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2942 IV->getAccessControl() != ObjCIvarDecl::Package) {
2943 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2944 if (ObjCMethodDecl *MD = getCurMethodDecl())
2945 ClassOfMethodDecl = MD->getClassInterface();
2946 else if (ObjCImpDecl && getCurFunctionDecl()) {
2947 // Case of a c-function declared inside an objc implementation.
2948 // FIXME: For a c-style function nested inside an objc implementation
2949 // class, there is no implementation context available, so we pass
2950 // down the context as argument to this routine. Ideally, this context
2951 // need be passed down in the AST node and somehow calculated from the
2952 // AST for a function decl.
2953 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002954 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002955 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2956 ClassOfMethodDecl = IMPD->getClassInterface();
2957 else if (ObjCCategoryImplDecl* CatImplClass =
2958 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2959 ClassOfMethodDecl = CatImplClass->getClassInterface();
2960 }
Mike Stump1eb44332009-09-09 15:08:12 +00002961
2962 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2963 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002964 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002965 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002966 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002967 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2968 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002969 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002970 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002971 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002972
2973 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2974 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002975 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002976 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002977 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002978 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002979 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002980 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002981 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002982 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002983 if (!IsArrow && (BaseType->isObjCIdType() ||
2984 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002985 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002986 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Steve Naroff14108da2009-07-10 23:34:53 +00002988 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002989 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002990 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2991 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2992 // Check the use of this declaration
2993 if (DiagnoseUseOfDecl(PD, MemberLoc))
2994 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Steve Naroff14108da2009-07-10 23:34:53 +00002996 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2997 MemberLoc, BaseExpr));
2998 }
2999 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3000 // Check the use of this method.
3001 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3002 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Steve Naroff14108da2009-07-10 23:34:53 +00003004 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00003005 OMD->getResultType(),
3006 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00003007 NULL, 0));
3008 }
3009 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003010
Steve Naroff14108da2009-07-10 23:34:53 +00003011 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003012 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003013 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00003014 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3015 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00003016 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00003017 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00003018 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3019 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003020 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Daniel Dunbar2307d312008-09-03 01:05:41 +00003022 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003023 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003024 // Check whether we can reference this property.
3025 if (DiagnoseUseOfDecl(PD, MemberLoc))
3026 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003027 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003028 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003029 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00003030 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3031 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003032 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00003033 MemberLoc, BaseExpr));
3034 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003035 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003036 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3037 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003038 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003039 // Check whether we can reference this property.
3040 if (DiagnoseUseOfDecl(PD, MemberLoc))
3041 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00003042
Steve Naroff6ece14c2009-01-21 00:14:39 +00003043 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00003044 MemberLoc, BaseExpr));
3045 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003046 // If that failed, look for an "implicit" property by seeing if the nullary
3047 // selector is implemented.
3048
3049 // FIXME: The logic for looking up nullary and unary selectors should be
3050 // shared with the code in ActOnInstanceMessage.
3051
Anders Carlsson8f28f992009-08-26 18:25:21 +00003052 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003053 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003054
Daniel Dunbar2307d312008-09-03 01:05:41 +00003055 // If this reference is in an @implementation, check for 'private' methods.
3056 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00003057 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003058
Steve Naroff7692ed62008-10-22 19:16:27 +00003059 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003060 if (!Getter)
3061 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003062 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003063 // Check if we can reference this property.
3064 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3065 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00003066 }
3067 // If we found a getter then this may be a valid dot-reference, we
3068 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00003069 Selector SetterSel =
3070 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00003071 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003072 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003073 if (!Setter) {
3074 // If this reference is in an @implementation, also check for 'private'
3075 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003076 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003077 }
3078 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003079 if (!Setter)
3080 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003081
Steve Naroff1ca66942009-03-11 13:48:17 +00003082 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3083 return ExprError();
3084
Fariborz Jahaniandd0cb902010-01-19 17:48:02 +00003085 if (Getter) {
Steve Naroff1ca66942009-03-11 13:48:17 +00003086 QualType PType;
Fariborz Jahaniandd0cb902010-01-19 17:48:02 +00003087 PType = Getter->getResultType();
Fariborz Jahanian09105f52009-08-20 17:02:02 +00003088 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00003089 Setter, MemberLoc, BaseExpr));
3090 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003091
3092 // Attempt to correct for typos in property names.
3093 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3094 LookupOrdinaryName);
3095 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3096 Res.getAsSingle<ObjCPropertyDecl>()) {
3097 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3098 << MemberName << BaseType << Res.getLookupName()
3099 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3100 Res.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003101 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3102 Diag(Property->getLocation(), diag::note_previous_decl)
3103 << Property->getDeclName();
3104
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003105 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCallc2233c52010-01-15 08:34:02 +00003106 ObjCImpDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003107 }
3108
Sebastian Redl0eb23302009-01-19 00:08:26 +00003109 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003110 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00003111 }
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Steve Narofff242b1b2009-07-24 17:54:45 +00003113 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003114 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003115 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003116 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003117 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003118 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003119
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003120 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003121 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003122 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003123 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3124 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003125 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003126 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003127 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003128 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003129
Douglas Gregor214f31a2009-03-27 06:00:30 +00003130 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3131 << BaseType << BaseExpr->getSourceRange();
3132
Douglas Gregor214f31a2009-03-27 06:00:30 +00003133 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003134}
3135
John McCall129e2df2009-11-30 22:42:35 +00003136static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3137 SourceLocation NameLoc,
3138 Sema::ExprArg MemExpr) {
3139 Expr *E = (Expr *) MemExpr.get();
3140 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3141 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00003142 << isa<CXXPseudoDestructorExpr>(E)
3143 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3144
John McCall129e2df2009-11-30 22:42:35 +00003145 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3146 move(MemExpr),
3147 /*LPLoc*/ ExpectedLParenLoc,
3148 Sema::MultiExprArg(SemaRef, 0, 0),
3149 /*CommaLocs*/ 0,
3150 /*RPLoc*/ ExpectedLParenLoc);
3151}
3152
3153/// The main callback when the parser finds something like
3154/// expression . [nested-name-specifier] identifier
3155/// expression -> [nested-name-specifier] identifier
3156/// where 'identifier' encompasses a fairly broad spectrum of
3157/// possibilities, including destructor and operator references.
3158///
3159/// \param OpKind either tok::arrow or tok::period
3160/// \param HasTrailingLParen whether the next token is '(', which
3161/// is used to diagnose mis-uses of special members that can
3162/// only be called
3163/// \param ObjCImpDecl the current ObjC @implementation decl;
3164/// this is an ugly hack around the fact that ObjC @implementations
3165/// aren't properly put in the context chain
3166Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3167 SourceLocation OpLoc,
3168 tok::TokenKind OpKind,
3169 const CXXScopeSpec &SS,
3170 UnqualifiedId &Id,
3171 DeclPtrTy ObjCImpDecl,
3172 bool HasTrailingLParen) {
3173 if (SS.isSet() && SS.isInvalid())
3174 return ExprError();
3175
3176 TemplateArgumentListInfo TemplateArgsBuffer;
3177
3178 // Decompose the name into its component parts.
3179 DeclarationName Name;
3180 SourceLocation NameLoc;
3181 const TemplateArgumentListInfo *TemplateArgs;
3182 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3183 Name, NameLoc, TemplateArgs);
3184
3185 bool IsArrow = (OpKind == tok::arrow);
3186
3187 NamedDecl *FirstQualifierInScope
3188 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3189 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3190
3191 // This is a postfix expression, so get rid of ParenListExprs.
3192 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3193
3194 Expr *Base = BaseArg.takeAs<Expr>();
3195 OwningExprResult Result(*this);
Douglas Gregor48026d22010-01-11 18:40:55 +00003196 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCallaa81e162009-12-01 22:10:20 +00003197 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003198 IsArrow, OpLoc,
3199 SS, FirstQualifierInScope,
3200 Name, NameLoc,
3201 TemplateArgs);
3202 } else {
3203 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3204 if (TemplateArgs) {
3205 // Re-use the lookup done for the template name.
3206 DecomposeTemplateName(R, Id);
3207 } else {
3208 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00003209 SS, ObjCImpDecl);
John McCall129e2df2009-11-30 22:42:35 +00003210
3211 if (Result.isInvalid()) {
3212 Owned(Base);
3213 return ExprError();
3214 }
3215
3216 if (Result.get()) {
3217 // The only way a reference to a destructor can be used is to
3218 // immediately call it, which falls into this case. If the
3219 // next token is not a '(', produce a diagnostic and build the
3220 // call now.
3221 if (!HasTrailingLParen &&
3222 Id.getKind() == UnqualifiedId::IK_DestructorName)
3223 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3224
3225 return move(Result);
3226 }
3227 }
3228
John McCallaa81e162009-12-01 22:10:20 +00003229 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003230 OpLoc, IsArrow, SS, FirstQualifierInScope,
3231 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003232 }
3233
3234 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003235}
3236
Anders Carlsson56c5e332009-08-25 03:49:14 +00003237Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3238 FunctionDecl *FD,
3239 ParmVarDecl *Param) {
3240 if (Param->hasUnparsedDefaultArg()) {
3241 Diag (CallLoc,
3242 diag::err_use_of_default_argument_to_function_declared_later) <<
3243 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003244 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003245 diag::note_default_argument_declared_here);
3246 } else {
3247 if (Param->hasUninstantiatedDefaultArg()) {
3248 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3249
3250 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003251 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003252
Mike Stump1eb44332009-09-09 15:08:12 +00003253 InstantiatingTemplate Inst(*this, CallLoc, Param,
3254 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003255 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003256
John McCallce3ff2b2009-08-25 22:02:44 +00003257 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003258 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003259 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003260
Douglas Gregor65222e82009-12-23 18:19:08 +00003261 // Check the expression as an initializer for the parameter.
3262 InitializedEntity Entity
3263 = InitializedEntity::InitializeParameter(Param);
3264 InitializationKind Kind
3265 = InitializationKind::CreateCopy(Param->getLocation(),
3266 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3267 Expr *ResultE = Result.takeAs<Expr>();
3268
3269 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3270 Result = InitSeq.Perform(*this, Entity, Kind,
3271 MultiExprArg(*this, (void**)&ResultE, 1));
3272 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003273 return ExprError();
Douglas Gregor65222e82009-12-23 18:19:08 +00003274
3275 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003276 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003277 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003278 }
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Anders Carlsson56c5e332009-08-25 03:49:14 +00003280 // If the default expression creates temporaries, we need to
3281 // push them to the current stack of expression temporaries so they'll
3282 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003283 // FIXME: We should really be rebuilding the default argument with new
3284 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003285 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3286 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003287 }
3288
3289 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003290 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003291}
3292
Douglas Gregor88a35142008-12-22 05:46:06 +00003293/// ConvertArgumentsForCall - Converts the arguments specified in
3294/// Args/NumArgs to the parameter types of the function FDecl with
3295/// function prototype Proto. Call is the call expression itself, and
3296/// Fn is the function expression. For a C++ member function, this
3297/// routine does not attempt to convert the object argument. Returns
3298/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003299bool
3300Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003301 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003302 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003303 Expr **Args, unsigned NumArgs,
3304 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003305 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003306 // assignment, to the types of the corresponding parameter, ...
3307 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003308 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003309
Douglas Gregor88a35142008-12-22 05:46:06 +00003310 // If too few arguments are available (and we don't have default
3311 // arguments for the remaining parameters), don't make the call.
3312 if (NumArgs < NumArgsInProto) {
3313 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3314 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3315 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003316 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003317 }
3318
3319 // If too many are passed and not variadic, error on the extras and drop
3320 // them.
3321 if (NumArgs > NumArgsInProto) {
3322 if (!Proto->isVariadic()) {
3323 Diag(Args[NumArgsInProto]->getLocStart(),
3324 diag::err_typecheck_call_too_many_args)
3325 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3326 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3327 Args[NumArgs-1]->getLocEnd());
3328 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003329 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003330 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003331 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003332 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003333 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003334 VariadicCallType CallType =
3335 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3336 if (Fn->getType()->isBlockPointerType())
3337 CallType = VariadicBlock; // Block
3338 else if (isa<MemberExpr>(Fn))
3339 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003340 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003341 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003342 if (Invalid)
3343 return true;
3344 unsigned TotalNumArgs = AllArgs.size();
3345 for (unsigned i = 0; i < TotalNumArgs; ++i)
3346 Call->setArg(i, AllArgs[i]);
3347
3348 return false;
3349}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003350
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003351bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3352 FunctionDecl *FDecl,
3353 const FunctionProtoType *Proto,
3354 unsigned FirstProtoArg,
3355 Expr **Args, unsigned NumArgs,
3356 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003357 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003358 unsigned NumArgsInProto = Proto->getNumArgs();
3359 unsigned NumArgsToCheck = NumArgs;
3360 bool Invalid = false;
3361 if (NumArgs != NumArgsInProto)
3362 // Use default arguments for missing arguments
3363 NumArgsToCheck = NumArgsInProto;
3364 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003365 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003366 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003367 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003368
Douglas Gregor88a35142008-12-22 05:46:06 +00003369 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003370 if (ArgIx < NumArgs) {
3371 Arg = Args[ArgIx++];
3372
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003373 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3374 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003375 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003376 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003377 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003378
Douglas Gregora188ff22009-12-22 16:09:06 +00003379 // Pass the argument
3380 ParmVarDecl *Param = 0;
3381 if (FDecl && i < FDecl->getNumParams())
3382 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003383
Douglas Gregora188ff22009-12-22 16:09:06 +00003384
3385 InitializedEntity Entity =
3386 Param? InitializedEntity::InitializeParameter(Param)
3387 : InitializedEntity::InitializeParameter(ProtoArgType);
3388 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3389 SourceLocation(),
3390 Owned(Arg));
3391 if (ArgE.isInvalid())
3392 return true;
3393
3394 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003395 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003396 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003397
Mike Stump1eb44332009-09-09 15:08:12 +00003398 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003399 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003400 if (ArgExpr.isInvalid())
3401 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003402
Anders Carlsson56c5e332009-08-25 03:49:14 +00003403 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003404 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003405 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003406 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003407
Douglas Gregor88a35142008-12-22 05:46:06 +00003408 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003409 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003410 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003411 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003412 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003413 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003414 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003415 }
3416 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003417 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003418}
3419
Steve Narofff69936d2007-09-16 03:34:24 +00003420/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003421/// This provides the location of the left/right parens and a list of comma
3422/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003423Action::OwningExprResult
3424Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3425 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003426 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003427 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003428
3429 // Since this might be a postfix expression, get rid of ParenListExprs.
3430 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003432 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003433 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003434 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Douglas Gregor88a35142008-12-22 05:46:06 +00003436 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003437 // If this is a pseudo-destructor expression, build the call immediately.
3438 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3439 if (NumArgs > 0) {
3440 // Pseudo-destructor calls should not have any arguments.
3441 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3442 << CodeModificationHint::CreateRemoval(
3443 SourceRange(Args[0]->getLocStart(),
3444 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003445
Douglas Gregora71d8192009-09-04 17:36:40 +00003446 for (unsigned I = 0; I != NumArgs; ++I)
3447 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Douglas Gregora71d8192009-09-04 17:36:40 +00003449 NumArgs = 0;
3450 }
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregora71d8192009-09-04 17:36:40 +00003452 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3453 RParenLoc));
3454 }
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Douglas Gregor17330012009-02-04 15:01:18 +00003456 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003457 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003458 // FIXME: Will need to cache the results of name lookup (including ADL) in
3459 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003460 bool Dependent = false;
3461 if (Fn->isTypeDependent())
3462 Dependent = true;
3463 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3464 Dependent = true;
3465
3466 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003467 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003468 Context.DependentTy, RParenLoc));
3469
3470 // Determine whether this is a call to an object (C++ [over.call.object]).
3471 if (Fn->getType()->isRecordType())
3472 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3473 CommaLocs, RParenLoc));
3474
John McCall129e2df2009-11-30 22:42:35 +00003475 Expr *NakedFn = Fn->IgnoreParens();
3476
3477 // Determine whether this is a call to an unresolved member function.
3478 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3479 // If lookup was unresolved but not dependent (i.e. didn't find
3480 // an unresolved using declaration), it has to be an overloaded
3481 // function set, which means it must contain either multiple
3482 // declarations (all methods or method templates) or a single
3483 // method template.
3484 assert((MemE->getNumDecls() > 1) ||
3485 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003486 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003487
John McCallaa81e162009-12-01 22:10:20 +00003488 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3489 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003490 }
3491
Douglas Gregorfa047642009-02-04 00:32:51 +00003492 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003493 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003494 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003495 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003496 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3497 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003498 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003499
3500 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003501 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003502 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3503 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003504 if (const FunctionProtoType *FPT =
3505 dyn_cast<FunctionProtoType>(BO->getType())) {
3506 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003507
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003508 ExprOwningPtr<CXXMemberCallExpr>
3509 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3510 NumArgs, ResultTy,
3511 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003512
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003513 if (CheckCallReturnType(FPT->getResultType(),
3514 BO->getRHS()->getSourceRange().getBegin(),
3515 TheCall.get(), 0))
3516 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003517
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003518 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3519 RParenLoc))
3520 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003521
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003522 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3523 }
3524 return ExprError(Diag(Fn->getLocStart(),
3525 diag::err_typecheck_call_not_function)
3526 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003527 }
3528 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003529 }
3530
Douglas Gregorfa047642009-02-04 00:32:51 +00003531 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003532 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003533 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003534
Eli Friedmanefa42f72009-12-26 03:35:45 +00003535 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003536 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3537 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3538 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3539 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003540 }
Chris Lattner04421082008-04-08 04:40:51 +00003541
John McCall3b4294e2009-12-16 12:17:52 +00003542 NamedDecl *NDecl = 0;
3543 if (isa<DeclRefExpr>(NakedFn))
3544 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3545
John McCallaa81e162009-12-01 22:10:20 +00003546 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3547}
3548
John McCall3b4294e2009-12-16 12:17:52 +00003549/// BuildResolvedCallExpr - Build a call to a resolved expression,
3550/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003551/// unary-convert to an expression of function-pointer or
3552/// block-pointer type.
3553///
3554/// \param NDecl the declaration being called, if available
3555Sema::OwningExprResult
3556Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3557 SourceLocation LParenLoc,
3558 Expr **Args, unsigned NumArgs,
3559 SourceLocation RParenLoc) {
3560 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3561
Chris Lattner04421082008-04-08 04:40:51 +00003562 // Promote the function operand.
3563 UsualUnaryConversions(Fn);
3564
Chris Lattner925e60d2007-12-28 05:29:59 +00003565 // Make the call expr early, before semantic checks. This guarantees cleanup
3566 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003567 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3568 Args, NumArgs,
3569 Context.BoolTy,
3570 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003571
Steve Naroffdd972f22008-09-05 22:11:13 +00003572 const FunctionType *FuncT;
3573 if (!Fn->getType()->isBlockPointerType()) {
3574 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3575 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003576 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003577 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003578 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3579 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003580 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003581 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003582 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003583 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003584 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003585 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003586 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3587 << Fn->getType() << Fn->getSourceRange());
3588
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003589 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003590 if (CheckCallReturnType(FuncT->getResultType(),
3591 Fn->getSourceRange().getBegin(), TheCall.get(),
3592 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003593 return ExprError();
3594
Chris Lattner925e60d2007-12-28 05:29:59 +00003595 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003596 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003597
Douglas Gregor72564e72009-02-26 23:50:07 +00003598 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003599 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003600 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003601 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003602 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003603 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003604
Douglas Gregor74734d52009-04-02 15:37:10 +00003605 if (FDecl) {
3606 // Check if we have too few/too many template arguments, based
3607 // on our knowledge of the function definition.
3608 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003609 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003610 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003611 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003612 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3613 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3614 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3615 }
3616 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003617 }
3618
Steve Naroffb291ab62007-08-28 23:30:39 +00003619 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003620 for (unsigned i = 0; i != NumArgs; i++) {
3621 Expr *Arg = Args[i];
3622 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003623 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3624 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003625 PDiag(diag::err_call_incomplete_argument)
3626 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003627 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003628 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003629 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003630 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003631
Douglas Gregor88a35142008-12-22 05:46:06 +00003632 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3633 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003634 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3635 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003636
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003637 // Check for sentinels
3638 if (NDecl)
3639 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Chris Lattner59907c42007-08-10 20:18:51 +00003641 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003642 if (FDecl) {
3643 if (CheckFunctionCall(FDecl, TheCall.get()))
3644 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003646 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003647 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3648 } else if (NDecl) {
3649 if (CheckBlockCall(NDecl, TheCall.get()))
3650 return ExprError();
3651 }
Chris Lattner59907c42007-08-10 20:18:51 +00003652
Anders Carlssonec74c592009-08-16 03:06:32 +00003653 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003654}
3655
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003656Action::OwningExprResult
3657Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3658 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003659 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003660 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003661 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003662
3663 TypeSourceInfo *TInfo;
3664 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3665 if (!TInfo)
3666 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3667
3668 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3669}
3670
3671Action::OwningExprResult
3672Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3673 SourceLocation RParenLoc, ExprArg InitExpr) {
3674 QualType literalType = TInfo->getType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003675 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003676
Eli Friedman6223c222008-05-20 05:22:08 +00003677 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003678 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003679 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3680 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003681 } else if (!literalType->isDependentType() &&
3682 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003683 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003684 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003685 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003686 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003687
Douglas Gregor99a2e602009-12-16 01:38:02 +00003688 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003689 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003690 InitializationKind Kind
3691 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3692 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003693 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3694 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3695 MultiExprArg(*this, (void**)&literalExpr, 1),
3696 &literalType);
3697 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003698 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003699 InitExpr.release();
3700 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003701
Chris Lattner371f2582008-12-04 23:50:19 +00003702 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003703 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003704 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003705 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003706 }
Eli Friedman08544622009-12-22 02:35:53 +00003707
3708 Result.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003709
John McCall1d7d8d62010-01-19 22:33:45 +00003710 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003711 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003712}
3713
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003714Action::OwningExprResult
3715Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003716 SourceLocation RBraceLoc) {
3717 unsigned NumInit = initlist.size();
3718 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003719
Steve Naroff08d92e42007-09-15 18:49:24 +00003720 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003721 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003722
Mike Stumpeed9cac2009-02-19 03:04:26 +00003723 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003724 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003725 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003726 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003727}
3728
Anders Carlsson82debc72009-10-18 18:12:03 +00003729static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3730 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003731 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003732 return CastExpr::CK_NoOp;
3733
3734 if (SrcTy->hasPointerRepresentation()) {
3735 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003736 return DestTy->isObjCObjectPointerType() ?
3737 CastExpr::CK_AnyPointerToObjCPointerCast :
3738 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003739 if (DestTy->isIntegerType())
3740 return CastExpr::CK_PointerToIntegral;
3741 }
3742
3743 if (SrcTy->isIntegerType()) {
3744 if (DestTy->isIntegerType())
3745 return CastExpr::CK_IntegralCast;
3746 if (DestTy->hasPointerRepresentation())
3747 return CastExpr::CK_IntegralToPointer;
3748 if (DestTy->isRealFloatingType())
3749 return CastExpr::CK_IntegralToFloating;
3750 }
3751
3752 if (SrcTy->isRealFloatingType()) {
3753 if (DestTy->isRealFloatingType())
3754 return CastExpr::CK_FloatingCast;
3755 if (DestTy->isIntegerType())
3756 return CastExpr::CK_FloatingToIntegral;
3757 }
3758
3759 // FIXME: Assert here.
3760 // assert(false && "Unhandled cast combination!");
3761 return CastExpr::CK_Unknown;
3762}
3763
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003764/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003765bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003766 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003767 CXXMethodDecl *& ConversionDecl,
3768 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003769 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003770 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3771 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003772
Eli Friedman199ea952009-08-15 19:02:19 +00003773 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003774
3775 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3776 // type needs to be scalar.
3777 if (castType->isVoidType()) {
3778 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003779 Kind = CastExpr::CK_ToVoid;
3780 return false;
3781 }
3782
3783 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003784 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003785 (castType->isStructureType() || castType->isUnionType())) {
3786 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003787 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003788 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3789 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003790 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003791 return false;
3792 }
3793
3794 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003795 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003796 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003797 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003798 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003799 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003800 if (Context.hasSameUnqualifiedType(Field->getType(),
3801 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003802 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3803 << castExpr->getSourceRange();
3804 break;
3805 }
3806 }
3807 if (Field == FieldEnd)
3808 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3809 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003810 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003811 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003812 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003813
3814 // Reject any other conversions to non-scalar types.
3815 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3816 << castType << castExpr->getSourceRange();
3817 }
3818
3819 if (!castExpr->getType()->isScalarType() &&
3820 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003821 return Diag(castExpr->getLocStart(),
3822 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003823 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003824 }
3825
Anders Carlsson16a89042009-10-16 05:23:41 +00003826 if (castType->isExtVectorType())
3827 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3828
Anders Carlssonc3516322009-10-16 02:48:28 +00003829 if (castType->isVectorType())
3830 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3831 if (castExpr->getType()->isVectorType())
3832 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3833
3834 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003835 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003836
Anders Carlsson16a89042009-10-16 05:23:41 +00003837 if (isa<ObjCSelectorExpr>(castExpr))
3838 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3839
Anders Carlssonc3516322009-10-16 02:48:28 +00003840 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003841 QualType castExprType = castExpr->getType();
3842 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3843 return Diag(castExpr->getLocStart(),
3844 diag::err_cast_pointer_from_non_pointer_int)
3845 << castExprType << castExpr->getSourceRange();
3846 } else if (!castExpr->getType()->isArithmeticType()) {
3847 if (!castType->isIntegralType() && castType->isArithmeticType())
3848 return Diag(castExpr->getLocStart(),
3849 diag::err_cast_pointer_to_non_pointer_int)
3850 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003851 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003852
3853 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003854 return false;
3855}
3856
Anders Carlssonc3516322009-10-16 02:48:28 +00003857bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3858 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003859 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003860
Anders Carlssona64db8f2007-11-27 05:51:55 +00003861 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003862 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003863 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003864 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003865 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003866 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003867 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003868 } else
3869 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003870 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003871 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003872
Anders Carlssonc3516322009-10-16 02:48:28 +00003873 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003874 return false;
3875}
3876
Anders Carlsson16a89042009-10-16 05:23:41 +00003877bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3878 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003879 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003880
3881 QualType SrcTy = CastExpr->getType();
3882
Nate Begeman9b10da62009-06-27 22:05:55 +00003883 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3884 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003885 if (SrcTy->isVectorType()) {
3886 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3887 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3888 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003889 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003890 return false;
3891 }
3892
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003893 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003894 // conversion will take place first from scalar to elt type, and then
3895 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003896 if (SrcTy->isPointerType())
3897 return Diag(R.getBegin(),
3898 diag::err_invalid_conversion_between_vector_and_scalar)
3899 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003900
3901 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3902 ImpCastExprToType(CastExpr, DestElemTy,
3903 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003904
3905 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003906 return false;
3907}
3908
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003909Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003910Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003911 SourceLocation RParenLoc, ExprArg Op) {
3912 assert((Ty != 0) && (Op.get() != 0) &&
3913 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003914
John McCall9d125032010-01-15 18:39:57 +00003915 TypeSourceInfo *castTInfo;
3916 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3917 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00003918 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Nate Begeman2ef13e52009-08-10 23:49:36 +00003920 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00003921 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003922 if (isa<ParenListExpr>(castExpr))
John McCall42f56b52010-01-18 19:35:47 +00003923 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3924 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00003925
3926 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3927}
3928
3929Action::OwningExprResult
3930Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3931 SourceLocation RParenLoc, ExprArg Op) {
3932 Expr *castExpr = static_cast<Expr*>(Op.get());
3933
Anders Carlsson0aebc812009-09-09 21:33:21 +00003934 CXXMethodDecl *Method = 0;
John McCallb042fdf2010-01-15 18:56:44 +00003935 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3936 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003937 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003938 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003939
3940 if (Method) {
John McCallb042fdf2010-01-15 18:56:44 +00003941 // FIXME: preserve type source info here
3942 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
3943 Kind, Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003944
Anders Carlsson0aebc812009-09-09 21:33:21 +00003945 if (CastArg.isInvalid())
3946 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003947
Anders Carlsson0aebc812009-09-09 21:33:21 +00003948 castExpr = CastArg.takeAs<Expr>();
3949 } else {
3950 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003951 }
Mike Stump1eb44332009-09-09 15:08:12 +00003952
John McCallb042fdf2010-01-15 18:56:44 +00003953 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3954 Kind, castExpr, Ty,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003955 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003956}
3957
Nate Begeman2ef13e52009-08-10 23:49:36 +00003958/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3959/// of comma binary operators.
3960Action::OwningExprResult
3961Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3962 Expr *expr = EA.takeAs<Expr>();
3963 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3964 if (!E)
3965 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Nate Begeman2ef13e52009-08-10 23:49:36 +00003967 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Nate Begeman2ef13e52009-08-10 23:49:36 +00003969 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3970 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3971 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Nate Begeman2ef13e52009-08-10 23:49:36 +00003973 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3974}
3975
3976Action::OwningExprResult
3977Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3978 SourceLocation RParenLoc, ExprArg Op,
John McCall42f56b52010-01-18 19:35:47 +00003979 TypeSourceInfo *TInfo) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003980 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCall42f56b52010-01-18 19:35:47 +00003981 QualType Ty = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003982
3983 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003984 // then handle it as such.
3985 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3986 if (PE->getNumExprs() == 0) {
3987 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3988 return ExprError();
3989 }
3990
3991 llvm::SmallVector<Expr *, 8> initExprs;
3992 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3993 initExprs.push_back(PE->getExpr(i));
3994
3995 // FIXME: This means that pretty-printing the final AST will produce curly
3996 // braces instead of the original commas.
3997 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003998 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003999 initExprs.size(), RParenLoc);
4000 E->setType(Ty);
John McCall42f56b52010-01-18 19:35:47 +00004001 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004002 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004003 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004004 // sequence of BinOp comma operators.
4005 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCall42f56b52010-01-18 19:35:47 +00004006 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004007 }
4008}
4009
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004010Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004011 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004012 MultiExprArg Val,
4013 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004014 unsigned nexprs = Val.size();
4015 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004016 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4017 Expr *expr;
4018 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4019 expr = new (Context) ParenExpr(L, R, exprs[0]);
4020 else
4021 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004022 return Owned(expr);
4023}
4024
Sebastian Redl28507842009-02-26 14:39:58 +00004025/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4026/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004027/// C99 6.5.15
4028QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4029 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004030 // C++ is sufficiently different to merit its own checker.
4031 if (getLangOptions().CPlusPlus)
4032 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4033
John McCallb13c87f2009-11-05 09:23:39 +00004034 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4035
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004036 UsualUnaryConversions(Cond);
4037 UsualUnaryConversions(LHS);
4038 UsualUnaryConversions(RHS);
4039 QualType CondTy = Cond->getType();
4040 QualType LHSTy = LHS->getType();
4041 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004042
Reid Spencer5f016e22007-07-11 17:01:13 +00004043 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004044 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4045 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4046 << CondTy;
4047 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004048 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004049
Chris Lattner70d67a92008-01-06 22:42:25 +00004050 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004051 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4052 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004053
Chris Lattner70d67a92008-01-06 22:42:25 +00004054 // If both operands have arithmetic type, do the usual arithmetic conversions
4055 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004056 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4057 UsualArithmeticConversions(LHS, RHS);
4058 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004059 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004060
Chris Lattner70d67a92008-01-06 22:42:25 +00004061 // If both operands are the same structure or union type, the result is that
4062 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004063 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4064 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004065 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004066 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004067 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004068 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004069 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004070 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004071
Chris Lattner70d67a92008-01-06 22:42:25 +00004072 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004073 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004074 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4075 if (!LHSTy->isVoidType())
4076 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4077 << RHS->getSourceRange();
4078 if (!RHSTy->isVoidType())
4079 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4080 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004081 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4082 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004083 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004084 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004085 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4086 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004087 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004088 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004089 // promote the null to a pointer.
4090 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004091 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004092 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004093 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004094 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004095 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004096 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004097 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004098
4099 // All objective-c pointer type analysis is done here.
4100 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4101 QuestionLoc);
4102 if (!compositeType.isNull())
4103 return compositeType;
4104
4105
Steve Naroff7154a772009-07-01 14:36:47 +00004106 // Handle block pointer types.
4107 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4108 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4109 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4110 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004111 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4112 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004113 return destType;
4114 }
4115 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004116 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004117 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004118 }
Steve Naroff7154a772009-07-01 14:36:47 +00004119 // We have 2 block pointer types.
4120 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4121 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004122 return LHSTy;
4123 }
Steve Naroff7154a772009-07-01 14:36:47 +00004124 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004125 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4126 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004127
Steve Naroff7154a772009-07-01 14:36:47 +00004128 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4129 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004130 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004131 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004132 // In this situation, we assume void* type. No especially good
4133 // reason, but this is what gcc does, and we do have to pick
4134 // to get a consistent AST.
4135 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004136 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4137 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004138 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004139 }
Steve Naroff7154a772009-07-01 14:36:47 +00004140 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004141 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4142 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004143 return LHSTy;
4144 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004145
Steve Naroff7154a772009-07-01 14:36:47 +00004146 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4147 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4148 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004149 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4150 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004151
4152 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4153 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4154 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004155 QualType destPointee
4156 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004157 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004158 // Add qualifiers if necessary.
4159 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4160 // Promote to void*.
4161 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004162 return destType;
4163 }
4164 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004165 QualType destPointee
4166 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004167 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004168 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004169 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004170 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004171 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004172 return destType;
4173 }
4174
4175 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4176 // Two identical pointer types are always compatible.
4177 return LHSTy;
4178 }
4179 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4180 rhptee.getUnqualifiedType())) {
4181 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4182 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4183 // In this situation, we assume void* type. No especially good
4184 // reason, but this is what gcc does, and we do have to pick
4185 // to get a consistent AST.
4186 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004187 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4188 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004189 return incompatTy;
4190 }
4191 // The pointer types are compatible.
4192 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4193 // differently qualified versions of compatible types, the result type is
4194 // a pointer to an appropriately qualified version of the *composite*
4195 // type.
4196 // FIXME: Need to calculate the composite type.
4197 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004198 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4199 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004200 return LHSTy;
4201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Steve Naroff7154a772009-07-01 14:36:47 +00004203 // GCC compatibility: soften pointer/integer mismatch.
4204 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4205 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4206 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004207 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004208 return RHSTy;
4209 }
4210 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4211 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4212 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004213 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004214 return LHSTy;
4215 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004216
Chris Lattner70d67a92008-01-06 22:42:25 +00004217 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004218 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4219 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004220 return QualType();
4221}
4222
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004223/// FindCompositeObjCPointerType - Helper method to find composite type of
4224/// two objective-c pointer types of the two input expressions.
4225QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4226 SourceLocation QuestionLoc) {
4227 QualType LHSTy = LHS->getType();
4228 QualType RHSTy = RHS->getType();
4229
4230 // Handle things like Class and struct objc_class*. Here we case the result
4231 // to the pseudo-builtin, because that will be implicitly cast back to the
4232 // redefinition type if an attempt is made to access its fields.
4233 if (LHSTy->isObjCClassType() &&
4234 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4235 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4236 return LHSTy;
4237 }
4238 if (RHSTy->isObjCClassType() &&
4239 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4240 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4241 return RHSTy;
4242 }
4243 // And the same for struct objc_object* / id
4244 if (LHSTy->isObjCIdType() &&
4245 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4246 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4247 return LHSTy;
4248 }
4249 if (RHSTy->isObjCIdType() &&
4250 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4251 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4252 return RHSTy;
4253 }
4254 // And the same for struct objc_selector* / SEL
4255 if (Context.isObjCSelType(LHSTy) &&
4256 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4257 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4258 return LHSTy;
4259 }
4260 if (Context.isObjCSelType(RHSTy) &&
4261 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4262 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4263 return RHSTy;
4264 }
4265 // Check constraints for Objective-C object pointers types.
4266 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4267
4268 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4269 // Two identical object pointer types are always compatible.
4270 return LHSTy;
4271 }
4272 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4273 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4274 QualType compositeType = LHSTy;
4275
4276 // If both operands are interfaces and either operand can be
4277 // assigned to the other, use that type as the composite
4278 // type. This allows
4279 // xxx ? (A*) a : (B*) b
4280 // where B is a subclass of A.
4281 //
4282 // Additionally, as for assignment, if either type is 'id'
4283 // allow silent coercion. Finally, if the types are
4284 // incompatible then make sure to use 'id' as the composite
4285 // type so the result is acceptable for sending messages to.
4286
4287 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4288 // It could return the composite type.
4289 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4290 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4291 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4292 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4293 } else if ((LHSTy->isObjCQualifiedIdType() ||
4294 RHSTy->isObjCQualifiedIdType()) &&
4295 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4296 // Need to handle "id<xx>" explicitly.
4297 // GCC allows qualified id and any Objective-C type to devolve to
4298 // id. Currently localizing to here until clear this should be
4299 // part of ObjCQualifiedIdTypesAreCompatible.
4300 compositeType = Context.getObjCIdType();
4301 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4302 compositeType = Context.getObjCIdType();
4303 } else if (!(compositeType =
4304 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4305 ;
4306 else {
4307 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4308 << LHSTy << RHSTy
4309 << LHS->getSourceRange() << RHS->getSourceRange();
4310 QualType incompatTy = Context.getObjCIdType();
4311 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4312 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4313 return incompatTy;
4314 }
4315 // The object pointer types are compatible.
4316 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4317 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4318 return compositeType;
4319 }
4320 // Check Objective-C object pointer types and 'void *'
4321 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4322 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4323 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4324 QualType destPointee
4325 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4326 QualType destType = Context.getPointerType(destPointee);
4327 // Add qualifiers if necessary.
4328 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4329 // Promote to void*.
4330 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4331 return destType;
4332 }
4333 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4334 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4335 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4336 QualType destPointee
4337 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4338 QualType destType = Context.getPointerType(destPointee);
4339 // Add qualifiers if necessary.
4340 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4341 // Promote to void*.
4342 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4343 return destType;
4344 }
4345 return QualType();
4346}
4347
Steve Narofff69936d2007-09-16 03:34:24 +00004348/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004349/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004350Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4351 SourceLocation ColonLoc,
4352 ExprArg Cond, ExprArg LHS,
4353 ExprArg RHS) {
4354 Expr *CondExpr = (Expr *) Cond.get();
4355 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004356
4357 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4358 // was the condition.
4359 bool isLHSNull = LHSExpr == 0;
4360 if (isLHSNull)
4361 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004362
4363 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004364 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004365 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004366 return ExprError();
4367
4368 Cond.release();
4369 LHS.release();
4370 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004371 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004372 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004373 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004374}
4375
Reid Spencer5f016e22007-07-11 17:01:13 +00004376// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004377// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004378// routine is it effectively iqnores the qualifiers on the top level pointee.
4379// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4380// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004381Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004382Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4383 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004384
David Chisnall0f436562009-08-17 16:35:33 +00004385 if ((lhsType->isObjCClassType() &&
4386 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4387 (rhsType->isObjCClassType() &&
4388 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4389 return Compatible;
4390 }
4391
Reid Spencer5f016e22007-07-11 17:01:13 +00004392 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004393 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4394 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004395
Reid Spencer5f016e22007-07-11 17:01:13 +00004396 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004397 lhptee = Context.getCanonicalType(lhptee);
4398 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004399
Chris Lattner5cf216b2008-01-04 18:04:52 +00004400 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004401
4402 // C99 6.5.16.1p1: This following citation is common to constraints
4403 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4404 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004405 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004406 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004407 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004408
Mike Stumpeed9cac2009-02-19 03:04:26 +00004409 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4410 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004411 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004412 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004413 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004414 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004415
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004416 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004417 assert(rhptee->isFunctionType());
4418 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004419 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004420
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004421 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004422 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004423 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004424
4425 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004426 assert(lhptee->isFunctionType());
4427 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004428 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004429 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004430 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004431 lhptee = lhptee.getUnqualifiedType();
4432 rhptee = rhptee.getUnqualifiedType();
4433 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4434 // Check if the pointee types are compatible ignoring the sign.
4435 // We explicitly check for char so that we catch "char" vs
4436 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004437 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004438 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004439 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004440 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004441
4442 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004443 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004444 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004445 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004446
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004447 if (lhptee == rhptee) {
4448 // Types are compatible ignoring the sign. Qualifier incompatibility
4449 // takes priority over sign incompatibility because the sign
4450 // warning can be disabled.
4451 if (ConvTy != Compatible)
4452 return ConvTy;
4453 return IncompatiblePointerSign;
4454 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004455
4456 // If we are a multi-level pointer, it's possible that our issue is simply
4457 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4458 // the eventual target type is the same and the pointers have the same
4459 // level of indirection, this must be the issue.
4460 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4461 do {
4462 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4463 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4464
4465 lhptee = Context.getCanonicalType(lhptee);
4466 rhptee = Context.getCanonicalType(rhptee);
4467 } while (lhptee->isPointerType() && rhptee->isPointerType());
4468
Douglas Gregora4923eb2009-11-16 21:35:15 +00004469 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004470 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004471 }
4472
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004473 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004474 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004475 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004476 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004477}
4478
Steve Naroff1c7d0672008-09-04 15:10:53 +00004479/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4480/// block pointer types are compatible or whether a block and normal pointer
4481/// are compatible. It is more restrict than comparing two function pointer
4482// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004483Sema::AssignConvertType
4484Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004485 QualType rhsType) {
4486 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004487
Steve Naroff1c7d0672008-09-04 15:10:53 +00004488 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004489 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4490 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004491
Steve Naroff1c7d0672008-09-04 15:10:53 +00004492 // make sure we operate on the canonical type
4493 lhptee = Context.getCanonicalType(lhptee);
4494 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004495
Steve Naroff1c7d0672008-09-04 15:10:53 +00004496 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004497
Steve Naroff1c7d0672008-09-04 15:10:53 +00004498 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004499 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004500 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004501
Eli Friedman26784c12009-06-08 05:08:54 +00004502 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004503 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004504 return ConvTy;
4505}
4506
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004507/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4508/// for assignment compatibility.
4509Sema::AssignConvertType
4510Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4511 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4512 return Compatible;
4513 QualType lhptee =
4514 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4515 QualType rhptee =
4516 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4517 // make sure we operate on the canonical type
4518 lhptee = Context.getCanonicalType(lhptee);
4519 rhptee = Context.getCanonicalType(rhptee);
4520 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4521 return CompatiblePointerDiscardsQualifiers;
4522
4523 if (Context.typesAreCompatible(lhsType, rhsType))
4524 return Compatible;
4525 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4526 return IncompatibleObjCQualifiedId;
4527 return IncompatiblePointer;
4528}
4529
Mike Stumpeed9cac2009-02-19 03:04:26 +00004530/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4531/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004532/// pointers. Here are some objectionable examples that GCC considers warnings:
4533///
4534/// int a, *pint;
4535/// short *pshort;
4536/// struct foo *pfoo;
4537///
4538/// pint = pshort; // warning: assignment from incompatible pointer type
4539/// a = pint; // warning: assignment makes integer from pointer without a cast
4540/// pint = a; // warning: assignment makes pointer from integer without a cast
4541/// pint = pfoo; // warning: assignment from incompatible pointer type
4542///
4543/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004544/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004545///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004546Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004547Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004548 // Get canonical types. We're not formatting these types, just comparing
4549 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004550 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4551 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004552
4553 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004554 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004555
David Chisnall0f436562009-08-17 16:35:33 +00004556 if ((lhsType->isObjCClassType() &&
4557 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4558 (rhsType->isObjCClassType() &&
4559 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4560 return Compatible;
4561 }
4562
Douglas Gregor9d293df2008-10-28 00:22:11 +00004563 // If the left-hand side is a reference type, then we are in a
4564 // (rare!) case where we've allowed the use of references in C,
4565 // e.g., as a parameter type in a built-in function. In this case,
4566 // just make sure that the type referenced is compatible with the
4567 // right-hand side type. The caller is responsible for adjusting
4568 // lhsType so that the resulting expression does not have reference
4569 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004570 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004571 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004572 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004573 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004574 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004575 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4576 // to the same ExtVector type.
4577 if (lhsType->isExtVectorType()) {
4578 if (rhsType->isExtVectorType())
4579 return lhsType == rhsType ? Compatible : Incompatible;
4580 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4581 return Compatible;
4582 }
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Nate Begemanbe2341d2008-07-14 18:02:46 +00004584 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004585 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004586 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004587 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004588 if (getLangOptions().LaxVectorConversions &&
4589 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004590 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004591 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004592 }
4593 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004594 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004595
Chris Lattnere8b3e962008-01-04 23:32:24 +00004596 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004597 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004598
Chris Lattner78eca282008-04-07 06:49:41 +00004599 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004600 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004601 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004602
Chris Lattner78eca282008-04-07 06:49:41 +00004603 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004604 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004605
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004606 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004607 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004608 if (lhsType->isVoidPointerType()) // an exception to the rule.
4609 return Compatible;
4610 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004611 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004612 if (rhsType->getAs<BlockPointerType>()) {
4613 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004614 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004615
4616 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004617 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004618 return Compatible;
4619 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004620 return Incompatible;
4621 }
4622
4623 if (isa<BlockPointerType>(lhsType)) {
4624 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004625 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004626
Steve Naroffb4406862008-09-29 18:10:17 +00004627 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004628 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004629 return Compatible;
4630
Steve Naroff1c7d0672008-09-04 15:10:53 +00004631 if (rhsType->isBlockPointerType())
4632 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004633
Ted Kremenek6217b802009-07-29 21:53:49 +00004634 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004635 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004636 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004637 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004638 return Incompatible;
4639 }
4640
Steve Naroff14108da2009-07-10 23:34:53 +00004641 if (isa<ObjCObjectPointerType>(lhsType)) {
4642 if (rhsType->isIntegerType())
4643 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004645 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004646 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004647 if (rhsType->isVoidPointerType()) // an exception to the rule.
4648 return Compatible;
4649 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004650 }
4651 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004652 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004653 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004654 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004655 if (RHSPT->getPointeeType()->isVoidType())
4656 return Compatible;
4657 }
4658 // Treat block pointers as objects.
4659 if (rhsType->isBlockPointerType())
4660 return Compatible;
4661 return Incompatible;
4662 }
Chris Lattner78eca282008-04-07 06:49:41 +00004663 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004664 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004665 if (lhsType == Context.BoolTy)
4666 return Compatible;
4667
4668 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004669 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004670
Mike Stumpeed9cac2009-02-19 03:04:26 +00004671 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004672 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004673
4674 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004675 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004676 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004677 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004678 }
Steve Naroff14108da2009-07-10 23:34:53 +00004679 if (isa<ObjCObjectPointerType>(rhsType)) {
4680 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4681 if (lhsType == Context.BoolTy)
4682 return Compatible;
4683
4684 if (lhsType->isIntegerType())
4685 return PointerToInt;
4686
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004687 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004688 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004689 if (lhsType->isVoidPointerType()) // an exception to the rule.
4690 return Compatible;
4691 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004692 }
4693 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004694 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004695 return Compatible;
4696 return Incompatible;
4697 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004698
Chris Lattnerfc144e22008-01-04 23:18:45 +00004699 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004700 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004701 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004702 }
4703 return Incompatible;
4704}
4705
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004706/// \brief Constructs a transparent union from an expression that is
4707/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004708static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004709 QualType UnionType, FieldDecl *Field) {
4710 // Build an initializer list that designates the appropriate member
4711 // of the transparent union.
4712 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4713 &E, 1,
4714 SourceLocation());
4715 Initializer->setType(UnionType);
4716 Initializer->setInitializedFieldInUnion(Field);
4717
4718 // Build a compound literal constructing a value of the transparent
4719 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004720 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004721 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004722 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004723}
4724
4725Sema::AssignConvertType
4726Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4727 QualType FromType = rExpr->getType();
4728
Mike Stump1eb44332009-09-09 15:08:12 +00004729 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004730 // transparent_union GCC extension.
4731 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004732 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004733 return Incompatible;
4734
4735 // The field to initialize within the transparent union.
4736 RecordDecl *UD = UT->getDecl();
4737 FieldDecl *InitField = 0;
4738 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004739 for (RecordDecl::field_iterator it = UD->field_begin(),
4740 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004741 it != itend; ++it) {
4742 if (it->getType()->isPointerType()) {
4743 // If the transparent union contains a pointer type, we allow:
4744 // 1) void pointer
4745 // 2) null pointer constant
4746 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004747 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004748 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004749 InitField = *it;
4750 break;
4751 }
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Douglas Gregorce940492009-09-25 04:25:58 +00004753 if (rExpr->isNullPointerConstant(Context,
4754 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004755 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004756 InitField = *it;
4757 break;
4758 }
4759 }
4760
4761 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4762 == Compatible) {
4763 InitField = *it;
4764 break;
4765 }
4766 }
4767
4768 if (!InitField)
4769 return Incompatible;
4770
4771 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4772 return Compatible;
4773}
4774
Chris Lattner5cf216b2008-01-04 18:04:52 +00004775Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004776Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004777 if (getLangOptions().CPlusPlus) {
4778 if (!lhsType->isRecordType()) {
4779 // C++ 5.17p3: If the left operand is not of class type, the
4780 // expression is implicitly converted (C++ 4) to the
4781 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004782 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004783 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004784 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004785 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004786 }
4787
4788 // FIXME: Currently, we fall through and treat C++ classes like C
4789 // structures.
4790 }
4791
Steve Naroff529a4ad2007-11-27 17:58:44 +00004792 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4793 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004794 if ((lhsType->isPointerType() ||
4795 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004796 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004797 && rExpr->isNullPointerConstant(Context,
4798 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004799 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004800 return Compatible;
4801 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004802
Chris Lattner943140e2007-10-16 02:55:40 +00004803 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004804 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004805 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004806 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004807 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004808 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004809 if (!lhsType->isReferenceType())
4810 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004811
Chris Lattner5cf216b2008-01-04 18:04:52 +00004812 Sema::AssignConvertType result =
4813 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004814
Steve Narofff1120de2007-08-24 22:33:52 +00004815 // C99 6.5.16.1p2: The value of the right operand is converted to the
4816 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004817 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4818 // so that we can use references in built-in functions even in C.
4819 // The getNonReferenceType() call makes sure that the resulting expression
4820 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004821 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004822 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4823 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004824 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004825}
4826
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004827QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004828 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004829 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004830 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004831 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004832}
4833
Chris Lattner7ef655a2010-01-12 21:23:57 +00004834QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004835 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004836 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004837 QualType lhsType =
4838 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4839 QualType rhsType =
4840 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004841
Nate Begemanbe2341d2008-07-14 18:02:46 +00004842 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004843 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004844 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004845
Nate Begemanbe2341d2008-07-14 18:02:46 +00004846 // Handle the case of a vector & extvector type of the same size and element
4847 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004848 if (getLangOptions().LaxVectorConversions) {
4849 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004850 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4851 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004852 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004853 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004854 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004855 }
4856 }
4857 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004858
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004859 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4860 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4861 bool swapped = false;
4862 if (rhsType->isExtVectorType()) {
4863 swapped = true;
4864 std::swap(rex, lex);
4865 std::swap(rhsType, lhsType);
4866 }
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Nate Begemandde25982009-06-28 19:12:57 +00004868 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004869 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004870 QualType EltTy = LV->getElementType();
4871 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4872 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004873 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004874 if (swapped) std::swap(rex, lex);
4875 return lhsType;
4876 }
4877 }
4878 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4879 rhsType->isRealFloatingType()) {
4880 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004881 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004882 if (swapped) std::swap(rex, lex);
4883 return lhsType;
4884 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004885 }
4886 }
Mike Stump1eb44332009-09-09 15:08:12 +00004887
Nate Begemandde25982009-06-28 19:12:57 +00004888 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004889 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004890 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004891 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004892 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004893}
4894
Chris Lattner7ef655a2010-01-12 21:23:57 +00004895QualType Sema::CheckMultiplyDivideOperands(
4896 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004897 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004898 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004899
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004900 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004901
Chris Lattner7ef655a2010-01-12 21:23:57 +00004902 if (!lex->getType()->isArithmeticType() ||
4903 !rex->getType()->isArithmeticType())
4904 return InvalidOperands(Loc, lex, rex);
4905
4906 // Check for division by zero.
4907 if (isDiv &&
4908 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004909 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4910 << rex->getSourceRange());
Chris Lattner7ef655a2010-01-12 21:23:57 +00004911
4912 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004913}
4914
Chris Lattner7ef655a2010-01-12 21:23:57 +00004915QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004916 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004917 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4918 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4919 return CheckVectorOperands(Loc, lex, rex);
4920 return InvalidOperands(Loc, lex, rex);
4921 }
Steve Naroff90045e82007-07-13 23:32:42 +00004922
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004923 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004924
Chris Lattner7ef655a2010-01-12 21:23:57 +00004925 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4926 return InvalidOperands(Loc, lex, rex);
4927
4928 // Check for remainder by zero.
4929 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004930 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4931 << rex->getSourceRange());
Chris Lattner7ef655a2010-01-12 21:23:57 +00004932
4933 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004934}
4935
Chris Lattner7ef655a2010-01-12 21:23:57 +00004936QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004937 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004938 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4939 QualType compType = CheckVectorOperands(Loc, lex, rex);
4940 if (CompLHSTy) *CompLHSTy = compType;
4941 return compType;
4942 }
Steve Naroff49b45262007-07-13 16:58:59 +00004943
Eli Friedmanab3a8522009-03-28 01:22:36 +00004944 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004945
Reid Spencer5f016e22007-07-11 17:01:13 +00004946 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004947 if (lex->getType()->isArithmeticType() &&
4948 rex->getType()->isArithmeticType()) {
4949 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004950 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004951 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004952
Eli Friedmand72d16e2008-05-18 18:08:51 +00004953 // Put any potential pointer into PExp
4954 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004955 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004956 std::swap(PExp, IExp);
4957
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004958 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004959
Eli Friedmand72d16e2008-05-18 18:08:51 +00004960 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004961 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Chris Lattnerb5f15622009-04-24 23:50:08 +00004963 // Check for arithmetic on pointers to incomplete types.
4964 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004965 if (getLangOptions().CPlusPlus) {
4966 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004967 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004968 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004969 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004970
4971 // GNU extension: arithmetic on pointer to void
4972 Diag(Loc, diag::ext_gnu_void_ptr)
4973 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004974 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004975 if (getLangOptions().CPlusPlus) {
4976 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4977 << lex->getType() << lex->getSourceRange();
4978 return QualType();
4979 }
4980
4981 // GNU extension: arithmetic on pointer to function
4982 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4983 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004984 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004985 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004986 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004987 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004988 PExp->getType()->isObjCObjectPointerType()) &&
4989 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004990 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4991 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004992 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004993 return QualType();
4994 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004995 // Diagnose bad cases where we step over interface counts.
4996 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4997 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4998 << PointeeTy << PExp->getSourceRange();
4999 return QualType();
5000 }
Mike Stump1eb44332009-09-09 15:08:12 +00005001
Eli Friedmanab3a8522009-03-28 01:22:36 +00005002 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005003 QualType LHSTy = Context.isPromotableBitField(lex);
5004 if (LHSTy.isNull()) {
5005 LHSTy = lex->getType();
5006 if (LHSTy->isPromotableIntegerType())
5007 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005008 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005009 *CompLHSTy = LHSTy;
5010 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005011 return PExp->getType();
5012 }
5013 }
5014
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005015 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005016}
5017
Chris Lattnereca7be62008-04-07 05:30:13 +00005018// C99 6.5.6
5019QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005020 SourceLocation Loc, QualType* CompLHSTy) {
5021 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5022 QualType compType = CheckVectorOperands(Loc, lex, rex);
5023 if (CompLHSTy) *CompLHSTy = compType;
5024 return compType;
5025 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005026
Eli Friedmanab3a8522009-03-28 01:22:36 +00005027 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005028
Chris Lattner6e4ab612007-12-09 21:53:25 +00005029 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005030
Chris Lattner6e4ab612007-12-09 21:53:25 +00005031 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005032 if (lex->getType()->isArithmeticType()
5033 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005034 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005035 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005036 }
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Chris Lattner6e4ab612007-12-09 21:53:25 +00005038 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005039 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005040 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005041
Douglas Gregore7450f52009-03-24 19:52:54 +00005042 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005043
Douglas Gregore7450f52009-03-24 19:52:54 +00005044 bool ComplainAboutVoid = false;
5045 Expr *ComplainAboutFunc = 0;
5046 if (lpointee->isVoidType()) {
5047 if (getLangOptions().CPlusPlus) {
5048 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5049 << lex->getSourceRange() << rex->getSourceRange();
5050 return QualType();
5051 }
5052
5053 // GNU C extension: arithmetic on pointer to void
5054 ComplainAboutVoid = true;
5055 } else if (lpointee->isFunctionType()) {
5056 if (getLangOptions().CPlusPlus) {
5057 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005058 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005059 return QualType();
5060 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005061
5062 // GNU C extension: arithmetic on pointer to function
5063 ComplainAboutFunc = lex;
5064 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005065 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005066 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005067 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005068 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005069 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005070
Chris Lattnerb5f15622009-04-24 23:50:08 +00005071 // Diagnose bad cases where we step over interface counts.
5072 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5073 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5074 << lpointee << lex->getSourceRange();
5075 return QualType();
5076 }
Mike Stump1eb44332009-09-09 15:08:12 +00005077
Chris Lattner6e4ab612007-12-09 21:53:25 +00005078 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005079 if (rex->getType()->isIntegerType()) {
5080 if (ComplainAboutVoid)
5081 Diag(Loc, diag::ext_gnu_void_ptr)
5082 << lex->getSourceRange() << rex->getSourceRange();
5083 if (ComplainAboutFunc)
5084 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005085 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005086 << ComplainAboutFunc->getSourceRange();
5087
Eli Friedmanab3a8522009-03-28 01:22:36 +00005088 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005089 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005090 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005091
Chris Lattner6e4ab612007-12-09 21:53:25 +00005092 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005093 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005094 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005095
Douglas Gregore7450f52009-03-24 19:52:54 +00005096 // RHS must be a completely-type object type.
5097 // Handle the GNU void* extension.
5098 if (rpointee->isVoidType()) {
5099 if (getLangOptions().CPlusPlus) {
5100 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5101 << lex->getSourceRange() << rex->getSourceRange();
5102 return QualType();
5103 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005104
Douglas Gregore7450f52009-03-24 19:52:54 +00005105 ComplainAboutVoid = true;
5106 } else if (rpointee->isFunctionType()) {
5107 if (getLangOptions().CPlusPlus) {
5108 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005109 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005110 return QualType();
5111 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005112
5113 // GNU extension: arithmetic on pointer to function
5114 if (!ComplainAboutFunc)
5115 ComplainAboutFunc = rex;
5116 } else if (!rpointee->isDependentType() &&
5117 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005118 PDiag(diag::err_typecheck_sub_ptr_object)
5119 << rex->getSourceRange()
5120 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005121 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005122
Eli Friedman88d936b2009-05-16 13:54:38 +00005123 if (getLangOptions().CPlusPlus) {
5124 // Pointee types must be the same: C++ [expr.add]
5125 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5126 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5127 << lex->getType() << rex->getType()
5128 << lex->getSourceRange() << rex->getSourceRange();
5129 return QualType();
5130 }
5131 } else {
5132 // Pointee types must be compatible C99 6.5.6p3
5133 if (!Context.typesAreCompatible(
5134 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5135 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5136 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5137 << lex->getType() << rex->getType()
5138 << lex->getSourceRange() << rex->getSourceRange();
5139 return QualType();
5140 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005141 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005142
Douglas Gregore7450f52009-03-24 19:52:54 +00005143 if (ComplainAboutVoid)
5144 Diag(Loc, diag::ext_gnu_void_ptr)
5145 << lex->getSourceRange() << rex->getSourceRange();
5146 if (ComplainAboutFunc)
5147 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005148 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005149 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005150
5151 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005152 return Context.getPointerDiffType();
5153 }
5154 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005155
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005156 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005157}
5158
Chris Lattnereca7be62008-04-07 05:30:13 +00005159// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005160QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005161 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005162 // C99 6.5.7p2: Each of the operands shall have integer type.
5163 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005164 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005165
Nate Begeman2207d792009-10-25 02:26:48 +00005166 // Vector shifts promote their scalar inputs to vector type.
5167 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5168 return CheckVectorOperands(Loc, lex, rex);
5169
Chris Lattnerca5eede2007-12-12 05:47:28 +00005170 // Shifts don't perform usual arithmetic conversions, they just do integer
5171 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005172 QualType LHSTy = Context.isPromotableBitField(lex);
5173 if (LHSTy.isNull()) {
5174 LHSTy = lex->getType();
5175 if (LHSTy->isPromotableIntegerType())
5176 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005177 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005178 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005179 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005180
Chris Lattnerca5eede2007-12-12 05:47:28 +00005181 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005182
Ryan Flynnd0439682009-08-07 16:20:20 +00005183 // Sanity-check shift operands
5184 llvm::APSInt Right;
5185 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005186 if (!rex->isValueDependent() &&
5187 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005188 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005189 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5190 else {
5191 llvm::APInt LeftBits(Right.getBitWidth(),
5192 Context.getTypeSize(lex->getType()));
5193 if (Right.uge(LeftBits))
5194 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5195 }
5196 }
5197
Chris Lattnerca5eede2007-12-12 05:47:28 +00005198 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005199 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005200}
5201
Douglas Gregor0c6db942009-05-04 06:07:12 +00005202// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005203QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005204 unsigned OpaqueOpc, bool isRelational) {
5205 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5206
Chris Lattner02dd4b12009-12-05 05:40:13 +00005207 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005208 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005209 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005210
John McCall5dbad3d2009-11-06 08:49:08 +00005211 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5212 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005213
Chris Lattnera5937dd2007-08-26 01:18:55 +00005214 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005215 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5216 UsualArithmeticConversions(lex, rex);
5217 else {
5218 UsualUnaryConversions(lex);
5219 UsualUnaryConversions(rex);
5220 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005221 QualType lType = lex->getType();
5222 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005223
Mike Stumpaf199f32009-05-07 18:43:07 +00005224 if (!lType->isFloatingType()
5225 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005226 // For non-floating point types, check for self-comparisons of the form
5227 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5228 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005229 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005230 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005231 Expr *LHSStripped = lex->IgnoreParens();
5232 Expr *RHSStripped = rex->IgnoreParens();
5233 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5234 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005235 if (DRL->getDecl() == DRR->getDecl() &&
5236 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005237 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump1eb44332009-09-09 15:08:12 +00005238
Chris Lattner55660a72009-03-08 19:39:53 +00005239 if (isa<CastExpr>(LHSStripped))
5240 LHSStripped = LHSStripped->IgnoreParenCasts();
5241 if (isa<CastExpr>(RHSStripped))
5242 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Chris Lattner55660a72009-03-08 19:39:53 +00005244 // Warn about comparisons against a string constant (unless the other
5245 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005246 Expr *literalString = 0;
5247 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005248 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005249 !RHSStripped->isNullPointerConstant(Context,
5250 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005251 literalString = lex;
5252 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005253 } else if ((isa<StringLiteral>(RHSStripped) ||
5254 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005255 !LHSStripped->isNullPointerConstant(Context,
5256 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005257 literalString = rex;
5258 literalStringStripped = RHSStripped;
5259 }
5260
5261 if (literalString) {
5262 std::string resultComparison;
5263 switch (Opc) {
5264 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5265 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5266 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5267 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5268 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5269 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5270 default: assert(false && "Invalid comparison operator");
5271 }
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005272
5273 DiagRuntimeBehavior(Loc,
5274 PDiag(diag::warn_stringcompare)
5275 << isa<ObjCEncodeExpr>(literalStringStripped)
5276 << literalString->getSourceRange()
5277 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5278 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5279 "strcmp(")
5280 << CodeModificationHint::CreateInsertion(
5281 PP.getLocForEndOfToken(rex->getLocEnd()),
5282 resultComparison));
Douglas Gregora86b8322009-04-06 18:45:53 +00005283 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005284 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005285
Douglas Gregor447b69e2008-11-19 03:25:36 +00005286 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005287 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005288
Chris Lattnera5937dd2007-08-26 01:18:55 +00005289 if (isRelational) {
5290 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005291 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005292 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005293 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005294 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005295 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005296
Chris Lattnera5937dd2007-08-26 01:18:55 +00005297 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005298 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005299 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005300
Douglas Gregorce940492009-09-25 04:25:58 +00005301 bool LHSIsNull = lex->isNullPointerConstant(Context,
5302 Expr::NPC_ValueDependentIsNull);
5303 bool RHSIsNull = rex->isNullPointerConstant(Context,
5304 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005305
Chris Lattnera5937dd2007-08-26 01:18:55 +00005306 // All of the following pointer related warnings are GCC extensions, except
5307 // when handling null pointer constants. One day, we can consider making them
5308 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005309 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005310 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005311 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005312 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005313 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005314
Douglas Gregor0c6db942009-05-04 06:07:12 +00005315 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005316 if (LCanPointeeTy == RCanPointeeTy)
5317 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005318 if (!isRelational &&
5319 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5320 // Valid unless comparison between non-null pointer and function pointer
5321 // This is a gcc extension compatibility comparison.
5322 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5323 && !LHSIsNull && !RHSIsNull) {
5324 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5325 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5326 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5327 return ResultTy;
5328 }
5329 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005330 // C++ [expr.rel]p2:
5331 // [...] Pointer conversions (4.10) and qualification
5332 // conversions (4.4) are performed on pointer operands (or on
5333 // a pointer operand and a null pointer constant) to bring
5334 // them to their composite pointer type. [...]
5335 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005336 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005337 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005338 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005339 if (T.isNull()) {
5340 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5341 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5342 return QualType();
5343 }
5344
Eli Friedman73c39ab2009-10-20 08:27:19 +00005345 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5346 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005347 return ResultTy;
5348 }
Eli Friedman3075e762009-08-23 00:27:47 +00005349 // C99 6.5.9p2 and C99 6.5.8p2
5350 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5351 RCanPointeeTy.getUnqualifiedType())) {
5352 // Valid unless a relational comparison of function pointers
5353 if (isRelational && LCanPointeeTy->isFunctionType()) {
5354 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5355 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5356 }
5357 } else if (!isRelational &&
5358 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5359 // Valid unless comparison between non-null pointer and function pointer
5360 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5361 && !LHSIsNull && !RHSIsNull) {
5362 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5363 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5364 }
5365 } else {
5366 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005367 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005368 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005369 }
Eli Friedman3075e762009-08-23 00:27:47 +00005370 if (LCanPointeeTy != RCanPointeeTy)
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 Naroffe77fd3c2007-08-16 21:48:38 +00005373 }
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005375 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005376 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005377 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005378 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005379 (lType->isPointerType() ||
5380 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005381 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005382 return ResultTy;
5383 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005384 if (LHSIsNull &&
5385 (rType->isPointerType() ||
5386 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005387 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005388 return ResultTy;
5389 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005390
5391 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005392 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005393 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5394 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005395 // In addition, pointers to members can be compared, or a pointer to
5396 // member and a null pointer constant. Pointer to member conversions
5397 // (4.11) and qualification conversions (4.4) are performed to bring
5398 // them to a common type. If one operand is a null pointer constant,
5399 // the common type is the type of the other operand. Otherwise, the
5400 // common type is a pointer to member type similar (4.4) to the type
5401 // of one of the operands, with a cv-qualification signature (4.4)
5402 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005403 // types.
5404 QualType T = FindCompositePointerType(lex, rex);
5405 if (T.isNull()) {
5406 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5407 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5408 return QualType();
5409 }
Mike Stump1eb44332009-09-09 15:08:12 +00005410
Eli Friedman73c39ab2009-10-20 08:27:19 +00005411 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5412 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005413 return ResultTy;
5414 }
Mike Stump1eb44332009-09-09 15:08:12 +00005415
Douglas Gregor20b3e992009-08-24 17:42:35 +00005416 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005417 if (lType->isNullPtrType() && rType->isNullPtrType())
5418 return ResultTy;
5419 }
Mike Stump1eb44332009-09-09 15:08:12 +00005420
Steve Naroff1c7d0672008-09-04 15:10:53 +00005421 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005422 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005423 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5424 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005425
Steve Naroff1c7d0672008-09-04 15:10:53 +00005426 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005427 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005428 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005429 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005430 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005431 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005432 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005433 }
Steve Naroff59f53942008-09-28 01:11:11 +00005434 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005435 if (!isRelational
5436 && ((lType->isBlockPointerType() && rType->isPointerType())
5437 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005438 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005439 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005440 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005441 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005442 ->getPointeeType()->isVoidType())))
5443 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5444 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005445 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005446 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005447 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005448 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005449
Steve Naroff14108da2009-07-10 23:34:53 +00005450 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005451 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005452 const PointerType *LPT = lType->getAs<PointerType>();
5453 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005455 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005456 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005457 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005458
Steve Naroffa8069f12008-11-17 19:49:16 +00005459 if (!LPtrToVoid && !RPtrToVoid &&
5460 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005461 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005462 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005463 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005464 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005465 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005466 }
Steve Naroff14108da2009-07-10 23:34:53 +00005467 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005468 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005469 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5470 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005471 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005472 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005473 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005474 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005475 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005476 unsigned DiagID = 0;
5477 if (RHSIsNull) {
5478 if (isRelational)
5479 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5480 } else if (isRelational)
5481 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5482 else
5483 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005485 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005486 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005487 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005488 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005489 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005490 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005491 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005492 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005493 unsigned DiagID = 0;
5494 if (LHSIsNull) {
5495 if (isRelational)
5496 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5497 } else if (isRelational)
5498 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5499 else
5500 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005501
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005502 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005503 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005504 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005505 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005506 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005507 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005508 }
Steve Naroff39218df2008-09-04 16:56:14 +00005509 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005510 if (!isRelational && RHSIsNull
5511 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005512 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005513 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005514 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005515 if (!isRelational && LHSIsNull
5516 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005517 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005518 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005519 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005520 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005521}
5522
Nate Begemanbe2341d2008-07-14 18:02:46 +00005523/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005525/// like a scalar comparison, a vector comparison produces a vector of integer
5526/// types.
5527QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005528 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005529 bool isRelational) {
5530 // Check to make sure we're operating on vectors of the same type and width,
5531 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005532 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005533 if (vType.isNull())
5534 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005535
Nate Begemanbe2341d2008-07-14 18:02:46 +00005536 QualType lType = lex->getType();
5537 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005538
Nate Begemanbe2341d2008-07-14 18:02:46 +00005539 // For non-floating point types, check for self-comparisons of the form
5540 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5541 // often indicate logic errors in the program.
5542 if (!lType->isFloatingType()) {
5543 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5544 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5545 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005546 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begemanbe2341d2008-07-14 18:02:46 +00005547 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005548
Nate Begemanbe2341d2008-07-14 18:02:46 +00005549 // Check for comparisons of floating point operands using != and ==.
5550 if (!isRelational && lType->isFloatingType()) {
5551 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005552 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005553 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005554
Nate Begemanbe2341d2008-07-14 18:02:46 +00005555 // Return the type for the comparison, which is the same as vector type for
5556 // integer vectors, or an integer type of identical size and number of
5557 // elements for floating point vectors.
5558 if (lType->isIntegerType())
5559 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005560
John McCall183700f2009-09-21 23:43:11 +00005561 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005562 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005563 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005564 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005565 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005566 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5567
Mike Stumpeed9cac2009-02-19 03:04:26 +00005568 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005569 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005570 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5571}
5572
Reid Spencer5f016e22007-07-11 17:01:13 +00005573inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005574 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005575 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005576 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005577
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005578 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005579
Steve Naroffa4332e22007-07-17 00:58:39 +00005580 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005581 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005582 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005583}
5584
5585inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005586 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005587 if (!Context.getLangOptions().CPlusPlus) {
5588 UsualUnaryConversions(lex);
5589 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005590
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005591 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5592 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005593
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005594 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005595 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005596
5597 // C++ [expr.log.and]p1
5598 // C++ [expr.log.or]p1
5599 // The operands are both implicitly converted to type bool (clause 4).
5600 StandardConversionSequence LHS;
5601 if (!IsStandardConversion(lex, Context.BoolTy,
5602 /*InOverloadResolution=*/false, LHS))
5603 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005604
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005605 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005606 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005607 return InvalidOperands(Loc, lex, rex);
5608
5609 StandardConversionSequence RHS;
5610 if (!IsStandardConversion(rex, Context.BoolTy,
5611 /*InOverloadResolution=*/false, RHS))
5612 return InvalidOperands(Loc, lex, rex);
5613
5614 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005615 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005616 return InvalidOperands(Loc, lex, rex);
5617
5618 // C++ [expr.log.and]p2
5619 // C++ [expr.log.or]p2
5620 // The result is a bool.
5621 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005622}
5623
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005624/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5625/// is a read-only property; return true if so. A readonly property expression
5626/// depends on various declarations and thus must be treated specially.
5627///
Mike Stump1eb44332009-09-09 15:08:12 +00005628static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005629 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5630 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5631 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5632 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005633 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005634 BaseType->getAsObjCInterfacePointerType())
5635 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5636 if (S.isPropertyReadonly(PDecl, IFace))
5637 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005638 }
5639 }
5640 return false;
5641}
5642
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005643/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5644/// emit an error and return true. If so, return false.
5645static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005646 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005647 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005648 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005649 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5650 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005651 if (IsLV == Expr::MLV_Valid)
5652 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005653
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005654 unsigned Diag = 0;
5655 bool NeedType = false;
5656 switch (IsLV) { // C99 6.5.16p2
5657 default: assert(0 && "Unknown result from isModifiableLvalue!");
5658 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005659 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005660 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5661 NeedType = true;
5662 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005663 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005664 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5665 NeedType = true;
5666 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005667 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005668 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5669 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005670 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005671 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5672 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005673 case Expr::MLV_IncompleteType:
5674 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005675 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005676 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5677 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005678 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005679 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5680 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005681 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005682 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5683 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005684 case Expr::MLV_ReadonlyProperty:
5685 Diag = diag::error_readonly_property_assignment;
5686 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005687 case Expr::MLV_NoSetterProperty:
5688 Diag = diag::error_nosetter_property_assignment;
5689 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005690 case Expr::MLV_SubObjCPropertySetting:
5691 Diag = diag::error_no_subobject_property_setting;
5692 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005693 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005694
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005695 SourceRange Assign;
5696 if (Loc != OrigLoc)
5697 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005698 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005699 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005700 else
Mike Stump1eb44332009-09-09 15:08:12 +00005701 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005702 return true;
5703}
5704
5705
5706
5707// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005708QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5709 SourceLocation Loc,
5710 QualType CompoundType) {
5711 // Verify that LHS is a modifiable lvalue, and emit error if not.
5712 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005713 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005714
5715 QualType LHSType = LHS->getType();
5716 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005717
Chris Lattner5cf216b2008-01-04 18:04:52 +00005718 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005719 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005720 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005721 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005722 // Special case of NSObject attributes on c-style pointer types.
5723 if (ConvTy == IncompatiblePointer &&
5724 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005725 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005726 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005727 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005728 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005729
Chris Lattner2c156472008-08-21 18:04:13 +00005730 // If the RHS is a unary plus or minus, check to see if they = and + are
5731 // right next to each other. If so, the user may have typo'd "x =+ 4"
5732 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005733 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005734 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5735 RHSCheck = ICE->getSubExpr();
5736 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5737 if ((UO->getOpcode() == UnaryOperator::Plus ||
5738 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005739 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005740 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005741 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5742 // And there is a space or other character before the subexpr of the
5743 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005744 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5745 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005746 Diag(Loc, diag::warn_not_compound_assign)
5747 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5748 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005749 }
Chris Lattner2c156472008-08-21 18:04:13 +00005750 }
5751 } else {
5752 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005753 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005754 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005755
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005756 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005757 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005758 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005759
Reid Spencer5f016e22007-07-11 17:01:13 +00005760 // C99 6.5.16p3: The type of an assignment expression is the type of the
5761 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005762 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005763 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5764 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005765 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005766 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005767 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005768}
5769
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005770// C99 6.5.17
5771QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005772 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005773 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005774
5775 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5776 // incomplete in C++).
5777
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005778 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005779}
5780
Steve Naroff49b45262007-07-13 16:58:59 +00005781/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5782/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005783QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5784 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005785 if (Op->isTypeDependent())
5786 return Context.DependentTy;
5787
Chris Lattner3528d352008-11-21 07:05:48 +00005788 QualType ResType = Op->getType();
5789 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005790
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005791 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5792 // Decrement of bool is not allowed.
5793 if (!isInc) {
5794 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5795 return QualType();
5796 }
5797 // Increment of bool sets it to true, but is deprecated.
5798 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5799 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005800 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005801 } else if (ResType->isAnyPointerType()) {
5802 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005803
Chris Lattner3528d352008-11-21 07:05:48 +00005804 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005805 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005806 if (getLangOptions().CPlusPlus) {
5807 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5808 << Op->getSourceRange();
5809 return QualType();
5810 }
5811
5812 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005813 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005814 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005815 if (getLangOptions().CPlusPlus) {
5816 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5817 << Op->getType() << Op->getSourceRange();
5818 return QualType();
5819 }
5820
5821 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005822 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005823 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005824 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005825 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005826 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005827 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005828 // Diagnose bad cases where we step over interface counts.
5829 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5830 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5831 << PointeeTy << Op->getSourceRange();
5832 return QualType();
5833 }
Eli Friedman5b088a12010-01-03 00:20:48 +00005834 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005835 // C99 does not support ++/-- on complex types, we allow as an extension.
5836 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005837 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005838 } else {
5839 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005840 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005841 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005842 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005843 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005844 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005845 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005846 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005847 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005848}
5849
Anders Carlsson369dee42008-02-01 07:15:58 +00005850/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005851/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005852/// where the declaration is needed for type checking. We only need to
5853/// handle cases when the expression references a function designator
5854/// or is an lvalue. Here are some examples:
5855/// - &(x) => x
5856/// - &*****f => f for f a function designator.
5857/// - &s.xx => s
5858/// - &s.zz[1].yy -> s, if zz is an array
5859/// - *(x + 1) -> x, if x is an array
5860/// - &"123"[2] -> 0
5861/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005862static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005863 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005864 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005865 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005866 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005867 // If this is an arrow operator, the address is an offset from
5868 // the base's value, so the object the base refers to is
5869 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005870 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005871 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005872 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005873 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005874 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005875 // FIXME: This code shouldn't be necessary! We should catch the implicit
5876 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005877 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5878 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5879 if (ICE->getSubExpr()->getType()->isArrayType())
5880 return getPrimaryDecl(ICE->getSubExpr());
5881 }
5882 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005883 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005884 case Stmt::UnaryOperatorClass: {
5885 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005886
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005887 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005888 case UnaryOperator::Real:
5889 case UnaryOperator::Imag:
5890 case UnaryOperator::Extension:
5891 return getPrimaryDecl(UO->getSubExpr());
5892 default:
5893 return 0;
5894 }
5895 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005896 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005897 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005898 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005899 // If the result of an implicit cast is an l-value, we care about
5900 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005901 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005902 default:
5903 return 0;
5904 }
5905}
5906
5907/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005908/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005909/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005910/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005911/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005912/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005913/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005914QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005915 // Make sure to ignore parentheses in subsequent checks
5916 op = op->IgnoreParens();
5917
Douglas Gregor9103bb22008-12-17 22:52:20 +00005918 if (op->isTypeDependent())
5919 return Context.DependentTy;
5920
Steve Naroff08f19672008-01-13 17:10:08 +00005921 if (getLangOptions().C99) {
5922 // Implement C99-only parts of addressof rules.
5923 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5924 if (uOp->getOpcode() == UnaryOperator::Deref)
5925 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5926 // (assuming the deref expression is valid).
5927 return uOp->getSubExpr()->getType();
5928 }
5929 // Technically, there should be a check for array subscript
5930 // expressions here, but the result of one is always an lvalue anyway.
5931 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005932 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005933 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005934
Sebastian Redle27d87f2010-01-11 15:56:56 +00005935 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5936 if (lval == Expr::LV_MemberFunction && ME &&
5937 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5938 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5939 // &f where f is a member of the current object, or &o.f, or &p->f
5940 // All these are not allowed, and we need to catch them before the dcl
5941 // branch of the if, below.
5942 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5943 << dcl;
5944 // FIXME: Improve this diagnostic and provide a fixit.
5945
5946 // Now recover by acting as if the function had been accessed qualified.
5947 return Context.getMemberPointerType(op->getType(),
5948 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5949 .getTypePtr());
5950 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00005951 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005952 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005953 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005954 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005955 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5956 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005957 return QualType();
5958 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005959 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005960 // The operand cannot be a bit-field
5961 Diag(OpLoc, diag::err_typecheck_address_of)
5962 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005963 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005964 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5965 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005966 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005967 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005968 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005969 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005970 } else if (isa<ObjCPropertyRefExpr>(op)) {
5971 // cannot take address of a property expression.
5972 Diag(OpLoc, diag::err_typecheck_address_of)
5973 << "property expression" << op->getSourceRange();
5974 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005975 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5976 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005977 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5978 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005979 } else if (isa<UnresolvedLookupExpr>(op)) {
5980 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005981 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005982 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005983 // with the register storage-class specifier.
5984 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5985 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005986 Diag(OpLoc, diag::err_typecheck_address_of)
5987 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005988 return QualType();
5989 }
John McCallba135432009-11-21 08:51:07 +00005990 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005991 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005992 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005993 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005994 // Could be a pointer to member, though, if there is an explicit
5995 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005996 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005997 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005998 if (Ctx && Ctx->isRecord()) {
5999 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006000 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006001 diag::err_cannot_form_pointer_to_member_of_reference_type)
6002 << FD->getDeclName() << FD->getType();
6003 return QualType();
6004 }
Mike Stump1eb44332009-09-09 15:08:12 +00006005
Sebastian Redlebc07d52009-02-03 20:19:35 +00006006 return Context.getMemberPointerType(op->getType(),
6007 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006008 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006009 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006010 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006011 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006012 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006013 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6014 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006015 return Context.getMemberPointerType(op->getType(),
6016 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6017 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006018 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006019 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006020
Eli Friedman441cf102009-05-16 23:27:50 +00006021 if (lval == Expr::LV_IncompleteVoidType) {
6022 // Taking the address of a void variable is technically illegal, but we
6023 // allow it in cases which are otherwise valid.
6024 // Example: "extern void x; void* y = &x;".
6025 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6026 }
6027
Reid Spencer5f016e22007-07-11 17:01:13 +00006028 // If the operand has type "type", the result has type "pointer to type".
6029 return Context.getPointerType(op->getType());
6030}
6031
Chris Lattner22caddc2008-11-23 09:13:29 +00006032QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006033 if (Op->isTypeDependent())
6034 return Context.DependentTy;
6035
Chris Lattner22caddc2008-11-23 09:13:29 +00006036 UsualUnaryConversions(Op);
6037 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006038
Chris Lattner22caddc2008-11-23 09:13:29 +00006039 // Note that per both C89 and C99, this is always legal, even if ptype is an
6040 // incomplete type or void. It would be possible to warn about dereferencing
6041 // a void pointer, but it's completely well-defined, and such a warning is
6042 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00006043 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00006044 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006045
John McCall183700f2009-09-21 23:43:11 +00006046 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00006047 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00006048
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006049 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00006050 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006051 return QualType();
6052}
6053
6054static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6055 tok::TokenKind Kind) {
6056 BinaryOperator::Opcode Opc;
6057 switch (Kind) {
6058 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006059 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6060 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006061 case tok::star: Opc = BinaryOperator::Mul; break;
6062 case tok::slash: Opc = BinaryOperator::Div; break;
6063 case tok::percent: Opc = BinaryOperator::Rem; break;
6064 case tok::plus: Opc = BinaryOperator::Add; break;
6065 case tok::minus: Opc = BinaryOperator::Sub; break;
6066 case tok::lessless: Opc = BinaryOperator::Shl; break;
6067 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6068 case tok::lessequal: Opc = BinaryOperator::LE; break;
6069 case tok::less: Opc = BinaryOperator::LT; break;
6070 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6071 case tok::greater: Opc = BinaryOperator::GT; break;
6072 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6073 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6074 case tok::amp: Opc = BinaryOperator::And; break;
6075 case tok::caret: Opc = BinaryOperator::Xor; break;
6076 case tok::pipe: Opc = BinaryOperator::Or; break;
6077 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6078 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6079 case tok::equal: Opc = BinaryOperator::Assign; break;
6080 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6081 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6082 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6083 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6084 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6085 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6086 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6087 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6088 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6089 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6090 case tok::comma: Opc = BinaryOperator::Comma; break;
6091 }
6092 return Opc;
6093}
6094
6095static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6096 tok::TokenKind Kind) {
6097 UnaryOperator::Opcode Opc;
6098 switch (Kind) {
6099 default: assert(0 && "Unknown unary op!");
6100 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6101 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6102 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6103 case tok::star: Opc = UnaryOperator::Deref; break;
6104 case tok::plus: Opc = UnaryOperator::Plus; break;
6105 case tok::minus: Opc = UnaryOperator::Minus; break;
6106 case tok::tilde: Opc = UnaryOperator::Not; break;
6107 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006108 case tok::kw___real: Opc = UnaryOperator::Real; break;
6109 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6110 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6111 }
6112 return Opc;
6113}
6114
Douglas Gregoreaebc752008-11-06 23:29:22 +00006115/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6116/// operator @p Opc at location @c TokLoc. This routine only supports
6117/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006118Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6119 unsigned Op,
6120 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006121 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006122 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006123 // The following two variables are used for compound assignment operators
6124 QualType CompLHSTy; // Type of LHS after promotions for computation
6125 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006126
6127 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006128 case BinaryOperator::Assign:
6129 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6130 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006131 case BinaryOperator::PtrMemD:
6132 case BinaryOperator::PtrMemI:
6133 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6134 Opc == BinaryOperator::PtrMemI);
6135 break;
6136 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006137 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006138 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6139 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006140 break;
6141 case BinaryOperator::Rem:
6142 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6143 break;
6144 case BinaryOperator::Add:
6145 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6146 break;
6147 case BinaryOperator::Sub:
6148 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6149 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006150 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006151 case BinaryOperator::Shr:
6152 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6153 break;
6154 case BinaryOperator::LE:
6155 case BinaryOperator::LT:
6156 case BinaryOperator::GE:
6157 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006158 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006159 break;
6160 case BinaryOperator::EQ:
6161 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006162 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006163 break;
6164 case BinaryOperator::And:
6165 case BinaryOperator::Xor:
6166 case BinaryOperator::Or:
6167 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6168 break;
6169 case BinaryOperator::LAnd:
6170 case BinaryOperator::LOr:
6171 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6172 break;
6173 case BinaryOperator::MulAssign:
6174 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006175 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6176 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006177 CompLHSTy = CompResultTy;
6178 if (!CompResultTy.isNull())
6179 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006180 break;
6181 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006182 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6183 CompLHSTy = CompResultTy;
6184 if (!CompResultTy.isNull())
6185 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006186 break;
6187 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006188 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6189 if (!CompResultTy.isNull())
6190 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006191 break;
6192 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006193 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6194 if (!CompResultTy.isNull())
6195 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006196 break;
6197 case BinaryOperator::ShlAssign:
6198 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006199 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6200 CompLHSTy = CompResultTy;
6201 if (!CompResultTy.isNull())
6202 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006203 break;
6204 case BinaryOperator::AndAssign:
6205 case BinaryOperator::XorAssign:
6206 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006207 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6208 CompLHSTy = CompResultTy;
6209 if (!CompResultTy.isNull())
6210 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006211 break;
6212 case BinaryOperator::Comma:
6213 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6214 break;
6215 }
6216 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006217 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006218 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006219 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6220 else
6221 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006222 CompLHSTy, CompResultTy,
6223 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006224}
6225
Sebastian Redlaee3c932009-10-27 12:10:02 +00006226/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6227/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006228static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6229 const PartialDiagnostic &PD,
Douglas Gregor827feec2010-01-08 00:20:23 +00006230 SourceRange ParenRange,
6231 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6232 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006233 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6234 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6235 // We can't display the parentheses, so just dig the
6236 // warning/error and return.
6237 Self.Diag(Loc, PD);
6238 return;
6239 }
6240
6241 Self.Diag(Loc, PD)
6242 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6243 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00006244
6245 if (!SecondPD.getDiagID())
6246 return;
6247
6248 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6249 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6250 // We can't display the parentheses, so just dig the
6251 // warning/error and return.
6252 Self.Diag(Loc, SecondPD);
6253 return;
6254 }
6255
6256 Self.Diag(Loc, SecondPD)
6257 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6258 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006259}
6260
Sebastian Redlaee3c932009-10-27 12:10:02 +00006261/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6262/// operators are mixed in a way that suggests that the programmer forgot that
6263/// comparison operators have higher precedence. The most typical example of
6264/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006265static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6266 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006267 typedef BinaryOperator BinOp;
6268 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6269 rhsopc = static_cast<BinOp::Opcode>(-1);
6270 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006271 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006272 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006273 rhsopc = BO->getOpcode();
6274
6275 // Subs are not binary operators.
6276 if (lhsopc == -1 && rhsopc == -1)
6277 return;
6278
6279 // Bitwise operations are sometimes used as eager logical ops.
6280 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006281 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6282 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006283 return;
6284
Sebastian Redlaee3c932009-10-27 12:10:02 +00006285 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006286 SuggestParentheses(Self, OpLoc,
6287 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006288 << SourceRange(lhs->getLocStart(), OpLoc)
6289 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006290 lhs->getSourceRange(),
6291 PDiag(diag::note_precedence_bitwise_first)
6292 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006293 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6294 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006295 SuggestParentheses(Self, OpLoc,
6296 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006297 << SourceRange(OpLoc, rhs->getLocEnd())
6298 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006299 rhs->getSourceRange(),
6300 PDiag(diag::note_precedence_bitwise_first)
6301 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006302 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006303}
6304
6305/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6306/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6307/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6308static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6309 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006310 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006311 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6312}
6313
Reid Spencer5f016e22007-07-11 17:01:13 +00006314// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006315Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6316 tok::TokenKind Kind,
6317 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006318 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006319 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006320
Steve Narofff69936d2007-09-16 03:34:24 +00006321 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6322 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006323
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006324 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6325 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6326
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006327 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6328}
6329
6330Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6331 BinaryOperator::Opcode Opc,
6332 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006333 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006334 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006335 rhs->getType()->isOverloadableType())) {
6336 // Find all of the overloaded operators visible from this
6337 // point. We perform both an operator-name lookup from the local
6338 // scope and an argument-dependent lookup based on the types of
6339 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006340 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006341 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006342 if (S && OverOp != OO_None)
6343 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6344 Functions);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006345
Douglas Gregor063daf62009-03-13 18:40:31 +00006346 // Build the (potentially-overloaded, potentially-dependent)
6347 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006348 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006349 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006350
Douglas Gregoreaebc752008-11-06 23:29:22 +00006351 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006352 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006353}
6354
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006355Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006356 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006357 ExprArg InputArg) {
6358 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006359
Mike Stump390b4cc2009-05-16 07:39:55 +00006360 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006361 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006362 QualType resultType;
6363 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006364 case UnaryOperator::OffsetOf:
6365 assert(false && "Invalid unary operator");
6366 break;
6367
Reid Spencer5f016e22007-07-11 17:01:13 +00006368 case UnaryOperator::PreInc:
6369 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006370 case UnaryOperator::PostInc:
6371 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006372 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006373 Opc == UnaryOperator::PreInc ||
6374 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006375 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006376 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006377 resultType = CheckAddressOfOperand(Input, OpLoc);
6378 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006379 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006380 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006381 resultType = CheckIndirectionOperand(Input, OpLoc);
6382 break;
6383 case UnaryOperator::Plus:
6384 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006385 UsualUnaryConversions(Input);
6386 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006387 if (resultType->isDependentType())
6388 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006389 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6390 break;
6391 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6392 resultType->isEnumeralType())
6393 break;
6394 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6395 Opc == UnaryOperator::Plus &&
6396 resultType->isPointerType())
6397 break;
6398
Sebastian Redl0eb23302009-01-19 00:08:26 +00006399 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6400 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006401 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006402 UsualUnaryConversions(Input);
6403 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006404 if (resultType->isDependentType())
6405 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006406 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6407 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6408 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006409 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006410 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006411 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006412 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6413 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006414 break;
6415 case UnaryOperator::LNot: // logical negation
6416 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006417 DefaultFunctionArrayConversion(Input);
6418 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006419 if (resultType->isDependentType())
6420 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006421 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006422 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6423 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006424 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006425 // In C++, it's bool. C++ 5.3.1p8
6426 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006427 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006428 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006429 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006430 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006431 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006432 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006433 resultType = Input->getType();
6434 break;
6435 }
6436 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006437 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006438
6439 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006440 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006441}
6442
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006443Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6444 UnaryOperator::Opcode Opc,
6445 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006446 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006447 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6448 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006449 // Find all of the overloaded operators visible from this
6450 // point. We perform both an operator-name lookup from the local
6451 // scope and an argument-dependent lookup based on the types of
6452 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006453 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006454 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006455 if (S && OverOp != OO_None)
6456 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6457 Functions);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006458
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006459 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6460 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006461
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006462 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6463}
6464
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006465// Unary Operators. 'Tok' is the token for the operator.
6466Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6467 tok::TokenKind Op, ExprArg input) {
6468 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6469}
6470
Steve Naroff1b273c42007-09-16 14:56:35 +00006471/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006472Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6473 SourceLocation LabLoc,
6474 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006475 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006476 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006477
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006478 // If we haven't seen this label yet, create a forward reference. It
6479 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006480 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006481 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006482
Reid Spencer5f016e22007-07-11 17:01:13 +00006483 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006484 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6485 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006486}
6487
Sebastian Redlf53597f2009-03-15 17:47:39 +00006488Sema::OwningExprResult
6489Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6490 SourceLocation RPLoc) { // "({..})"
6491 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006492 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6493 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6494
Eli Friedmandca2b732009-01-24 23:09:00 +00006495 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006496 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006497 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006498
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006499 // FIXME: there are a variety of strange constraints to enforce here, for
6500 // example, it is not possible to goto into a stmt expression apparently.
6501 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006502
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006503 // If there are sub stmts in the compound stmt, take the type of the last one
6504 // as the type of the stmtexpr.
6505 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006506
Chris Lattner611b2ec2008-07-26 19:51:01 +00006507 if (!Compound->body_empty()) {
6508 Stmt *LastStmt = Compound->body_back();
6509 // If LastStmt is a label, skip down through into the body.
6510 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6511 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006512
Chris Lattner611b2ec2008-07-26 19:51:01 +00006513 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006514 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006515 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006516
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006517 // FIXME: Check that expression type is complete/non-abstract; statement
6518 // expressions are not lvalues.
6519
Sebastian Redlf53597f2009-03-15 17:47:39 +00006520 substmt.release();
6521 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006522}
Steve Naroffd34e9152007-08-01 22:05:33 +00006523
Sebastian Redlf53597f2009-03-15 17:47:39 +00006524Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6525 SourceLocation BuiltinLoc,
6526 SourceLocation TypeLoc,
6527 TypeTy *argty,
6528 OffsetOfComponent *CompPtr,
6529 unsigned NumComponents,
6530 SourceLocation RPLoc) {
6531 // FIXME: This function leaks all expressions in the offset components on
6532 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006533 // FIXME: Preserve type source info.
6534 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006535 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006536
Sebastian Redl28507842009-02-26 14:39:58 +00006537 bool Dependent = ArgTy->isDependentType();
6538
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006539 // We must have at least one component that refers to the type, and the first
6540 // one is known to be a field designator. Verify that the ArgTy represents
6541 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006542 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006543 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006544
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006545 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6546 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006547
Eli Friedman35183ac2009-02-27 06:44:11 +00006548 // Otherwise, create a null pointer as the base, and iteratively process
6549 // the offsetof designators.
6550 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6551 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006552 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006553 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006554
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006555 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6556 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006557 // FIXME: This diagnostic isn't actually visible because the location is in
6558 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006559 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006560 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6561 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006562
Sebastian Redl28507842009-02-26 14:39:58 +00006563 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006564 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006565
John McCalld00f2002009-11-04 03:03:43 +00006566 if (RequireCompleteType(TypeLoc, Res->getType(),
6567 diag::err_offsetof_incomplete_type))
6568 return ExprError();
6569
Sebastian Redl28507842009-02-26 14:39:58 +00006570 // FIXME: Dependent case loses a lot of information here. And probably
6571 // leaks like a sieve.
6572 for (unsigned i = 0; i != NumComponents; ++i) {
6573 const OffsetOfComponent &OC = CompPtr[i];
6574 if (OC.isBrackets) {
6575 // Offset of an array sub-field. TODO: Should we allow vector elements?
6576 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6577 if (!AT) {
6578 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006579 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6580 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006581 }
6582
6583 // FIXME: C++: Verify that operator[] isn't overloaded.
6584
Eli Friedman35183ac2009-02-27 06:44:11 +00006585 // Promote the array so it looks more like a normal array subscript
6586 // expression.
6587 DefaultFunctionArrayConversion(Res);
6588
Sebastian Redl28507842009-02-26 14:39:58 +00006589 // C99 6.5.2.1p1
6590 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006591 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006592 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006593 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006594 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006595 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006596
6597 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6598 OC.LocEnd);
6599 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006600 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006601
Ted Kremenek6217b802009-07-29 21:53:49 +00006602 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006603 if (!RC) {
6604 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006605 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6606 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006607 }
Chris Lattner704fe352007-08-30 17:59:59 +00006608
Sebastian Redl28507842009-02-26 14:39:58 +00006609 // Get the decl corresponding to this.
6610 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006611 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006612 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6613 DiagRuntimeBehavior(BuiltinLoc,
6614 PDiag(diag::warn_offsetof_non_pod_type)
6615 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6616 << Res->getType()))
6617 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006618 }
Mike Stump1eb44332009-09-09 15:08:12 +00006619
John McCalla24dc2e2009-11-17 02:14:36 +00006620 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6621 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006622
John McCall1bcee0a2009-12-02 08:25:40 +00006623 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006624 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006625 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006626 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6627 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006628
Sebastian Redl28507842009-02-26 14:39:58 +00006629 // FIXME: C++: Verify that MemberDecl isn't a static field.
6630 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006631 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006632 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006633 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006634 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006635 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006636 // MemberDecl->getType() doesn't get the right qualifiers, but it
6637 // doesn't matter here.
6638 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6639 MemberDecl->getType().getNonReferenceType());
6640 }
Sebastian Redl28507842009-02-26 14:39:58 +00006641 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006642 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006643
Sebastian Redlf53597f2009-03-15 17:47:39 +00006644 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6645 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006646}
6647
6648
Sebastian Redlf53597f2009-03-15 17:47:39 +00006649Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6650 TypeTy *arg1,TypeTy *arg2,
6651 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006652 // FIXME: Preserve type source info.
6653 QualType argT1 = GetTypeFromParser(arg1);
6654 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006655
Steve Naroffd34e9152007-08-01 22:05:33 +00006656 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006657
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006658 if (getLangOptions().CPlusPlus) {
6659 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6660 << SourceRange(BuiltinLoc, RPLoc);
6661 return ExprError();
6662 }
6663
Sebastian Redlf53597f2009-03-15 17:47:39 +00006664 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6665 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006666}
6667
Sebastian Redlf53597f2009-03-15 17:47:39 +00006668Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6669 ExprArg cond,
6670 ExprArg expr1, ExprArg expr2,
6671 SourceLocation RPLoc) {
6672 Expr *CondExpr = static_cast<Expr*>(cond.get());
6673 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6674 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006675
Steve Naroffd04fdd52007-08-03 21:21:27 +00006676 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6677
Sebastian Redl28507842009-02-26 14:39:58 +00006678 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006679 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006680 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006681 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006682 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006683 } else {
6684 // The conditional expression is required to be a constant expression.
6685 llvm::APSInt condEval(32);
6686 SourceLocation ExpLoc;
6687 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006688 return ExprError(Diag(ExpLoc,
6689 diag::err_typecheck_choose_expr_requires_constant)
6690 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006691
Sebastian Redl28507842009-02-26 14:39:58 +00006692 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6693 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006694 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6695 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006696 }
6697
Sebastian Redlf53597f2009-03-15 17:47:39 +00006698 cond.release(); expr1.release(); expr2.release();
6699 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006700 resType, RPLoc,
6701 resType->isDependentType(),
6702 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006703}
6704
Steve Naroff4eb206b2008-09-03 18:15:37 +00006705//===----------------------------------------------------------------------===//
6706// Clang Extensions.
6707//===----------------------------------------------------------------------===//
6708
6709/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006710void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006711 // Analyze block parameters.
6712 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006713
Steve Naroff4eb206b2008-09-03 18:15:37 +00006714 // Add BSI to CurBlock.
6715 BSI->PrevBlockInfo = CurBlock;
6716 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006717
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006718 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006719 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006720 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006721 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006722 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6723 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006724
Steve Naroff090276f2008-10-10 01:28:17 +00006725 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006726 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006727 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006728}
6729
Mike Stump98eb8a72009-02-04 22:31:32 +00006730void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006731 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006732
6733 if (ParamInfo.getNumTypeObjects() == 0
6734 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006735 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006736 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6737
Mike Stump4eeab842009-04-28 01:10:27 +00006738 if (T->isArrayType()) {
6739 Diag(ParamInfo.getSourceRange().getBegin(),
6740 diag::err_block_returns_array);
6741 return;
6742 }
6743
Mike Stump98eb8a72009-02-04 22:31:32 +00006744 // The parameter list is optional, if there was none, assume ().
6745 if (!T->isFunctionType())
6746 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6747
6748 CurBlock->hasPrototype = true;
6749 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006750 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006751 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006752 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006753 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006754 // FIXME: remove the attribute.
6755 }
John McCall183700f2009-09-21 23:43:11 +00006756 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006757
Chris Lattner9097af12009-04-11 19:27:54 +00006758 // Do not allow returning a objc interface by-value.
6759 if (RetTy->isObjCInterfaceType()) {
6760 Diag(ParamInfo.getSourceRange().getBegin(),
6761 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6762 return;
6763 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006764 return;
6765 }
6766
Steve Naroff4eb206b2008-09-03 18:15:37 +00006767 // Analyze arguments to block.
6768 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6769 "Not a function declarator!");
6770 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006771
Steve Naroff090276f2008-10-10 01:28:17 +00006772 CurBlock->hasPrototype = FTI.hasPrototype;
6773 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006774
Steve Naroff4eb206b2008-09-03 18:15:37 +00006775 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6776 // no arguments, not a function that takes a single void argument.
6777 if (FTI.hasPrototype &&
6778 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006779 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6780 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006781 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006782 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006783 } else if (FTI.hasPrototype) {
6784 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006785 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006786 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006787 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006788 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006789 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006790 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006791 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006792 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00006793 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6794 (*AI)->setOwningFunction(CurBlock->TheDecl);
6795
Steve Naroff090276f2008-10-10 01:28:17 +00006796 // If this has an identifier, add it to the scope stack.
6797 if ((*AI)->getIdentifier())
6798 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall7a9813c2010-01-22 00:28:27 +00006799 }
Chris Lattner9097af12009-04-11 19:27:54 +00006800
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006801 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006802 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006803 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006804 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006805 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006806 // FIXME: remove the attribute.
6807 }
Mike Stump1eb44332009-09-09 15:08:12 +00006808
Chris Lattner9097af12009-04-11 19:27:54 +00006809 // Analyze the return type.
6810 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006811 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006812
Chris Lattner9097af12009-04-11 19:27:54 +00006813 // Do not allow returning a objc interface by-value.
6814 if (RetTy->isObjCInterfaceType()) {
6815 Diag(ParamInfo.getSourceRange().getBegin(),
6816 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6817 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006818 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006819}
6820
6821/// ActOnBlockError - If there is an error parsing a block, this callback
6822/// is invoked to pop the information about the block from the action impl.
6823void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6824 // Ensure that CurBlock is deleted.
6825 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006826
Chris Lattner17a78302009-04-19 05:28:12 +00006827 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6828
Steve Naroff4eb206b2008-09-03 18:15:37 +00006829 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006830 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006831 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006832 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006833}
6834
6835/// ActOnBlockStmtExpr - This is called when the body of a block statement
6836/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006837Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6838 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006839 // If blocks are disabled, emit an error.
6840 if (!LangOpts.Blocks)
6841 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006842
Steve Naroff4eb206b2008-09-03 18:15:37 +00006843 // Ensure that CurBlock is deleted.
6844 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006845
Steve Naroff090276f2008-10-10 01:28:17 +00006846 PopDeclContext();
6847
Steve Naroff4eb206b2008-09-03 18:15:37 +00006848 // Pop off CurBlock, handle nested blocks.
6849 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006850
Steve Naroff4eb206b2008-09-03 18:15:37 +00006851 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006852 if (!BSI->ReturnType.isNull())
6853 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006854
Steve Naroff4eb206b2008-09-03 18:15:37 +00006855 llvm::SmallVector<QualType, 8> ArgTypes;
6856 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6857 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006858
Mike Stump56925862009-07-28 22:04:01 +00006859 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006860 QualType BlockTy;
6861 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006862 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6863 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006864 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006865 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006866 BSI->isVariadic, 0, false, false, 0, 0,
6867 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006868
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006869 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006870 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006871 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006872
Chris Lattner17a78302009-04-19 05:28:12 +00006873 // If needed, diagnose invalid gotos and switches in the block.
6874 if (CurFunctionNeedsScopeChecking)
6875 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6876 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006877
Anders Carlssone9146f22009-05-01 19:49:17 +00006878 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpa3899eb2010-01-19 23:08:01 +00006879
6880 bool Good = true;
6881 // Check goto/label use.
6882 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
6883 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
6884 LabelStmt *L = I->second;
6885
6886 // Verify that we have no forward references left. If so, there was a goto
6887 // or address of a label taken, but no definition of it.
6888 if (L->getSubStmt() != 0)
6889 continue;
6890
6891 // Emit error.
6892 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
6893 Good = false;
6894 }
6895 BSI->LabelMap.clear();
6896 if (!Good)
6897 return ExprError();
6898
Mike Stumpfa6ef182010-01-13 02:59:54 +00006899 AnalysisContext AC(BSI->TheDecl);
6900 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6901 CheckUnreachable(AC);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006902 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6903 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006904}
6905
Sebastian Redlf53597f2009-03-15 17:47:39 +00006906Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6907 ExprArg expr, TypeTy *type,
6908 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006909 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006910 Expr *E = static_cast<Expr*>(expr.get());
6911 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006912
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006913 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006914
6915 // Get the va_list type
6916 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006917 if (VaListType->isArrayType()) {
6918 // Deal with implicit array decay; for example, on x86-64,
6919 // va_list is an array, but it's supposed to decay to
6920 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006921 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006922 // Make sure the input expression also decays appropriately.
6923 UsualUnaryConversions(E);
6924 } else {
6925 // Otherwise, the va_list argument must be an l-value because
6926 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006927 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006928 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006929 return ExprError();
6930 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006931
Douglas Gregordd027302009-05-19 23:10:31 +00006932 if (!E->isTypeDependent() &&
6933 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006934 return ExprError(Diag(E->getLocStart(),
6935 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006936 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006937 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006938
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006939 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006940 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006941
Sebastian Redlf53597f2009-03-15 17:47:39 +00006942 expr.release();
6943 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6944 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006945}
6946
Sebastian Redlf53597f2009-03-15 17:47:39 +00006947Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006948 // The type of __null will be int or long, depending on the size of
6949 // pointers on the target.
6950 QualType Ty;
6951 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6952 Ty = Context.IntTy;
6953 else
6954 Ty = Context.LongTy;
6955
Sebastian Redlf53597f2009-03-15 17:47:39 +00006956 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006957}
6958
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006959static void
6960MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6961 QualType DstType,
6962 Expr *SrcExpr,
6963 CodeModificationHint &Hint) {
6964 if (!SemaRef.getLangOptions().ObjC1)
6965 return;
6966
6967 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6968 if (!PT)
6969 return;
6970
6971 // Check if the destination is of type 'id'.
6972 if (!PT->isObjCIdType()) {
6973 // Check if the destination is the 'NSString' interface.
6974 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6975 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6976 return;
6977 }
6978
6979 // Strip off any parens and casts.
6980 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6981 if (!SL || SL->isWide())
6982 return;
6983
6984 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6985}
6986
Chris Lattner5cf216b2008-01-04 18:04:52 +00006987bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6988 SourceLocation Loc,
6989 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00006990 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00006991 // Decode the result (notice that AST's are still created for extensions).
6992 bool isInvalid = false;
6993 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006994 CodeModificationHint Hint;
6995
Chris Lattner5cf216b2008-01-04 18:04:52 +00006996 switch (ConvTy) {
6997 default: assert(0 && "Unknown conversion type");
6998 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006999 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007000 DiagKind = diag::ext_typecheck_convert_pointer_int;
7001 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007002 case IntToPointer:
7003 DiagKind = diag::ext_typecheck_convert_int_pointer;
7004 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007005 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007006 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007007 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7008 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007009 case IncompatiblePointerSign:
7010 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7011 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007012 case FunctionVoidPointer:
7013 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7014 break;
7015 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007016 // If the qualifiers lost were because we were applying the
7017 // (deprecated) C++ conversion from a string literal to a char*
7018 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7019 // Ideally, this check would be performed in
7020 // CheckPointerTypesForAssignment. However, that would require a
7021 // bit of refactoring (so that the second argument is an
7022 // expression, rather than a type), which should be done as part
7023 // of a larger effort to fix CheckPointerTypesForAssignment for
7024 // C++ semantics.
7025 if (getLangOptions().CPlusPlus &&
7026 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7027 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007028 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7029 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007030 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007031 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007032 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007033 case IntToBlockPointer:
7034 DiagKind = diag::err_int_to_block_pointer;
7035 break;
7036 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007037 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007038 break;
Steve Naroff39579072008-10-14 22:18:38 +00007039 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007040 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007041 // it can give a more specific diagnostic.
7042 DiagKind = diag::warn_incompatible_qualified_id;
7043 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007044 case IncompatibleVectors:
7045 DiagKind = diag::warn_incompatible_vectors;
7046 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007047 case Incompatible:
7048 DiagKind = diag::err_typecheck_convert_incompatible;
7049 isInvalid = true;
7050 break;
7051 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007052
Douglas Gregor68647482009-12-16 03:45:30 +00007053 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007054 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007055 return isInvalid;
7056}
Anders Carlssone21555e2008-11-30 19:50:32 +00007057
Chris Lattner3bf68932009-04-25 21:59:05 +00007058bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007059 llvm::APSInt ICEResult;
7060 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7061 if (Result)
7062 *Result = ICEResult;
7063 return false;
7064 }
7065
Anders Carlssone21555e2008-11-30 19:50:32 +00007066 Expr::EvalResult EvalResult;
7067
Mike Stumpeed9cac2009-02-19 03:04:26 +00007068 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007069 EvalResult.HasSideEffects) {
7070 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7071
7072 if (EvalResult.Diag) {
7073 // We only show the note if it's not the usual "invalid subexpression"
7074 // or if it's actually in a subexpression.
7075 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7076 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7077 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7078 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007079
Anders Carlssone21555e2008-11-30 19:50:32 +00007080 return true;
7081 }
7082
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007083 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7084 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007085
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007086 if (EvalResult.Diag &&
7087 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7088 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007089
Anders Carlssone21555e2008-11-30 19:50:32 +00007090 if (Result)
7091 *Result = EvalResult.Val.getInt();
7092 return false;
7093}
Douglas Gregore0762c92009-06-19 23:52:42 +00007094
Douglas Gregor2afce722009-11-26 00:44:06 +00007095void
Mike Stump1eb44332009-09-09 15:08:12 +00007096Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007097 ExprEvalContexts.push_back(
7098 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007099}
7100
Mike Stump1eb44332009-09-09 15:08:12 +00007101void
Douglas Gregor2afce722009-11-26 00:44:06 +00007102Sema::PopExpressionEvaluationContext() {
7103 // Pop the current expression evaluation context off the stack.
7104 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7105 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007106
Douglas Gregor06d33692009-12-12 07:57:52 +00007107 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7108 if (Rec.PotentiallyReferenced) {
7109 // Mark any remaining declarations in the current position of the stack
7110 // as "referenced". If they were not meant to be referenced, semantic
7111 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7112 for (PotentiallyReferencedDecls::iterator
7113 I = Rec.PotentiallyReferenced->begin(),
7114 IEnd = Rec.PotentiallyReferenced->end();
7115 I != IEnd; ++I)
7116 MarkDeclarationReferenced(I->first, I->second);
7117 }
7118
7119 if (Rec.PotentiallyDiagnosed) {
7120 // Emit any pending diagnostics.
7121 for (PotentiallyEmittedDiagnostics::iterator
7122 I = Rec.PotentiallyDiagnosed->begin(),
7123 IEnd = Rec.PotentiallyDiagnosed->end();
7124 I != IEnd; ++I)
7125 Diag(I->first, I->second);
7126 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007127 }
7128
7129 // When are coming out of an unevaluated context, clear out any
7130 // temporaries that we may have created as part of the evaluation of
7131 // the expression in that context: they aren't relevant because they
7132 // will never be constructed.
7133 if (Rec.Context == Unevaluated &&
7134 ExprTemporaries.size() > Rec.NumTemporaries)
7135 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7136 ExprTemporaries.end());
7137
7138 // Destroy the popped expression evaluation record.
7139 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007140}
Douglas Gregore0762c92009-06-19 23:52:42 +00007141
7142/// \brief Note that the given declaration was referenced in the source code.
7143///
7144/// This routine should be invoke whenever a given declaration is referenced
7145/// in the source code, and where that reference occurred. If this declaration
7146/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7147/// C99 6.9p3), then the declaration will be marked as used.
7148///
7149/// \param Loc the location where the declaration was referenced.
7150///
7151/// \param D the declaration that has been referenced by the source code.
7152void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7153 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007154
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007155 if (D->isUsed())
7156 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007157
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007158 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7159 // template or not. The reason for this is that unevaluated expressions
7160 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7161 // -Wunused-parameters)
7162 if (isa<ParmVarDecl>(D) ||
7163 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007164 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007165
Douglas Gregore0762c92009-06-19 23:52:42 +00007166 // Do not mark anything as "used" within a dependent context; wait for
7167 // an instantiation.
7168 if (CurContext->isDependentContext())
7169 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007170
Douglas Gregor2afce722009-11-26 00:44:06 +00007171 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007172 case Unevaluated:
7173 // We are in an expression that is not potentially evaluated; do nothing.
7174 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007175
Douglas Gregorac7610d2009-06-22 20:57:11 +00007176 case PotentiallyEvaluated:
7177 // We are in a potentially-evaluated expression, so this declaration is
7178 // "used"; handle this below.
7179 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007180
Douglas Gregorac7610d2009-06-22 20:57:11 +00007181 case PotentiallyPotentiallyEvaluated:
7182 // We are in an expression that may be potentially evaluated; queue this
7183 // declaration reference until we know whether the expression is
7184 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007185 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007186 return;
7187 }
Mike Stump1eb44332009-09-09 15:08:12 +00007188
Douglas Gregore0762c92009-06-19 23:52:42 +00007189 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007190 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007191 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007192 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7193 if (!Constructor->isUsed())
7194 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007195 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007196 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007197 if (!Constructor->isUsed())
7198 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7199 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007200
7201 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007202 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7203 if (Destructor->isImplicit() && !Destructor->isUsed())
7204 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007205
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007206 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7207 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7208 MethodDecl->getOverloadedOperator() == OO_Equal) {
7209 if (!MethodDecl->isUsed())
7210 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7211 }
7212 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007213 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007214 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007215 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007216 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007217 bool AlreadyInstantiated = false;
7218 if (FunctionTemplateSpecializationInfo *SpecInfo
7219 = Function->getTemplateSpecializationInfo()) {
7220 if (SpecInfo->getPointOfInstantiation().isInvalid())
7221 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007222 else if (SpecInfo->getTemplateSpecializationKind()
7223 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007224 AlreadyInstantiated = true;
7225 } else if (MemberSpecializationInfo *MSInfo
7226 = Function->getMemberSpecializationInfo()) {
7227 if (MSInfo->getPointOfInstantiation().isInvalid())
7228 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007229 else if (MSInfo->getTemplateSpecializationKind()
7230 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007231 AlreadyInstantiated = true;
7232 }
7233
Douglas Gregor60406be2010-01-16 22:29:39 +00007234 if (!AlreadyInstantiated) {
7235 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7236 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7237 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7238 Loc));
7239 else
7240 PendingImplicitInstantiations.push_back(std::make_pair(Function,
7241 Loc));
7242 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007243 }
7244
Douglas Gregore0762c92009-06-19 23:52:42 +00007245 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007246 Function->setUsed(true);
7247 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007248 }
Mike Stump1eb44332009-09-09 15:08:12 +00007249
Douglas Gregore0762c92009-06-19 23:52:42 +00007250 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007251 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007252 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007253 Var->getInstantiatedFromStaticDataMember()) {
7254 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7255 assert(MSInfo && "Missing member specialization information?");
7256 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7257 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7258 MSInfo->setPointOfInstantiation(Loc);
7259 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7260 }
7261 }
Mike Stump1eb44332009-09-09 15:08:12 +00007262
Douglas Gregore0762c92009-06-19 23:52:42 +00007263 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007264
Douglas Gregore0762c92009-06-19 23:52:42 +00007265 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007266 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007267 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007268}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007269
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007270/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7271/// of the program being compiled.
7272///
7273/// This routine emits the given diagnostic when the code currently being
7274/// type-checked is "potentially evaluated", meaning that there is a
7275/// possibility that the code will actually be executable. Code in sizeof()
7276/// expressions, code used only during overload resolution, etc., are not
7277/// potentially evaluated. This routine will suppress such diagnostics or,
7278/// in the absolutely nutty case of potentially potentially evaluated
7279/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7280/// later.
7281///
7282/// This routine should be used for all diagnostics that describe the run-time
7283/// behavior of a program, such as passing a non-POD value through an ellipsis.
7284/// Failure to do so will likely result in spurious diagnostics or failures
7285/// during overload resolution or within sizeof/alignof/typeof/typeid.
7286bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7287 const PartialDiagnostic &PD) {
7288 switch (ExprEvalContexts.back().Context ) {
7289 case Unevaluated:
7290 // The argument will never be evaluated, so don't complain.
7291 break;
7292
7293 case PotentiallyEvaluated:
7294 Diag(Loc, PD);
7295 return true;
7296
7297 case PotentiallyPotentiallyEvaluated:
7298 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7299 break;
7300 }
7301
7302 return false;
7303}
7304
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007305bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7306 CallExpr *CE, FunctionDecl *FD) {
7307 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7308 return false;
7309
7310 PartialDiagnostic Note =
7311 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7312 << FD->getDeclName() : PDiag();
7313 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7314
7315 if (RequireCompleteType(Loc, ReturnType,
7316 FD ?
7317 PDiag(diag::err_call_function_incomplete_return)
7318 << CE->getSourceRange() << FD->getDeclName() :
7319 PDiag(diag::err_call_incomplete_return)
7320 << CE->getSourceRange(),
7321 std::make_pair(NoteLoc, Note)))
7322 return true;
7323
7324 return false;
7325}
7326
John McCall5a881bb2009-10-12 21:59:07 +00007327// Diagnose the common s/=/==/ typo. Note that adding parentheses
7328// will prevent this condition from triggering, which is what we want.
7329void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7330 SourceLocation Loc;
7331
John McCalla52ef082009-11-11 02:41:58 +00007332 unsigned diagnostic = diag::warn_condition_is_assignment;
7333
John McCall5a881bb2009-10-12 21:59:07 +00007334 if (isa<BinaryOperator>(E)) {
7335 BinaryOperator *Op = cast<BinaryOperator>(E);
7336 if (Op->getOpcode() != BinaryOperator::Assign)
7337 return;
7338
John McCallc8d8ac52009-11-12 00:06:05 +00007339 // Greylist some idioms by putting them into a warning subcategory.
7340 if (ObjCMessageExpr *ME
7341 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7342 Selector Sel = ME->getSelector();
7343
John McCallc8d8ac52009-11-12 00:06:05 +00007344 // self = [<foo> init...]
7345 if (isSelfExpr(Op->getLHS())
7346 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7347 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7348
7349 // <foo> = [<bar> nextObject]
7350 else if (Sel.isUnarySelector() &&
7351 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7352 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7353 }
John McCalla52ef082009-11-11 02:41:58 +00007354
John McCall5a881bb2009-10-12 21:59:07 +00007355 Loc = Op->getOperatorLoc();
7356 } else if (isa<CXXOperatorCallExpr>(E)) {
7357 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7358 if (Op->getOperator() != OO_Equal)
7359 return;
7360
7361 Loc = Op->getOperatorLoc();
7362 } else {
7363 // Not an assignment.
7364 return;
7365 }
7366
John McCall5a881bb2009-10-12 21:59:07 +00007367 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007368 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007369
John McCalla52ef082009-11-11 02:41:58 +00007370 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007371 << E->getSourceRange()
7372 << CodeModificationHint::CreateInsertion(Open, "(")
7373 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00007374 Diag(Loc, diag::note_condition_assign_to_comparison)
7375 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00007376}
7377
7378bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7379 DiagnoseAssignmentAsCondition(E);
7380
7381 if (!E->isTypeDependent()) {
7382 DefaultFunctionArrayConversion(E);
7383
7384 QualType T = E->getType();
7385
7386 if (getLangOptions().CPlusPlus) {
7387 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7388 return true;
7389 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7390 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7391 << T << E->getSourceRange();
7392 return true;
7393 }
7394 }
7395
7396 return false;
7397}