blob: 31ec7783903295b0ef4f3a7269ee4c3cc3a10fa3 [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"
Mike Stumpfa6ef182010-01-13 02:59:54 +000017#include "clang/Analysis/PathSensitive/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
3085 if (Getter || Setter) {
3086 QualType PType;
3087
3088 if (Getter)
3089 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00003090 else
3091 // Get the expression type from Setter's incoming parameter.
3092 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00003093 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00003094 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00003095 Setter, MemberLoc, BaseExpr));
3096 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003097
3098 // Attempt to correct for typos in property names.
3099 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3100 LookupOrdinaryName);
3101 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3102 Res.getAsSingle<ObjCPropertyDecl>()) {
3103 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3104 << MemberName << BaseType << Res.getLookupName()
3105 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3106 Res.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003107 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3108 Diag(Property->getLocation(), diag::note_previous_decl)
3109 << Property->getDeclName();
3110
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003111 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCallc2233c52010-01-15 08:34:02 +00003112 ObjCImpDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003113 }
3114
Sebastian Redl0eb23302009-01-19 00:08:26 +00003115 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003116 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00003117 }
Mike Stump1eb44332009-09-09 15:08:12 +00003118
Steve Narofff242b1b2009-07-24 17:54:45 +00003119 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003120 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003121 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003122 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003123 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003124 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003125
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003126 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003127 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003128 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003129 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3130 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003131 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003132 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003133 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003134 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003135
Douglas Gregor214f31a2009-03-27 06:00:30 +00003136 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3137 << BaseType << BaseExpr->getSourceRange();
3138
Douglas Gregor214f31a2009-03-27 06:00:30 +00003139 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003140}
3141
John McCall129e2df2009-11-30 22:42:35 +00003142static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3143 SourceLocation NameLoc,
3144 Sema::ExprArg MemExpr) {
3145 Expr *E = (Expr *) MemExpr.get();
3146 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3147 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00003148 << isa<CXXPseudoDestructorExpr>(E)
3149 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3150
John McCall129e2df2009-11-30 22:42:35 +00003151 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3152 move(MemExpr),
3153 /*LPLoc*/ ExpectedLParenLoc,
3154 Sema::MultiExprArg(SemaRef, 0, 0),
3155 /*CommaLocs*/ 0,
3156 /*RPLoc*/ ExpectedLParenLoc);
3157}
3158
3159/// The main callback when the parser finds something like
3160/// expression . [nested-name-specifier] identifier
3161/// expression -> [nested-name-specifier] identifier
3162/// where 'identifier' encompasses a fairly broad spectrum of
3163/// possibilities, including destructor and operator references.
3164///
3165/// \param OpKind either tok::arrow or tok::period
3166/// \param HasTrailingLParen whether the next token is '(', which
3167/// is used to diagnose mis-uses of special members that can
3168/// only be called
3169/// \param ObjCImpDecl the current ObjC @implementation decl;
3170/// this is an ugly hack around the fact that ObjC @implementations
3171/// aren't properly put in the context chain
3172Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3173 SourceLocation OpLoc,
3174 tok::TokenKind OpKind,
3175 const CXXScopeSpec &SS,
3176 UnqualifiedId &Id,
3177 DeclPtrTy ObjCImpDecl,
3178 bool HasTrailingLParen) {
3179 if (SS.isSet() && SS.isInvalid())
3180 return ExprError();
3181
3182 TemplateArgumentListInfo TemplateArgsBuffer;
3183
3184 // Decompose the name into its component parts.
3185 DeclarationName Name;
3186 SourceLocation NameLoc;
3187 const TemplateArgumentListInfo *TemplateArgs;
3188 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3189 Name, NameLoc, TemplateArgs);
3190
3191 bool IsArrow = (OpKind == tok::arrow);
3192
3193 NamedDecl *FirstQualifierInScope
3194 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3195 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3196
3197 // This is a postfix expression, so get rid of ParenListExprs.
3198 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3199
3200 Expr *Base = BaseArg.takeAs<Expr>();
3201 OwningExprResult Result(*this);
Douglas Gregor48026d22010-01-11 18:40:55 +00003202 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCallaa81e162009-12-01 22:10:20 +00003203 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003204 IsArrow, OpLoc,
3205 SS, FirstQualifierInScope,
3206 Name, NameLoc,
3207 TemplateArgs);
3208 } else {
3209 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3210 if (TemplateArgs) {
3211 // Re-use the lookup done for the template name.
3212 DecomposeTemplateName(R, Id);
3213 } else {
3214 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00003215 SS, ObjCImpDecl);
John McCall129e2df2009-11-30 22:42:35 +00003216
3217 if (Result.isInvalid()) {
3218 Owned(Base);
3219 return ExprError();
3220 }
3221
3222 if (Result.get()) {
3223 // The only way a reference to a destructor can be used is to
3224 // immediately call it, which falls into this case. If the
3225 // next token is not a '(', produce a diagnostic and build the
3226 // call now.
3227 if (!HasTrailingLParen &&
3228 Id.getKind() == UnqualifiedId::IK_DestructorName)
3229 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3230
3231 return move(Result);
3232 }
3233 }
3234
John McCallaa81e162009-12-01 22:10:20 +00003235 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003236 OpLoc, IsArrow, SS, FirstQualifierInScope,
3237 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003238 }
3239
3240 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003241}
3242
Anders Carlsson56c5e332009-08-25 03:49:14 +00003243Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3244 FunctionDecl *FD,
3245 ParmVarDecl *Param) {
3246 if (Param->hasUnparsedDefaultArg()) {
3247 Diag (CallLoc,
3248 diag::err_use_of_default_argument_to_function_declared_later) <<
3249 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003250 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003251 diag::note_default_argument_declared_here);
3252 } else {
3253 if (Param->hasUninstantiatedDefaultArg()) {
3254 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3255
3256 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003257 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003258
Mike Stump1eb44332009-09-09 15:08:12 +00003259 InstantiatingTemplate Inst(*this, CallLoc, Param,
3260 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003261 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003262
John McCallce3ff2b2009-08-25 22:02:44 +00003263 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003264 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003265 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Douglas Gregor65222e82009-12-23 18:19:08 +00003267 // Check the expression as an initializer for the parameter.
3268 InitializedEntity Entity
3269 = InitializedEntity::InitializeParameter(Param);
3270 InitializationKind Kind
3271 = InitializationKind::CreateCopy(Param->getLocation(),
3272 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3273 Expr *ResultE = Result.takeAs<Expr>();
3274
3275 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3276 Result = InitSeq.Perform(*this, Entity, Kind,
3277 MultiExprArg(*this, (void**)&ResultE, 1));
3278 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003279 return ExprError();
Douglas Gregor65222e82009-12-23 18:19:08 +00003280
3281 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003282 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003283 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003284 }
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Anders Carlsson56c5e332009-08-25 03:49:14 +00003286 // If the default expression creates temporaries, we need to
3287 // push them to the current stack of expression temporaries so they'll
3288 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003289 // FIXME: We should really be rebuilding the default argument with new
3290 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003291 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3292 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003293 }
3294
3295 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003296 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003297}
3298
Douglas Gregor88a35142008-12-22 05:46:06 +00003299/// ConvertArgumentsForCall - Converts the arguments specified in
3300/// Args/NumArgs to the parameter types of the function FDecl with
3301/// function prototype Proto. Call is the call expression itself, and
3302/// Fn is the function expression. For a C++ member function, this
3303/// routine does not attempt to convert the object argument. Returns
3304/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003305bool
3306Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003307 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003308 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003309 Expr **Args, unsigned NumArgs,
3310 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003311 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003312 // assignment, to the types of the corresponding parameter, ...
3313 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003314 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003315
Douglas Gregor88a35142008-12-22 05:46:06 +00003316 // If too few arguments are available (and we don't have default
3317 // arguments for the remaining parameters), don't make the call.
3318 if (NumArgs < NumArgsInProto) {
3319 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3320 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3321 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003322 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003323 }
3324
3325 // If too many are passed and not variadic, error on the extras and drop
3326 // them.
3327 if (NumArgs > NumArgsInProto) {
3328 if (!Proto->isVariadic()) {
3329 Diag(Args[NumArgsInProto]->getLocStart(),
3330 diag::err_typecheck_call_too_many_args)
3331 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3332 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3333 Args[NumArgs-1]->getLocEnd());
3334 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003335 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003336 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003337 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003338 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003339 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003340 VariadicCallType CallType =
3341 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3342 if (Fn->getType()->isBlockPointerType())
3343 CallType = VariadicBlock; // Block
3344 else if (isa<MemberExpr>(Fn))
3345 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003346 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003347 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003348 if (Invalid)
3349 return true;
3350 unsigned TotalNumArgs = AllArgs.size();
3351 for (unsigned i = 0; i < TotalNumArgs; ++i)
3352 Call->setArg(i, AllArgs[i]);
3353
3354 return false;
3355}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003356
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003357bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3358 FunctionDecl *FDecl,
3359 const FunctionProtoType *Proto,
3360 unsigned FirstProtoArg,
3361 Expr **Args, unsigned NumArgs,
3362 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003363 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003364 unsigned NumArgsInProto = Proto->getNumArgs();
3365 unsigned NumArgsToCheck = NumArgs;
3366 bool Invalid = false;
3367 if (NumArgs != NumArgsInProto)
3368 // Use default arguments for missing arguments
3369 NumArgsToCheck = NumArgsInProto;
3370 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003371 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003372 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003373 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003374
Douglas Gregor88a35142008-12-22 05:46:06 +00003375 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003376 if (ArgIx < NumArgs) {
3377 Arg = Args[ArgIx++];
3378
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003379 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3380 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003381 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003382 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003383 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003384
Douglas Gregora188ff22009-12-22 16:09:06 +00003385 // Pass the argument
3386 ParmVarDecl *Param = 0;
3387 if (FDecl && i < FDecl->getNumParams())
3388 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003389
Douglas Gregora188ff22009-12-22 16:09:06 +00003390
3391 InitializedEntity Entity =
3392 Param? InitializedEntity::InitializeParameter(Param)
3393 : InitializedEntity::InitializeParameter(ProtoArgType);
3394 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3395 SourceLocation(),
3396 Owned(Arg));
3397 if (ArgE.isInvalid())
3398 return true;
3399
3400 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003401 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003402 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003403
Mike Stump1eb44332009-09-09 15:08:12 +00003404 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003405 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003406 if (ArgExpr.isInvalid())
3407 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003408
Anders Carlsson56c5e332009-08-25 03:49:14 +00003409 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003410 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003411 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003412 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003413
Douglas Gregor88a35142008-12-22 05:46:06 +00003414 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003415 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003416 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003417 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003418 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003419 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003420 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003421 }
3422 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003423 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003424}
3425
Steve Narofff69936d2007-09-16 03:34:24 +00003426/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003427/// This provides the location of the left/right parens and a list of comma
3428/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003429Action::OwningExprResult
3430Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3431 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003432 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003433 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003434
3435 // Since this might be a postfix expression, get rid of ParenListExprs.
3436 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003438 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003439 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003440 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Douglas Gregor88a35142008-12-22 05:46:06 +00003442 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003443 // If this is a pseudo-destructor expression, build the call immediately.
3444 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3445 if (NumArgs > 0) {
3446 // Pseudo-destructor calls should not have any arguments.
3447 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3448 << CodeModificationHint::CreateRemoval(
3449 SourceRange(Args[0]->getLocStart(),
3450 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregora71d8192009-09-04 17:36:40 +00003452 for (unsigned I = 0; I != NumArgs; ++I)
3453 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregora71d8192009-09-04 17:36:40 +00003455 NumArgs = 0;
3456 }
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Douglas Gregora71d8192009-09-04 17:36:40 +00003458 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3459 RParenLoc));
3460 }
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregor17330012009-02-04 15:01:18 +00003462 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003463 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003464 // FIXME: Will need to cache the results of name lookup (including ADL) in
3465 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003466 bool Dependent = false;
3467 if (Fn->isTypeDependent())
3468 Dependent = true;
3469 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3470 Dependent = true;
3471
3472 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003473 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003474 Context.DependentTy, RParenLoc));
3475
3476 // Determine whether this is a call to an object (C++ [over.call.object]).
3477 if (Fn->getType()->isRecordType())
3478 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3479 CommaLocs, RParenLoc));
3480
John McCall129e2df2009-11-30 22:42:35 +00003481 Expr *NakedFn = Fn->IgnoreParens();
3482
3483 // Determine whether this is a call to an unresolved member function.
3484 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3485 // If lookup was unresolved but not dependent (i.e. didn't find
3486 // an unresolved using declaration), it has to be an overloaded
3487 // function set, which means it must contain either multiple
3488 // declarations (all methods or method templates) or a single
3489 // method template.
3490 assert((MemE->getNumDecls() > 1) ||
3491 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003492 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003493
John McCallaa81e162009-12-01 22:10:20 +00003494 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3495 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003496 }
3497
Douglas Gregorfa047642009-02-04 00:32:51 +00003498 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003499 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003500 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003501 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003502 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3503 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003504 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003505
3506 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003507 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003508 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3509 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003510 if (const FunctionProtoType *FPT =
3511 dyn_cast<FunctionProtoType>(BO->getType())) {
3512 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003513
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003514 ExprOwningPtr<CXXMemberCallExpr>
3515 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3516 NumArgs, ResultTy,
3517 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003518
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003519 if (CheckCallReturnType(FPT->getResultType(),
3520 BO->getRHS()->getSourceRange().getBegin(),
3521 TheCall.get(), 0))
3522 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003523
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003524 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3525 RParenLoc))
3526 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003527
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003528 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3529 }
3530 return ExprError(Diag(Fn->getLocStart(),
3531 diag::err_typecheck_call_not_function)
3532 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003533 }
3534 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003535 }
3536
Douglas Gregorfa047642009-02-04 00:32:51 +00003537 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003538 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003539 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003540
Eli Friedmanefa42f72009-12-26 03:35:45 +00003541 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003542 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3543 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3544 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3545 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003546 }
Chris Lattner04421082008-04-08 04:40:51 +00003547
John McCall3b4294e2009-12-16 12:17:52 +00003548 NamedDecl *NDecl = 0;
3549 if (isa<DeclRefExpr>(NakedFn))
3550 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3551
John McCallaa81e162009-12-01 22:10:20 +00003552 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3553}
3554
John McCall3b4294e2009-12-16 12:17:52 +00003555/// BuildResolvedCallExpr - Build a call to a resolved expression,
3556/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003557/// unary-convert to an expression of function-pointer or
3558/// block-pointer type.
3559///
3560/// \param NDecl the declaration being called, if available
3561Sema::OwningExprResult
3562Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3563 SourceLocation LParenLoc,
3564 Expr **Args, unsigned NumArgs,
3565 SourceLocation RParenLoc) {
3566 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3567
Chris Lattner04421082008-04-08 04:40:51 +00003568 // Promote the function operand.
3569 UsualUnaryConversions(Fn);
3570
Chris Lattner925e60d2007-12-28 05:29:59 +00003571 // Make the call expr early, before semantic checks. This guarantees cleanup
3572 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003573 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3574 Args, NumArgs,
3575 Context.BoolTy,
3576 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003577
Steve Naroffdd972f22008-09-05 22:11:13 +00003578 const FunctionType *FuncT;
3579 if (!Fn->getType()->isBlockPointerType()) {
3580 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3581 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003582 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003583 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003584 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3585 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003586 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003587 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003588 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003589 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003590 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003591 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003592 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3593 << Fn->getType() << Fn->getSourceRange());
3594
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003595 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003596 if (CheckCallReturnType(FuncT->getResultType(),
3597 Fn->getSourceRange().getBegin(), TheCall.get(),
3598 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003599 return ExprError();
3600
Chris Lattner925e60d2007-12-28 05:29:59 +00003601 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003602 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003603
Douglas Gregor72564e72009-02-26 23:50:07 +00003604 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003605 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003606 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003607 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003608 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003609 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003610
Douglas Gregor74734d52009-04-02 15:37:10 +00003611 if (FDecl) {
3612 // Check if we have too few/too many template arguments, based
3613 // on our knowledge of the function definition.
3614 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003615 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003616 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003617 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003618 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3619 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3620 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3621 }
3622 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003623 }
3624
Steve Naroffb291ab62007-08-28 23:30:39 +00003625 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003626 for (unsigned i = 0; i != NumArgs; i++) {
3627 Expr *Arg = Args[i];
3628 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003629 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3630 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003631 PDiag(diag::err_call_incomplete_argument)
3632 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003633 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003634 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003635 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003636 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003637
Douglas Gregor88a35142008-12-22 05:46:06 +00003638 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3639 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003640 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3641 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003642
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003643 // Check for sentinels
3644 if (NDecl)
3645 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003646
Chris Lattner59907c42007-08-10 20:18:51 +00003647 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003648 if (FDecl) {
3649 if (CheckFunctionCall(FDecl, TheCall.get()))
3650 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003652 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003653 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3654 } else if (NDecl) {
3655 if (CheckBlockCall(NDecl, TheCall.get()))
3656 return ExprError();
3657 }
Chris Lattner59907c42007-08-10 20:18:51 +00003658
Anders Carlssonec74c592009-08-16 03:06:32 +00003659 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003660}
3661
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003662Action::OwningExprResult
3663Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3664 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003665 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor99a2e602009-12-16 01:38:02 +00003666
Douglas Gregord6542d82009-12-22 15:35:07 +00003667 QualType literalType = GetTypeFromParser(Ty);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003668
Steve Naroffaff1edd2007-07-19 21:32:11 +00003669 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003670 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003671 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003672
Eli Friedman6223c222008-05-20 05:22:08 +00003673 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003674 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003675 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3676 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003677 } else if (!literalType->isDependentType() &&
3678 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003679 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003680 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003681 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003682 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003683
Douglas Gregor99a2e602009-12-16 01:38:02 +00003684 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003685 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003686 InitializationKind Kind
3687 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3688 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003689 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3690 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3691 MultiExprArg(*this, (void**)&literalExpr, 1),
3692 &literalType);
3693 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003694 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003695 InitExpr.release();
3696 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003697
Chris Lattner371f2582008-12-04 23:50:19 +00003698 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003699 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003700 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003701 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003702 }
Eli Friedman08544622009-12-22 02:35:53 +00003703
3704 Result.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003705
3706 // FIXME: Store the TInfo to preserve type information better.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003707 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003708 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003709}
3710
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003711Action::OwningExprResult
3712Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003713 SourceLocation RBraceLoc) {
3714 unsigned NumInit = initlist.size();
3715 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003716
Steve Naroff08d92e42007-09-15 18:49:24 +00003717 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003718 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003719
Mike Stumpeed9cac2009-02-19 03:04:26 +00003720 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003721 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003722 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003723 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003724}
3725
Anders Carlsson82debc72009-10-18 18:12:03 +00003726static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3727 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003728 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003729 return CastExpr::CK_NoOp;
3730
3731 if (SrcTy->hasPointerRepresentation()) {
3732 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003733 return DestTy->isObjCObjectPointerType() ?
3734 CastExpr::CK_AnyPointerToObjCPointerCast :
3735 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003736 if (DestTy->isIntegerType())
3737 return CastExpr::CK_PointerToIntegral;
3738 }
3739
3740 if (SrcTy->isIntegerType()) {
3741 if (DestTy->isIntegerType())
3742 return CastExpr::CK_IntegralCast;
3743 if (DestTy->hasPointerRepresentation())
3744 return CastExpr::CK_IntegralToPointer;
3745 if (DestTy->isRealFloatingType())
3746 return CastExpr::CK_IntegralToFloating;
3747 }
3748
3749 if (SrcTy->isRealFloatingType()) {
3750 if (DestTy->isRealFloatingType())
3751 return CastExpr::CK_FloatingCast;
3752 if (DestTy->isIntegerType())
3753 return CastExpr::CK_FloatingToIntegral;
3754 }
3755
3756 // FIXME: Assert here.
3757 // assert(false && "Unhandled cast combination!");
3758 return CastExpr::CK_Unknown;
3759}
3760
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003761/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003762bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003763 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003764 CXXMethodDecl *& ConversionDecl,
3765 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003766 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003767 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3768 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003769
Eli Friedman199ea952009-08-15 19:02:19 +00003770 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003771
3772 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3773 // type needs to be scalar.
3774 if (castType->isVoidType()) {
3775 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003776 Kind = CastExpr::CK_ToVoid;
3777 return false;
3778 }
3779
3780 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003781 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003782 (castType->isStructureType() || castType->isUnionType())) {
3783 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003784 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003785 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3786 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003787 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003788 return false;
3789 }
3790
3791 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003792 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003793 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003794 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003795 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003796 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003797 if (Context.hasSameUnqualifiedType(Field->getType(),
3798 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003799 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3800 << castExpr->getSourceRange();
3801 break;
3802 }
3803 }
3804 if (Field == FieldEnd)
3805 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3806 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003807 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003808 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003809 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003810
3811 // Reject any other conversions to non-scalar types.
3812 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3813 << castType << castExpr->getSourceRange();
3814 }
3815
3816 if (!castExpr->getType()->isScalarType() &&
3817 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003818 return Diag(castExpr->getLocStart(),
3819 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003820 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003821 }
3822
Anders Carlsson16a89042009-10-16 05:23:41 +00003823 if (castType->isExtVectorType())
3824 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3825
Anders Carlssonc3516322009-10-16 02:48:28 +00003826 if (castType->isVectorType())
3827 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3828 if (castExpr->getType()->isVectorType())
3829 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3830
3831 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003832 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003833
Anders Carlsson16a89042009-10-16 05:23:41 +00003834 if (isa<ObjCSelectorExpr>(castExpr))
3835 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3836
Anders Carlssonc3516322009-10-16 02:48:28 +00003837 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003838 QualType castExprType = castExpr->getType();
3839 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3840 return Diag(castExpr->getLocStart(),
3841 diag::err_cast_pointer_from_non_pointer_int)
3842 << castExprType << castExpr->getSourceRange();
3843 } else if (!castExpr->getType()->isArithmeticType()) {
3844 if (!castType->isIntegralType() && castType->isArithmeticType())
3845 return Diag(castExpr->getLocStart(),
3846 diag::err_cast_pointer_to_non_pointer_int)
3847 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003848 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003849
3850 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003851 return false;
3852}
3853
Anders Carlssonc3516322009-10-16 02:48:28 +00003854bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3855 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003856 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003857
Anders Carlssona64db8f2007-11-27 05:51:55 +00003858 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003859 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003860 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003861 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003862 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003863 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003864 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003865 } else
3866 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003867 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003868 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003869
Anders Carlssonc3516322009-10-16 02:48:28 +00003870 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003871 return false;
3872}
3873
Anders Carlsson16a89042009-10-16 05:23:41 +00003874bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3875 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003876 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003877
3878 QualType SrcTy = CastExpr->getType();
3879
Nate Begeman9b10da62009-06-27 22:05:55 +00003880 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3881 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003882 if (SrcTy->isVectorType()) {
3883 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3884 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3885 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003886 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003887 return false;
3888 }
3889
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003890 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003891 // conversion will take place first from scalar to elt type, and then
3892 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003893 if (SrcTy->isPointerType())
3894 return Diag(R.getBegin(),
3895 diag::err_invalid_conversion_between_vector_and_scalar)
3896 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003897
3898 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3899 ImpCastExprToType(CastExpr, DestElemTy,
3900 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003901
3902 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003903 return false;
3904}
3905
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003906Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003907Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003908 SourceLocation RParenLoc, ExprArg Op) {
3909 assert((Ty != 0) && (Op.get() != 0) &&
3910 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003911
John McCall9d125032010-01-15 18:39:57 +00003912 TypeSourceInfo *castTInfo;
3913 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3914 if (!castTInfo)
3915 castTInfo = Context.getTrivialTypeSourceInfo(castType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Nate Begeman2ef13e52009-08-10 23:49:36 +00003917 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00003918 // FIXME: preserve type source info.
3919 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003920 if (isa<ParenListExpr>(castExpr))
3921 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
John McCallb042fdf2010-01-15 18:56:44 +00003922
3923 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3924}
3925
3926Action::OwningExprResult
3927Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3928 SourceLocation RParenLoc, ExprArg Op) {
3929 Expr *castExpr = static_cast<Expr*>(Op.get());
3930
Anders Carlsson0aebc812009-09-09 21:33:21 +00003931 CXXMethodDecl *Method = 0;
John McCallb042fdf2010-01-15 18:56:44 +00003932 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3933 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003934 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003935 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003936
3937 if (Method) {
John McCallb042fdf2010-01-15 18:56:44 +00003938 // FIXME: preserve type source info here
3939 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
3940 Kind, Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003941
Anders Carlsson0aebc812009-09-09 21:33:21 +00003942 if (CastArg.isInvalid())
3943 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003944
Anders Carlsson0aebc812009-09-09 21:33:21 +00003945 castExpr = CastArg.takeAs<Expr>();
3946 } else {
3947 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003948 }
Mike Stump1eb44332009-09-09 15:08:12 +00003949
John McCallb042fdf2010-01-15 18:56:44 +00003950 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3951 Kind, castExpr, Ty,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003952 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003953}
3954
Nate Begeman2ef13e52009-08-10 23:49:36 +00003955/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3956/// of comma binary operators.
3957Action::OwningExprResult
3958Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3959 Expr *expr = EA.takeAs<Expr>();
3960 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3961 if (!E)
3962 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Nate Begeman2ef13e52009-08-10 23:49:36 +00003964 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Nate Begeman2ef13e52009-08-10 23:49:36 +00003966 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3967 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3968 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Nate Begeman2ef13e52009-08-10 23:49:36 +00003970 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3971}
3972
3973Action::OwningExprResult
3974Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3975 SourceLocation RParenLoc, ExprArg Op,
3976 QualType Ty) {
3977 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003978
3979 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003980 // then handle it as such.
3981 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3982 if (PE->getNumExprs() == 0) {
3983 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3984 return ExprError();
3985 }
3986
3987 llvm::SmallVector<Expr *, 8> initExprs;
3988 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3989 initExprs.push_back(PE->getExpr(i));
3990
3991 // FIXME: This means that pretty-printing the final AST will produce curly
3992 // braces instead of the original commas.
3993 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003994 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003995 initExprs.size(), RParenLoc);
3996 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003997 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003998 Owned(E));
3999 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004000 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004001 // sequence of BinOp comma operators.
4002 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
4003 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
4004 }
4005}
4006
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004007Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004008 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004009 MultiExprArg Val,
4010 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004011 unsigned nexprs = Val.size();
4012 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004013 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4014 Expr *expr;
4015 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4016 expr = new (Context) ParenExpr(L, R, exprs[0]);
4017 else
4018 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004019 return Owned(expr);
4020}
4021
Sebastian Redl28507842009-02-26 14:39:58 +00004022/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4023/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004024/// C99 6.5.15
4025QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4026 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004027 // C++ is sufficiently different to merit its own checker.
4028 if (getLangOptions().CPlusPlus)
4029 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4030
John McCallb13c87f2009-11-05 09:23:39 +00004031 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4032
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004033 UsualUnaryConversions(Cond);
4034 UsualUnaryConversions(LHS);
4035 UsualUnaryConversions(RHS);
4036 QualType CondTy = Cond->getType();
4037 QualType LHSTy = LHS->getType();
4038 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004039
Reid Spencer5f016e22007-07-11 17:01:13 +00004040 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004041 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4042 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4043 << CondTy;
4044 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004045 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004046
Chris Lattner70d67a92008-01-06 22:42:25 +00004047 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004048 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4049 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004050
Chris Lattner70d67a92008-01-06 22:42:25 +00004051 // If both operands have arithmetic type, do the usual arithmetic conversions
4052 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004053 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4054 UsualArithmeticConversions(LHS, RHS);
4055 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004056 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004057
Chris Lattner70d67a92008-01-06 22:42:25 +00004058 // If both operands are the same structure or union type, the result is that
4059 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004060 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4061 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004062 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004063 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004064 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004065 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004066 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004067 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004068
Chris Lattner70d67a92008-01-06 22:42:25 +00004069 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004070 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004071 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4072 if (!LHSTy->isVoidType())
4073 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4074 << RHS->getSourceRange();
4075 if (!RHSTy->isVoidType())
4076 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4077 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004078 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4079 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004080 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004081 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004082 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4083 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004084 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004085 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004086 // promote the null to a pointer.
4087 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004088 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004089 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004090 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004091 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004092 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004093 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004094 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004095
4096 // All objective-c pointer type analysis is done here.
4097 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4098 QuestionLoc);
4099 if (!compositeType.isNull())
4100 return compositeType;
4101
4102
Steve Naroff7154a772009-07-01 14:36:47 +00004103 // Handle block pointer types.
4104 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4105 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4106 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4107 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004108 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4109 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004110 return destType;
4111 }
4112 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004113 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004114 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004115 }
Steve Naroff7154a772009-07-01 14:36:47 +00004116 // We have 2 block pointer types.
4117 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4118 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004119 return LHSTy;
4120 }
Steve Naroff7154a772009-07-01 14:36:47 +00004121 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004122 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4123 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004124
Steve Naroff7154a772009-07-01 14:36:47 +00004125 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4126 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004127 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004128 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004129 // In this situation, we assume void* type. No especially good
4130 // reason, but this is what gcc does, and we do have to pick
4131 // to get a consistent AST.
4132 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004133 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4134 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004135 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004136 }
Steve Naroff7154a772009-07-01 14:36:47 +00004137 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004138 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4139 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004140 return LHSTy;
4141 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004142
Steve Naroff7154a772009-07-01 14:36:47 +00004143 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4144 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4145 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004146 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4147 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004148
4149 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4150 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4151 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004152 QualType destPointee
4153 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004154 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004155 // Add qualifiers if necessary.
4156 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4157 // Promote to void*.
4158 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004159 return destType;
4160 }
4161 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004162 QualType destPointee
4163 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004164 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004165 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004166 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004167 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004168 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004169 return destType;
4170 }
4171
4172 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4173 // Two identical pointer types are always compatible.
4174 return LHSTy;
4175 }
4176 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4177 rhptee.getUnqualifiedType())) {
4178 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4179 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4180 // In this situation, we assume void* type. No especially good
4181 // reason, but this is what gcc does, and we do have to pick
4182 // to get a consistent AST.
4183 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004184 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4185 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004186 return incompatTy;
4187 }
4188 // The pointer types are compatible.
4189 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4190 // differently qualified versions of compatible types, the result type is
4191 // a pointer to an appropriately qualified version of the *composite*
4192 // type.
4193 // FIXME: Need to calculate the composite type.
4194 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004195 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4196 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004197 return LHSTy;
4198 }
Mike Stump1eb44332009-09-09 15:08:12 +00004199
Steve Naroff7154a772009-07-01 14:36:47 +00004200 // GCC compatibility: soften pointer/integer mismatch.
4201 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4202 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4203 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004204 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004205 return RHSTy;
4206 }
4207 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4208 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4209 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004210 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004211 return LHSTy;
4212 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004213
Chris Lattner70d67a92008-01-06 22:42:25 +00004214 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004215 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4216 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004217 return QualType();
4218}
4219
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004220/// FindCompositeObjCPointerType - Helper method to find composite type of
4221/// two objective-c pointer types of the two input expressions.
4222QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4223 SourceLocation QuestionLoc) {
4224 QualType LHSTy = LHS->getType();
4225 QualType RHSTy = RHS->getType();
4226
4227 // Handle things like Class and struct objc_class*. Here we case the result
4228 // to the pseudo-builtin, because that will be implicitly cast back to the
4229 // redefinition type if an attempt is made to access its fields.
4230 if (LHSTy->isObjCClassType() &&
4231 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4232 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4233 return LHSTy;
4234 }
4235 if (RHSTy->isObjCClassType() &&
4236 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4237 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4238 return RHSTy;
4239 }
4240 // And the same for struct objc_object* / id
4241 if (LHSTy->isObjCIdType() &&
4242 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4243 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4244 return LHSTy;
4245 }
4246 if (RHSTy->isObjCIdType() &&
4247 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4248 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4249 return RHSTy;
4250 }
4251 // And the same for struct objc_selector* / SEL
4252 if (Context.isObjCSelType(LHSTy) &&
4253 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4254 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4255 return LHSTy;
4256 }
4257 if (Context.isObjCSelType(RHSTy) &&
4258 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4259 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4260 return RHSTy;
4261 }
4262 // Check constraints for Objective-C object pointers types.
4263 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4264
4265 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4266 // Two identical object pointer types are always compatible.
4267 return LHSTy;
4268 }
4269 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4270 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4271 QualType compositeType = LHSTy;
4272
4273 // If both operands are interfaces and either operand can be
4274 // assigned to the other, use that type as the composite
4275 // type. This allows
4276 // xxx ? (A*) a : (B*) b
4277 // where B is a subclass of A.
4278 //
4279 // Additionally, as for assignment, if either type is 'id'
4280 // allow silent coercion. Finally, if the types are
4281 // incompatible then make sure to use 'id' as the composite
4282 // type so the result is acceptable for sending messages to.
4283
4284 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4285 // It could return the composite type.
4286 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4287 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4288 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4289 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4290 } else if ((LHSTy->isObjCQualifiedIdType() ||
4291 RHSTy->isObjCQualifiedIdType()) &&
4292 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4293 // Need to handle "id<xx>" explicitly.
4294 // GCC allows qualified id and any Objective-C type to devolve to
4295 // id. Currently localizing to here until clear this should be
4296 // part of ObjCQualifiedIdTypesAreCompatible.
4297 compositeType = Context.getObjCIdType();
4298 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4299 compositeType = Context.getObjCIdType();
4300 } else if (!(compositeType =
4301 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4302 ;
4303 else {
4304 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4305 << LHSTy << RHSTy
4306 << LHS->getSourceRange() << RHS->getSourceRange();
4307 QualType incompatTy = Context.getObjCIdType();
4308 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4309 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4310 return incompatTy;
4311 }
4312 // The object pointer types are compatible.
4313 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4314 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4315 return compositeType;
4316 }
4317 // Check Objective-C object pointer types and 'void *'
4318 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4319 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4320 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4321 QualType destPointee
4322 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4323 QualType destType = Context.getPointerType(destPointee);
4324 // Add qualifiers if necessary.
4325 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4326 // Promote to void*.
4327 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4328 return destType;
4329 }
4330 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4331 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4332 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4333 QualType destPointee
4334 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4335 QualType destType = Context.getPointerType(destPointee);
4336 // Add qualifiers if necessary.
4337 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4338 // Promote to void*.
4339 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4340 return destType;
4341 }
4342 return QualType();
4343}
4344
Steve Narofff69936d2007-09-16 03:34:24 +00004345/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004346/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004347Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4348 SourceLocation ColonLoc,
4349 ExprArg Cond, ExprArg LHS,
4350 ExprArg RHS) {
4351 Expr *CondExpr = (Expr *) Cond.get();
4352 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004353
4354 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4355 // was the condition.
4356 bool isLHSNull = LHSExpr == 0;
4357 if (isLHSNull)
4358 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004359
4360 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004361 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004362 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004363 return ExprError();
4364
4365 Cond.release();
4366 LHS.release();
4367 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004368 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004369 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004370 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004371}
4372
Reid Spencer5f016e22007-07-11 17:01:13 +00004373// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004374// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004375// routine is it effectively iqnores the qualifiers on the top level pointee.
4376// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4377// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004378Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004379Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4380 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004381
David Chisnall0f436562009-08-17 16:35:33 +00004382 if ((lhsType->isObjCClassType() &&
4383 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4384 (rhsType->isObjCClassType() &&
4385 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4386 return Compatible;
4387 }
4388
Reid Spencer5f016e22007-07-11 17:01:13 +00004389 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004390 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4391 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004392
Reid Spencer5f016e22007-07-11 17:01:13 +00004393 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004394 lhptee = Context.getCanonicalType(lhptee);
4395 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004396
Chris Lattner5cf216b2008-01-04 18:04:52 +00004397 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004398
4399 // C99 6.5.16.1p1: This following citation is common to constraints
4400 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4401 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004402 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004403 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004404 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004405
Mike Stumpeed9cac2009-02-19 03:04:26 +00004406 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4407 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004408 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004409 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004410 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004411 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004412
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004413 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004414 assert(rhptee->isFunctionType());
4415 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004416 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004417
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004418 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004419 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004420 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004421
4422 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004423 assert(lhptee->isFunctionType());
4424 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004425 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004426 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004427 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004428 lhptee = lhptee.getUnqualifiedType();
4429 rhptee = rhptee.getUnqualifiedType();
4430 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4431 // Check if the pointee types are compatible ignoring the sign.
4432 // We explicitly check for char so that we catch "char" vs
4433 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004434 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004435 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004436 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004437 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004438
4439 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004440 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004441 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004442 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004443
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004444 if (lhptee == rhptee) {
4445 // Types are compatible ignoring the sign. Qualifier incompatibility
4446 // takes priority over sign incompatibility because the sign
4447 // warning can be disabled.
4448 if (ConvTy != Compatible)
4449 return ConvTy;
4450 return IncompatiblePointerSign;
4451 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004452
4453 // If we are a multi-level pointer, it's possible that our issue is simply
4454 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4455 // the eventual target type is the same and the pointers have the same
4456 // level of indirection, this must be the issue.
4457 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4458 do {
4459 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4460 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4461
4462 lhptee = Context.getCanonicalType(lhptee);
4463 rhptee = Context.getCanonicalType(rhptee);
4464 } while (lhptee->isPointerType() && rhptee->isPointerType());
4465
Douglas Gregora4923eb2009-11-16 21:35:15 +00004466 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004467 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004468 }
4469
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004470 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004471 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004472 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004473 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004474}
4475
Steve Naroff1c7d0672008-09-04 15:10:53 +00004476/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4477/// block pointer types are compatible or whether a block and normal pointer
4478/// are compatible. It is more restrict than comparing two function pointer
4479// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004480Sema::AssignConvertType
4481Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004482 QualType rhsType) {
4483 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004484
Steve Naroff1c7d0672008-09-04 15:10:53 +00004485 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004486 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4487 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004488
Steve Naroff1c7d0672008-09-04 15:10:53 +00004489 // make sure we operate on the canonical type
4490 lhptee = Context.getCanonicalType(lhptee);
4491 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004492
Steve Naroff1c7d0672008-09-04 15:10:53 +00004493 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004494
Steve Naroff1c7d0672008-09-04 15:10:53 +00004495 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004496 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004497 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004498
Eli Friedman26784c12009-06-08 05:08:54 +00004499 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004500 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004501 return ConvTy;
4502}
4503
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004504/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4505/// for assignment compatibility.
4506Sema::AssignConvertType
4507Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4508 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4509 return Compatible;
4510 QualType lhptee =
4511 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4512 QualType rhptee =
4513 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4514 // make sure we operate on the canonical type
4515 lhptee = Context.getCanonicalType(lhptee);
4516 rhptee = Context.getCanonicalType(rhptee);
4517 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4518 return CompatiblePointerDiscardsQualifiers;
4519
4520 if (Context.typesAreCompatible(lhsType, rhsType))
4521 return Compatible;
4522 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4523 return IncompatibleObjCQualifiedId;
4524 return IncompatiblePointer;
4525}
4526
Mike Stumpeed9cac2009-02-19 03:04:26 +00004527/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4528/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004529/// pointers. Here are some objectionable examples that GCC considers warnings:
4530///
4531/// int a, *pint;
4532/// short *pshort;
4533/// struct foo *pfoo;
4534///
4535/// pint = pshort; // warning: assignment from incompatible pointer type
4536/// a = pint; // warning: assignment makes integer from pointer without a cast
4537/// pint = a; // warning: assignment makes pointer from integer without a cast
4538/// pint = pfoo; // warning: assignment from incompatible pointer type
4539///
4540/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004541/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004542///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004543Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004544Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004545 // Get canonical types. We're not formatting these types, just comparing
4546 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004547 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4548 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004549
4550 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004551 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004552
David Chisnall0f436562009-08-17 16:35:33 +00004553 if ((lhsType->isObjCClassType() &&
4554 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4555 (rhsType->isObjCClassType() &&
4556 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4557 return Compatible;
4558 }
4559
Douglas Gregor9d293df2008-10-28 00:22:11 +00004560 // If the left-hand side is a reference type, then we are in a
4561 // (rare!) case where we've allowed the use of references in C,
4562 // e.g., as a parameter type in a built-in function. In this case,
4563 // just make sure that the type referenced is compatible with the
4564 // right-hand side type. The caller is responsible for adjusting
4565 // lhsType so that the resulting expression does not have reference
4566 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004567 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004568 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004569 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004570 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004571 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004572 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4573 // to the same ExtVector type.
4574 if (lhsType->isExtVectorType()) {
4575 if (rhsType->isExtVectorType())
4576 return lhsType == rhsType ? Compatible : Incompatible;
4577 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4578 return Compatible;
4579 }
Mike Stump1eb44332009-09-09 15:08:12 +00004580
Nate Begemanbe2341d2008-07-14 18:02:46 +00004581 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004582 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004583 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004584 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004585 if (getLangOptions().LaxVectorConversions &&
4586 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004587 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004588 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004589 }
4590 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004591 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004592
Chris Lattnere8b3e962008-01-04 23:32:24 +00004593 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004594 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004595
Chris Lattner78eca282008-04-07 06:49:41 +00004596 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004597 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004598 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004599
Chris Lattner78eca282008-04-07 06:49:41 +00004600 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004601 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004602
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004603 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004604 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004605 if (lhsType->isVoidPointerType()) // an exception to the rule.
4606 return Compatible;
4607 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004608 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004609 if (rhsType->getAs<BlockPointerType>()) {
4610 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004611 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004612
4613 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004614 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004615 return Compatible;
4616 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004617 return Incompatible;
4618 }
4619
4620 if (isa<BlockPointerType>(lhsType)) {
4621 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004622 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004623
Steve Naroffb4406862008-09-29 18:10:17 +00004624 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004625 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004626 return Compatible;
4627
Steve Naroff1c7d0672008-09-04 15:10:53 +00004628 if (rhsType->isBlockPointerType())
4629 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004630
Ted Kremenek6217b802009-07-29 21:53:49 +00004631 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004632 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004633 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004634 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004635 return Incompatible;
4636 }
4637
Steve Naroff14108da2009-07-10 23:34:53 +00004638 if (isa<ObjCObjectPointerType>(lhsType)) {
4639 if (rhsType->isIntegerType())
4640 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004641
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004642 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004643 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004644 if (rhsType->isVoidPointerType()) // an exception to the rule.
4645 return Compatible;
4646 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004647 }
4648 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004649 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004650 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004651 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004652 if (RHSPT->getPointeeType()->isVoidType())
4653 return Compatible;
4654 }
4655 // Treat block pointers as objects.
4656 if (rhsType->isBlockPointerType())
4657 return Compatible;
4658 return Incompatible;
4659 }
Chris Lattner78eca282008-04-07 06:49:41 +00004660 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004661 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004662 if (lhsType == Context.BoolTy)
4663 return Compatible;
4664
4665 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004666 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004667
Mike Stumpeed9cac2009-02-19 03:04:26 +00004668 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004669 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004670
4671 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004672 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004673 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004674 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004675 }
Steve Naroff14108da2009-07-10 23:34:53 +00004676 if (isa<ObjCObjectPointerType>(rhsType)) {
4677 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4678 if (lhsType == Context.BoolTy)
4679 return Compatible;
4680
4681 if (lhsType->isIntegerType())
4682 return PointerToInt;
4683
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004684 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004685 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004686 if (lhsType->isVoidPointerType()) // an exception to the rule.
4687 return Compatible;
4688 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004689 }
4690 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004691 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004692 return Compatible;
4693 return Incompatible;
4694 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004695
Chris Lattnerfc144e22008-01-04 23:18:45 +00004696 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004697 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004698 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004699 }
4700 return Incompatible;
4701}
4702
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004703/// \brief Constructs a transparent union from an expression that is
4704/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004705static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004706 QualType UnionType, FieldDecl *Field) {
4707 // Build an initializer list that designates the appropriate member
4708 // of the transparent union.
4709 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4710 &E, 1,
4711 SourceLocation());
4712 Initializer->setType(UnionType);
4713 Initializer->setInitializedFieldInUnion(Field);
4714
4715 // Build a compound literal constructing a value of the transparent
4716 // union type from this initializer list.
4717 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4718 false);
4719}
4720
4721Sema::AssignConvertType
4722Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4723 QualType FromType = rExpr->getType();
4724
Mike Stump1eb44332009-09-09 15:08:12 +00004725 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004726 // transparent_union GCC extension.
4727 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004728 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004729 return Incompatible;
4730
4731 // The field to initialize within the transparent union.
4732 RecordDecl *UD = UT->getDecl();
4733 FieldDecl *InitField = 0;
4734 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004735 for (RecordDecl::field_iterator it = UD->field_begin(),
4736 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004737 it != itend; ++it) {
4738 if (it->getType()->isPointerType()) {
4739 // If the transparent union contains a pointer type, we allow:
4740 // 1) void pointer
4741 // 2) null pointer constant
4742 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004743 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004744 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004745 InitField = *it;
4746 break;
4747 }
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Douglas Gregorce940492009-09-25 04:25:58 +00004749 if (rExpr->isNullPointerConstant(Context,
4750 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004751 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004752 InitField = *it;
4753 break;
4754 }
4755 }
4756
4757 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4758 == Compatible) {
4759 InitField = *it;
4760 break;
4761 }
4762 }
4763
4764 if (!InitField)
4765 return Incompatible;
4766
4767 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4768 return Compatible;
4769}
4770
Chris Lattner5cf216b2008-01-04 18:04:52 +00004771Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004772Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004773 if (getLangOptions().CPlusPlus) {
4774 if (!lhsType->isRecordType()) {
4775 // C++ 5.17p3: If the left operand is not of class type, the
4776 // expression is implicitly converted (C++ 4) to the
4777 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004778 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004779 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004780 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004781 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004782 }
4783
4784 // FIXME: Currently, we fall through and treat C++ classes like C
4785 // structures.
4786 }
4787
Steve Naroff529a4ad2007-11-27 17:58:44 +00004788 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4789 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004790 if ((lhsType->isPointerType() ||
4791 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004792 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004793 && rExpr->isNullPointerConstant(Context,
4794 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004795 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004796 return Compatible;
4797 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004798
Chris Lattner943140e2007-10-16 02:55:40 +00004799 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004800 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004801 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004802 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004803 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004804 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004805 if (!lhsType->isReferenceType())
4806 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004807
Chris Lattner5cf216b2008-01-04 18:04:52 +00004808 Sema::AssignConvertType result =
4809 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004810
Steve Narofff1120de2007-08-24 22:33:52 +00004811 // C99 6.5.16.1p2: The value of the right operand is converted to the
4812 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004813 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4814 // so that we can use references in built-in functions even in C.
4815 // The getNonReferenceType() call makes sure that the resulting expression
4816 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004817 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004818 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4819 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004820 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004821}
4822
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004823QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004824 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004825 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004826 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004827 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004828}
4829
Chris Lattner7ef655a2010-01-12 21:23:57 +00004830QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004831 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004832 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004833 QualType lhsType =
4834 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4835 QualType rhsType =
4836 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004837
Nate Begemanbe2341d2008-07-14 18:02:46 +00004838 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004839 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004840 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004841
Nate Begemanbe2341d2008-07-14 18:02:46 +00004842 // Handle the case of a vector & extvector type of the same size and element
4843 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004844 if (getLangOptions().LaxVectorConversions) {
4845 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004846 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4847 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004848 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004849 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004850 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004851 }
4852 }
4853 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004854
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004855 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4856 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4857 bool swapped = false;
4858 if (rhsType->isExtVectorType()) {
4859 swapped = true;
4860 std::swap(rex, lex);
4861 std::swap(rhsType, lhsType);
4862 }
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Nate Begemandde25982009-06-28 19:12:57 +00004864 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004865 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004866 QualType EltTy = LV->getElementType();
4867 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4868 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004869 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004870 if (swapped) std::swap(rex, lex);
4871 return lhsType;
4872 }
4873 }
4874 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4875 rhsType->isRealFloatingType()) {
4876 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004877 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004878 if (swapped) std::swap(rex, lex);
4879 return lhsType;
4880 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004881 }
4882 }
Mike Stump1eb44332009-09-09 15:08:12 +00004883
Nate Begemandde25982009-06-28 19:12:57 +00004884 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004885 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004886 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004887 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004888 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004889}
4890
Chris Lattner7ef655a2010-01-12 21:23:57 +00004891QualType Sema::CheckMultiplyDivideOperands(
4892 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004893 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004894 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004895
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004896 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004897
Chris Lattner7ef655a2010-01-12 21:23:57 +00004898 if (!lex->getType()->isArithmeticType() ||
4899 !rex->getType()->isArithmeticType())
4900 return InvalidOperands(Loc, lex, rex);
4901
4902 // Check for division by zero.
4903 if (isDiv &&
4904 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004905 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4906 << rex->getSourceRange());
Chris Lattner7ef655a2010-01-12 21:23:57 +00004907
4908 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004909}
4910
Chris Lattner7ef655a2010-01-12 21:23:57 +00004911QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004912 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004913 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4914 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4915 return CheckVectorOperands(Loc, lex, rex);
4916 return InvalidOperands(Loc, lex, rex);
4917 }
Steve Naroff90045e82007-07-13 23:32:42 +00004918
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004919 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004920
Chris Lattner7ef655a2010-01-12 21:23:57 +00004921 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4922 return InvalidOperands(Loc, lex, rex);
4923
4924 // Check for remainder by zero.
4925 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004926 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4927 << rex->getSourceRange());
Chris Lattner7ef655a2010-01-12 21:23:57 +00004928
4929 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004930}
4931
Chris Lattner7ef655a2010-01-12 21:23:57 +00004932QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004933 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004934 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4935 QualType compType = CheckVectorOperands(Loc, lex, rex);
4936 if (CompLHSTy) *CompLHSTy = compType;
4937 return compType;
4938 }
Steve Naroff49b45262007-07-13 16:58:59 +00004939
Eli Friedmanab3a8522009-03-28 01:22:36 +00004940 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004941
Reid Spencer5f016e22007-07-11 17:01:13 +00004942 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004943 if (lex->getType()->isArithmeticType() &&
4944 rex->getType()->isArithmeticType()) {
4945 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004946 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004947 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004948
Eli Friedmand72d16e2008-05-18 18:08:51 +00004949 // Put any potential pointer into PExp
4950 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004951 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004952 std::swap(PExp, IExp);
4953
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004954 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004955
Eli Friedmand72d16e2008-05-18 18:08:51 +00004956 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004957 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004958
Chris Lattnerb5f15622009-04-24 23:50:08 +00004959 // Check for arithmetic on pointers to incomplete types.
4960 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004961 if (getLangOptions().CPlusPlus) {
4962 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004963 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004964 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004965 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004966
4967 // GNU extension: arithmetic on pointer to void
4968 Diag(Loc, diag::ext_gnu_void_ptr)
4969 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004970 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004971 if (getLangOptions().CPlusPlus) {
4972 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4973 << lex->getType() << lex->getSourceRange();
4974 return QualType();
4975 }
4976
4977 // GNU extension: arithmetic on pointer to function
4978 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4979 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004980 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004981 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004982 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004983 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004984 PExp->getType()->isObjCObjectPointerType()) &&
4985 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004986 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4987 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004988 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004989 return QualType();
4990 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004991 // Diagnose bad cases where we step over interface counts.
4992 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4993 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4994 << PointeeTy << PExp->getSourceRange();
4995 return QualType();
4996 }
Mike Stump1eb44332009-09-09 15:08:12 +00004997
Eli Friedmanab3a8522009-03-28 01:22:36 +00004998 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004999 QualType LHSTy = Context.isPromotableBitField(lex);
5000 if (LHSTy.isNull()) {
5001 LHSTy = lex->getType();
5002 if (LHSTy->isPromotableIntegerType())
5003 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005004 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005005 *CompLHSTy = LHSTy;
5006 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005007 return PExp->getType();
5008 }
5009 }
5010
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005011 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005012}
5013
Chris Lattnereca7be62008-04-07 05:30:13 +00005014// C99 6.5.6
5015QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005016 SourceLocation Loc, QualType* CompLHSTy) {
5017 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5018 QualType compType = CheckVectorOperands(Loc, lex, rex);
5019 if (CompLHSTy) *CompLHSTy = compType;
5020 return compType;
5021 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005022
Eli Friedmanab3a8522009-03-28 01:22:36 +00005023 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005024
Chris Lattner6e4ab612007-12-09 21:53:25 +00005025 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005026
Chris Lattner6e4ab612007-12-09 21:53:25 +00005027 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005028 if (lex->getType()->isArithmeticType()
5029 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005030 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005031 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005032 }
Mike Stump1eb44332009-09-09 15:08:12 +00005033
Chris Lattner6e4ab612007-12-09 21:53:25 +00005034 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005035 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005036 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005037
Douglas Gregore7450f52009-03-24 19:52:54 +00005038 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005039
Douglas Gregore7450f52009-03-24 19:52:54 +00005040 bool ComplainAboutVoid = false;
5041 Expr *ComplainAboutFunc = 0;
5042 if (lpointee->isVoidType()) {
5043 if (getLangOptions().CPlusPlus) {
5044 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5045 << lex->getSourceRange() << rex->getSourceRange();
5046 return QualType();
5047 }
5048
5049 // GNU C extension: arithmetic on pointer to void
5050 ComplainAboutVoid = true;
5051 } else if (lpointee->isFunctionType()) {
5052 if (getLangOptions().CPlusPlus) {
5053 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005054 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005055 return QualType();
5056 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005057
5058 // GNU C extension: arithmetic on pointer to function
5059 ComplainAboutFunc = lex;
5060 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005061 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005062 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005063 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005064 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005065 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005066
Chris Lattnerb5f15622009-04-24 23:50:08 +00005067 // Diagnose bad cases where we step over interface counts.
5068 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5069 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5070 << lpointee << lex->getSourceRange();
5071 return QualType();
5072 }
Mike Stump1eb44332009-09-09 15:08:12 +00005073
Chris Lattner6e4ab612007-12-09 21:53:25 +00005074 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005075 if (rex->getType()->isIntegerType()) {
5076 if (ComplainAboutVoid)
5077 Diag(Loc, diag::ext_gnu_void_ptr)
5078 << lex->getSourceRange() << rex->getSourceRange();
5079 if (ComplainAboutFunc)
5080 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005081 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005082 << ComplainAboutFunc->getSourceRange();
5083
Eli Friedmanab3a8522009-03-28 01:22:36 +00005084 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005085 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005086 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005087
Chris Lattner6e4ab612007-12-09 21:53:25 +00005088 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005089 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005090 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005091
Douglas Gregore7450f52009-03-24 19:52:54 +00005092 // RHS must be a completely-type object type.
5093 // Handle the GNU void* extension.
5094 if (rpointee->isVoidType()) {
5095 if (getLangOptions().CPlusPlus) {
5096 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5097 << lex->getSourceRange() << rex->getSourceRange();
5098 return QualType();
5099 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005100
Douglas Gregore7450f52009-03-24 19:52:54 +00005101 ComplainAboutVoid = true;
5102 } else if (rpointee->isFunctionType()) {
5103 if (getLangOptions().CPlusPlus) {
5104 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005105 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005106 return QualType();
5107 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005108
5109 // GNU extension: arithmetic on pointer to function
5110 if (!ComplainAboutFunc)
5111 ComplainAboutFunc = rex;
5112 } else if (!rpointee->isDependentType() &&
5113 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005114 PDiag(diag::err_typecheck_sub_ptr_object)
5115 << rex->getSourceRange()
5116 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005117 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005118
Eli Friedman88d936b2009-05-16 13:54:38 +00005119 if (getLangOptions().CPlusPlus) {
5120 // Pointee types must be the same: C++ [expr.add]
5121 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5122 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5123 << lex->getType() << rex->getType()
5124 << lex->getSourceRange() << rex->getSourceRange();
5125 return QualType();
5126 }
5127 } else {
5128 // Pointee types must be compatible C99 6.5.6p3
5129 if (!Context.typesAreCompatible(
5130 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5131 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5132 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5133 << lex->getType() << rex->getType()
5134 << lex->getSourceRange() << rex->getSourceRange();
5135 return QualType();
5136 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005137 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005138
Douglas Gregore7450f52009-03-24 19:52:54 +00005139 if (ComplainAboutVoid)
5140 Diag(Loc, diag::ext_gnu_void_ptr)
5141 << lex->getSourceRange() << rex->getSourceRange();
5142 if (ComplainAboutFunc)
5143 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005144 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005145 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005146
5147 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005148 return Context.getPointerDiffType();
5149 }
5150 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005151
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005152 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005153}
5154
Chris Lattnereca7be62008-04-07 05:30:13 +00005155// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005156QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005157 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005158 // C99 6.5.7p2: Each of the operands shall have integer type.
5159 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005160 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005161
Nate Begeman2207d792009-10-25 02:26:48 +00005162 // Vector shifts promote their scalar inputs to vector type.
5163 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5164 return CheckVectorOperands(Loc, lex, rex);
5165
Chris Lattnerca5eede2007-12-12 05:47:28 +00005166 // Shifts don't perform usual arithmetic conversions, they just do integer
5167 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005168 QualType LHSTy = Context.isPromotableBitField(lex);
5169 if (LHSTy.isNull()) {
5170 LHSTy = lex->getType();
5171 if (LHSTy->isPromotableIntegerType())
5172 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005173 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005174 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005175 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005176
Chris Lattnerca5eede2007-12-12 05:47:28 +00005177 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005178
Ryan Flynnd0439682009-08-07 16:20:20 +00005179 // Sanity-check shift operands
5180 llvm::APSInt Right;
5181 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005182 if (!rex->isValueDependent() &&
5183 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005184 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005185 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5186 else {
5187 llvm::APInt LeftBits(Right.getBitWidth(),
5188 Context.getTypeSize(lex->getType()));
5189 if (Right.uge(LeftBits))
5190 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5191 }
5192 }
5193
Chris Lattnerca5eede2007-12-12 05:47:28 +00005194 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005195 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005196}
5197
Douglas Gregor0c6db942009-05-04 06:07:12 +00005198// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005199QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005200 unsigned OpaqueOpc, bool isRelational) {
5201 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5202
Chris Lattner02dd4b12009-12-05 05:40:13 +00005203 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005204 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005205 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005206
John McCall5dbad3d2009-11-06 08:49:08 +00005207 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5208 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005209
Chris Lattnera5937dd2007-08-26 01:18:55 +00005210 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005211 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5212 UsualArithmeticConversions(lex, rex);
5213 else {
5214 UsualUnaryConversions(lex);
5215 UsualUnaryConversions(rex);
5216 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005217 QualType lType = lex->getType();
5218 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005219
Mike Stumpaf199f32009-05-07 18:43:07 +00005220 if (!lType->isFloatingType()
5221 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005222 // For non-floating point types, check for self-comparisons of the form
5223 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5224 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005225 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005226 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005227 Expr *LHSStripped = lex->IgnoreParens();
5228 Expr *RHSStripped = rex->IgnoreParens();
5229 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5230 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005231 if (DRL->getDecl() == DRR->getDecl() &&
5232 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005233 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump1eb44332009-09-09 15:08:12 +00005234
Chris Lattner55660a72009-03-08 19:39:53 +00005235 if (isa<CastExpr>(LHSStripped))
5236 LHSStripped = LHSStripped->IgnoreParenCasts();
5237 if (isa<CastExpr>(RHSStripped))
5238 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Chris Lattner55660a72009-03-08 19:39:53 +00005240 // Warn about comparisons against a string constant (unless the other
5241 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005242 Expr *literalString = 0;
5243 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005244 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005245 !RHSStripped->isNullPointerConstant(Context,
5246 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005247 literalString = lex;
5248 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005249 } else if ((isa<StringLiteral>(RHSStripped) ||
5250 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005251 !LHSStripped->isNullPointerConstant(Context,
5252 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005253 literalString = rex;
5254 literalStringStripped = RHSStripped;
5255 }
5256
5257 if (literalString) {
5258 std::string resultComparison;
5259 switch (Opc) {
5260 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5261 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5262 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5263 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5264 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5265 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5266 default: assert(false && "Invalid comparison operator");
5267 }
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005268
5269 DiagRuntimeBehavior(Loc,
5270 PDiag(diag::warn_stringcompare)
5271 << isa<ObjCEncodeExpr>(literalStringStripped)
5272 << literalString->getSourceRange()
5273 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5274 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5275 "strcmp(")
5276 << CodeModificationHint::CreateInsertion(
5277 PP.getLocForEndOfToken(rex->getLocEnd()),
5278 resultComparison));
Douglas Gregora86b8322009-04-06 18:45:53 +00005279 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005280 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005281
Douglas Gregor447b69e2008-11-19 03:25:36 +00005282 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005283 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005284
Chris Lattnera5937dd2007-08-26 01:18:55 +00005285 if (isRelational) {
5286 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005287 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005288 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005289 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005290 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005291 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005292
Chris Lattnera5937dd2007-08-26 01:18:55 +00005293 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005294 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005295 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005296
Douglas Gregorce940492009-09-25 04:25:58 +00005297 bool LHSIsNull = lex->isNullPointerConstant(Context,
5298 Expr::NPC_ValueDependentIsNull);
5299 bool RHSIsNull = rex->isNullPointerConstant(Context,
5300 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005301
Chris Lattnera5937dd2007-08-26 01:18:55 +00005302 // All of the following pointer related warnings are GCC extensions, except
5303 // when handling null pointer constants. One day, we can consider making them
5304 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005305 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005306 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005307 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005308 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005309 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005310
Douglas Gregor0c6db942009-05-04 06:07:12 +00005311 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005312 if (LCanPointeeTy == RCanPointeeTy)
5313 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005314 if (!isRelational &&
5315 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5316 // Valid unless comparison between non-null pointer and function pointer
5317 // This is a gcc extension compatibility comparison.
5318 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5319 && !LHSIsNull && !RHSIsNull) {
5320 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5321 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5322 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5323 return ResultTy;
5324 }
5325 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005326 // C++ [expr.rel]p2:
5327 // [...] Pointer conversions (4.10) and qualification
5328 // conversions (4.4) are performed on pointer operands (or on
5329 // a pointer operand and a null pointer constant) to bring
5330 // them to their composite pointer type. [...]
5331 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005332 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005333 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005334 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005335 if (T.isNull()) {
5336 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5337 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5338 return QualType();
5339 }
5340
Eli Friedman73c39ab2009-10-20 08:27:19 +00005341 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5342 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005343 return ResultTy;
5344 }
Eli Friedman3075e762009-08-23 00:27:47 +00005345 // C99 6.5.9p2 and C99 6.5.8p2
5346 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5347 RCanPointeeTy.getUnqualifiedType())) {
5348 // Valid unless a relational comparison of function pointers
5349 if (isRelational && LCanPointeeTy->isFunctionType()) {
5350 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5351 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5352 }
5353 } else if (!isRelational &&
5354 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5355 // Valid unless comparison between non-null pointer and function pointer
5356 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5357 && !LHSIsNull && !RHSIsNull) {
5358 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5359 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5360 }
5361 } else {
5362 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005363 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005364 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005365 }
Eli Friedman3075e762009-08-23 00:27:47 +00005366 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005367 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005368 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005369 }
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005371 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005372 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005373 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005374 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005375 (lType->isPointerType() ||
5376 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005377 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005378 return ResultTy;
5379 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005380 if (LHSIsNull &&
5381 (rType->isPointerType() ||
5382 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005383 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005384 return ResultTy;
5385 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005386
5387 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005388 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005389 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5390 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005391 // In addition, pointers to members can be compared, or a pointer to
5392 // member and a null pointer constant. Pointer to member conversions
5393 // (4.11) and qualification conversions (4.4) are performed to bring
5394 // them to a common type. If one operand is a null pointer constant,
5395 // the common type is the type of the other operand. Otherwise, the
5396 // common type is a pointer to member type similar (4.4) to the type
5397 // of one of the operands, with a cv-qualification signature (4.4)
5398 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005399 // types.
5400 QualType T = FindCompositePointerType(lex, rex);
5401 if (T.isNull()) {
5402 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5403 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5404 return QualType();
5405 }
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Eli Friedman73c39ab2009-10-20 08:27:19 +00005407 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5408 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005409 return ResultTy;
5410 }
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Douglas Gregor20b3e992009-08-24 17:42:35 +00005412 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005413 if (lType->isNullPtrType() && rType->isNullPtrType())
5414 return ResultTy;
5415 }
Mike Stump1eb44332009-09-09 15:08:12 +00005416
Steve Naroff1c7d0672008-09-04 15:10:53 +00005417 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005418 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005419 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5420 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005421
Steve Naroff1c7d0672008-09-04 15:10:53 +00005422 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005423 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005424 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005425 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005426 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005427 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005428 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005429 }
Steve Naroff59f53942008-09-28 01:11:11 +00005430 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005431 if (!isRelational
5432 && ((lType->isBlockPointerType() && rType->isPointerType())
5433 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005434 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005435 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005436 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005437 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005438 ->getPointeeType()->isVoidType())))
5439 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5440 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005441 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005442 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005443 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005444 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005445
Steve Naroff14108da2009-07-10 23:34:53 +00005446 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005447 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005448 const PointerType *LPT = lType->getAs<PointerType>();
5449 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005450 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005451 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005452 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005453 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454
Steve Naroffa8069f12008-11-17 19:49:16 +00005455 if (!LPtrToVoid && !RPtrToVoid &&
5456 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005457 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005458 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005459 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005460 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005461 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005462 }
Steve Naroff14108da2009-07-10 23:34:53 +00005463 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005464 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005465 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5466 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005467 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005468 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005469 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005470 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005471 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005472 unsigned DiagID = 0;
5473 if (RHSIsNull) {
5474 if (isRelational)
5475 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5476 } else if (isRelational)
5477 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5478 else
5479 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005480
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005481 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005482 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005483 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005484 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005485 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005486 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005487 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005488 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005489 unsigned DiagID = 0;
5490 if (LHSIsNull) {
5491 if (isRelational)
5492 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5493 } else if (isRelational)
5494 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5495 else
5496 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005497
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005498 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005499 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005500 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005501 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005502 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005503 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005504 }
Steve Naroff39218df2008-09-04 16:56:14 +00005505 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005506 if (!isRelational && RHSIsNull
5507 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005508 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005509 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005510 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005511 if (!isRelational && LHSIsNull
5512 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005513 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005514 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005515 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005516 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005517}
5518
Nate Begemanbe2341d2008-07-14 18:02:46 +00005519/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005520/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005521/// like a scalar comparison, a vector comparison produces a vector of integer
5522/// types.
5523QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005524 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005525 bool isRelational) {
5526 // Check to make sure we're operating on vectors of the same type and width,
5527 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005528 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005529 if (vType.isNull())
5530 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005531
Nate Begemanbe2341d2008-07-14 18:02:46 +00005532 QualType lType = lex->getType();
5533 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005534
Nate Begemanbe2341d2008-07-14 18:02:46 +00005535 // For non-floating point types, check for self-comparisons of the form
5536 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5537 // often indicate logic errors in the program.
5538 if (!lType->isFloatingType()) {
5539 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5540 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5541 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005542 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begemanbe2341d2008-07-14 18:02:46 +00005543 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005544
Nate Begemanbe2341d2008-07-14 18:02:46 +00005545 // Check for comparisons of floating point operands using != and ==.
5546 if (!isRelational && lType->isFloatingType()) {
5547 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005548 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005549 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005550
Nate Begemanbe2341d2008-07-14 18:02:46 +00005551 // Return the type for the comparison, which is the same as vector type for
5552 // integer vectors, or an integer type of identical size and number of
5553 // elements for floating point vectors.
5554 if (lType->isIntegerType())
5555 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005556
John McCall183700f2009-09-21 23:43:11 +00005557 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005558 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005559 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005560 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005561 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005562 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5563
Mike Stumpeed9cac2009-02-19 03:04:26 +00005564 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005565 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005566 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5567}
5568
Reid Spencer5f016e22007-07-11 17:01:13 +00005569inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005570 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005571 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005572 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005573
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005574 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005575
Steve Naroffa4332e22007-07-17 00:58:39 +00005576 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005577 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005578 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005579}
5580
5581inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005582 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005583 if (!Context.getLangOptions().CPlusPlus) {
5584 UsualUnaryConversions(lex);
5585 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005586
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005587 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5588 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005589
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005590 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005591 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005592
5593 // C++ [expr.log.and]p1
5594 // C++ [expr.log.or]p1
5595 // The operands are both implicitly converted to type bool (clause 4).
5596 StandardConversionSequence LHS;
5597 if (!IsStandardConversion(lex, Context.BoolTy,
5598 /*InOverloadResolution=*/false, LHS))
5599 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005600
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005601 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005602 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005603 return InvalidOperands(Loc, lex, rex);
5604
5605 StandardConversionSequence RHS;
5606 if (!IsStandardConversion(rex, Context.BoolTy,
5607 /*InOverloadResolution=*/false, RHS))
5608 return InvalidOperands(Loc, lex, rex);
5609
5610 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005611 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005612 return InvalidOperands(Loc, lex, rex);
5613
5614 // C++ [expr.log.and]p2
5615 // C++ [expr.log.or]p2
5616 // The result is a bool.
5617 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005618}
5619
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005620/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5621/// is a read-only property; return true if so. A readonly property expression
5622/// depends on various declarations and thus must be treated specially.
5623///
Mike Stump1eb44332009-09-09 15:08:12 +00005624static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005625 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5626 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5627 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5628 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005629 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005630 BaseType->getAsObjCInterfacePointerType())
5631 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5632 if (S.isPropertyReadonly(PDecl, IFace))
5633 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005634 }
5635 }
5636 return false;
5637}
5638
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005639/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5640/// emit an error and return true. If so, return false.
5641static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005642 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005643 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005644 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005645 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5646 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005647 if (IsLV == Expr::MLV_Valid)
5648 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005649
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005650 unsigned Diag = 0;
5651 bool NeedType = false;
5652 switch (IsLV) { // C99 6.5.16p2
5653 default: assert(0 && "Unknown result from isModifiableLvalue!");
5654 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005655 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005656 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5657 NeedType = true;
5658 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005659 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005660 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5661 NeedType = true;
5662 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005663 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005664 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5665 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005666 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005667 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5668 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005669 case Expr::MLV_IncompleteType:
5670 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005671 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005672 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5673 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005674 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005675 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5676 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005677 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005678 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5679 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005680 case Expr::MLV_ReadonlyProperty:
5681 Diag = diag::error_readonly_property_assignment;
5682 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005683 case Expr::MLV_NoSetterProperty:
5684 Diag = diag::error_nosetter_property_assignment;
5685 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005686 case Expr::MLV_SubObjCPropertySetting:
5687 Diag = diag::error_no_subobject_property_setting;
5688 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005689 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005690
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005691 SourceRange Assign;
5692 if (Loc != OrigLoc)
5693 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005694 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005695 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005696 else
Mike Stump1eb44332009-09-09 15:08:12 +00005697 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005698 return true;
5699}
5700
5701
5702
5703// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005704QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5705 SourceLocation Loc,
5706 QualType CompoundType) {
5707 // Verify that LHS is a modifiable lvalue, and emit error if not.
5708 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005709 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005710
5711 QualType LHSType = LHS->getType();
5712 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005713
Chris Lattner5cf216b2008-01-04 18:04:52 +00005714 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005715 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005716 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005717 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005718 // Special case of NSObject attributes on c-style pointer types.
5719 if (ConvTy == IncompatiblePointer &&
5720 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005721 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005722 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005723 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005724 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005725
Chris Lattner2c156472008-08-21 18:04:13 +00005726 // If the RHS is a unary plus or minus, check to see if they = and + are
5727 // right next to each other. If so, the user may have typo'd "x =+ 4"
5728 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005729 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005730 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5731 RHSCheck = ICE->getSubExpr();
5732 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5733 if ((UO->getOpcode() == UnaryOperator::Plus ||
5734 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005735 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005736 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005737 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5738 // And there is a space or other character before the subexpr of the
5739 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005740 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5741 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005742 Diag(Loc, diag::warn_not_compound_assign)
5743 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5744 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005745 }
Chris Lattner2c156472008-08-21 18:04:13 +00005746 }
5747 } else {
5748 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005749 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005750 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005751
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005752 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005753 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005754 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005755
Reid Spencer5f016e22007-07-11 17:01:13 +00005756 // C99 6.5.16p3: The type of an assignment expression is the type of the
5757 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005758 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005759 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5760 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005761 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005762 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005763 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005764}
5765
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005766// C99 6.5.17
5767QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005768 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005769 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005770
5771 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5772 // incomplete in C++).
5773
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005774 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005775}
5776
Steve Naroff49b45262007-07-13 16:58:59 +00005777/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5778/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005779QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5780 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005781 if (Op->isTypeDependent())
5782 return Context.DependentTy;
5783
Chris Lattner3528d352008-11-21 07:05:48 +00005784 QualType ResType = Op->getType();
5785 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005786
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005787 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5788 // Decrement of bool is not allowed.
5789 if (!isInc) {
5790 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5791 return QualType();
5792 }
5793 // Increment of bool sets it to true, but is deprecated.
5794 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5795 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005796 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005797 } else if (ResType->isAnyPointerType()) {
5798 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005799
Chris Lattner3528d352008-11-21 07:05:48 +00005800 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005801 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005802 if (getLangOptions().CPlusPlus) {
5803 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5804 << Op->getSourceRange();
5805 return QualType();
5806 }
5807
5808 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005809 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005810 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005811 if (getLangOptions().CPlusPlus) {
5812 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5813 << Op->getType() << Op->getSourceRange();
5814 return QualType();
5815 }
5816
5817 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005818 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005819 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005820 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005821 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005822 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005823 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005824 // Diagnose bad cases where we step over interface counts.
5825 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5826 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5827 << PointeeTy << Op->getSourceRange();
5828 return QualType();
5829 }
Eli Friedman5b088a12010-01-03 00:20:48 +00005830 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005831 // C99 does not support ++/-- on complex types, we allow as an extension.
5832 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005833 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005834 } else {
5835 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005836 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005837 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005838 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005839 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005840 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005841 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005842 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005843 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005844}
5845
Anders Carlsson369dee42008-02-01 07:15:58 +00005846/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005847/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005848/// where the declaration is needed for type checking. We only need to
5849/// handle cases when the expression references a function designator
5850/// or is an lvalue. Here are some examples:
5851/// - &(x) => x
5852/// - &*****f => f for f a function designator.
5853/// - &s.xx => s
5854/// - &s.zz[1].yy -> s, if zz is an array
5855/// - *(x + 1) -> x, if x is an array
5856/// - &"123"[2] -> 0
5857/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005858static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005859 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005860 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005861 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005862 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005863 // If this is an arrow operator, the address is an offset from
5864 // the base's value, so the object the base refers to is
5865 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005866 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005867 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005868 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005869 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005870 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005871 // FIXME: This code shouldn't be necessary! We should catch the implicit
5872 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005873 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5874 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5875 if (ICE->getSubExpr()->getType()->isArrayType())
5876 return getPrimaryDecl(ICE->getSubExpr());
5877 }
5878 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005879 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005880 case Stmt::UnaryOperatorClass: {
5881 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005882
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005883 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005884 case UnaryOperator::Real:
5885 case UnaryOperator::Imag:
5886 case UnaryOperator::Extension:
5887 return getPrimaryDecl(UO->getSubExpr());
5888 default:
5889 return 0;
5890 }
5891 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005892 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005893 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005894 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005895 // If the result of an implicit cast is an l-value, we care about
5896 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005897 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005898 default:
5899 return 0;
5900 }
5901}
5902
5903/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005904/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005905/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005906/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005907/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005908/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005909/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005910QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005911 // Make sure to ignore parentheses in subsequent checks
5912 op = op->IgnoreParens();
5913
Douglas Gregor9103bb22008-12-17 22:52:20 +00005914 if (op->isTypeDependent())
5915 return Context.DependentTy;
5916
Steve Naroff08f19672008-01-13 17:10:08 +00005917 if (getLangOptions().C99) {
5918 // Implement C99-only parts of addressof rules.
5919 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5920 if (uOp->getOpcode() == UnaryOperator::Deref)
5921 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5922 // (assuming the deref expression is valid).
5923 return uOp->getSubExpr()->getType();
5924 }
5925 // Technically, there should be a check for array subscript
5926 // expressions here, but the result of one is always an lvalue anyway.
5927 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005928 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005929 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005930
Sebastian Redle27d87f2010-01-11 15:56:56 +00005931 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5932 if (lval == Expr::LV_MemberFunction && ME &&
5933 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5934 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5935 // &f where f is a member of the current object, or &o.f, or &p->f
5936 // All these are not allowed, and we need to catch them before the dcl
5937 // branch of the if, below.
5938 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5939 << dcl;
5940 // FIXME: Improve this diagnostic and provide a fixit.
5941
5942 // Now recover by acting as if the function had been accessed qualified.
5943 return Context.getMemberPointerType(op->getType(),
5944 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5945 .getTypePtr());
5946 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00005947 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005948 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005949 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005950 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005951 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5952 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005953 return QualType();
5954 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005955 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005956 // The operand cannot be a bit-field
5957 Diag(OpLoc, diag::err_typecheck_address_of)
5958 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005959 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005960 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5961 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005962 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005963 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005964 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005965 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005966 } else if (isa<ObjCPropertyRefExpr>(op)) {
5967 // cannot take address of a property expression.
5968 Diag(OpLoc, diag::err_typecheck_address_of)
5969 << "property expression" << op->getSourceRange();
5970 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005971 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5972 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005973 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5974 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005975 } else if (isa<UnresolvedLookupExpr>(op)) {
5976 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005977 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005978 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005979 // with the register storage-class specifier.
5980 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5981 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005982 Diag(OpLoc, diag::err_typecheck_address_of)
5983 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005984 return QualType();
5985 }
John McCallba135432009-11-21 08:51:07 +00005986 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005987 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005988 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005989 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005990 // Could be a pointer to member, though, if there is an explicit
5991 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005992 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005993 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005994 if (Ctx && Ctx->isRecord()) {
5995 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005996 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005997 diag::err_cannot_form_pointer_to_member_of_reference_type)
5998 << FD->getDeclName() << FD->getType();
5999 return QualType();
6000 }
Mike Stump1eb44332009-09-09 15:08:12 +00006001
Sebastian Redlebc07d52009-02-03 20:19:35 +00006002 return Context.getMemberPointerType(op->getType(),
6003 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006004 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006005 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006006 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006007 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006008 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006009 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6010 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006011 return Context.getMemberPointerType(op->getType(),
6012 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6013 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006014 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006015 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006016
Eli Friedman441cf102009-05-16 23:27:50 +00006017 if (lval == Expr::LV_IncompleteVoidType) {
6018 // Taking the address of a void variable is technically illegal, but we
6019 // allow it in cases which are otherwise valid.
6020 // Example: "extern void x; void* y = &x;".
6021 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6022 }
6023
Reid Spencer5f016e22007-07-11 17:01:13 +00006024 // If the operand has type "type", the result has type "pointer to type".
6025 return Context.getPointerType(op->getType());
6026}
6027
Chris Lattner22caddc2008-11-23 09:13:29 +00006028QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006029 if (Op->isTypeDependent())
6030 return Context.DependentTy;
6031
Chris Lattner22caddc2008-11-23 09:13:29 +00006032 UsualUnaryConversions(Op);
6033 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006034
Chris Lattner22caddc2008-11-23 09:13:29 +00006035 // Note that per both C89 and C99, this is always legal, even if ptype is an
6036 // incomplete type or void. It would be possible to warn about dereferencing
6037 // a void pointer, but it's completely well-defined, and such a warning is
6038 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00006039 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00006040 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006041
John McCall183700f2009-09-21 23:43:11 +00006042 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00006043 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00006044
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006045 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00006046 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006047 return QualType();
6048}
6049
6050static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6051 tok::TokenKind Kind) {
6052 BinaryOperator::Opcode Opc;
6053 switch (Kind) {
6054 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006055 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6056 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006057 case tok::star: Opc = BinaryOperator::Mul; break;
6058 case tok::slash: Opc = BinaryOperator::Div; break;
6059 case tok::percent: Opc = BinaryOperator::Rem; break;
6060 case tok::plus: Opc = BinaryOperator::Add; break;
6061 case tok::minus: Opc = BinaryOperator::Sub; break;
6062 case tok::lessless: Opc = BinaryOperator::Shl; break;
6063 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6064 case tok::lessequal: Opc = BinaryOperator::LE; break;
6065 case tok::less: Opc = BinaryOperator::LT; break;
6066 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6067 case tok::greater: Opc = BinaryOperator::GT; break;
6068 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6069 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6070 case tok::amp: Opc = BinaryOperator::And; break;
6071 case tok::caret: Opc = BinaryOperator::Xor; break;
6072 case tok::pipe: Opc = BinaryOperator::Or; break;
6073 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6074 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6075 case tok::equal: Opc = BinaryOperator::Assign; break;
6076 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6077 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6078 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6079 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6080 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6081 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6082 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6083 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6084 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6085 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6086 case tok::comma: Opc = BinaryOperator::Comma; break;
6087 }
6088 return Opc;
6089}
6090
6091static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6092 tok::TokenKind Kind) {
6093 UnaryOperator::Opcode Opc;
6094 switch (Kind) {
6095 default: assert(0 && "Unknown unary op!");
6096 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6097 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6098 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6099 case tok::star: Opc = UnaryOperator::Deref; break;
6100 case tok::plus: Opc = UnaryOperator::Plus; break;
6101 case tok::minus: Opc = UnaryOperator::Minus; break;
6102 case tok::tilde: Opc = UnaryOperator::Not; break;
6103 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006104 case tok::kw___real: Opc = UnaryOperator::Real; break;
6105 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6106 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6107 }
6108 return Opc;
6109}
6110
Douglas Gregoreaebc752008-11-06 23:29:22 +00006111/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6112/// operator @p Opc at location @c TokLoc. This routine only supports
6113/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006114Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6115 unsigned Op,
6116 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006117 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006118 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006119 // The following two variables are used for compound assignment operators
6120 QualType CompLHSTy; // Type of LHS after promotions for computation
6121 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006122
6123 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006124 case BinaryOperator::Assign:
6125 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6126 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006127 case BinaryOperator::PtrMemD:
6128 case BinaryOperator::PtrMemI:
6129 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6130 Opc == BinaryOperator::PtrMemI);
6131 break;
6132 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006133 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006134 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6135 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006136 break;
6137 case BinaryOperator::Rem:
6138 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6139 break;
6140 case BinaryOperator::Add:
6141 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6142 break;
6143 case BinaryOperator::Sub:
6144 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6145 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006146 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006147 case BinaryOperator::Shr:
6148 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6149 break;
6150 case BinaryOperator::LE:
6151 case BinaryOperator::LT:
6152 case BinaryOperator::GE:
6153 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006154 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006155 break;
6156 case BinaryOperator::EQ:
6157 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006158 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006159 break;
6160 case BinaryOperator::And:
6161 case BinaryOperator::Xor:
6162 case BinaryOperator::Or:
6163 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6164 break;
6165 case BinaryOperator::LAnd:
6166 case BinaryOperator::LOr:
6167 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6168 break;
6169 case BinaryOperator::MulAssign:
6170 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006171 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6172 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006173 CompLHSTy = CompResultTy;
6174 if (!CompResultTy.isNull())
6175 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006176 break;
6177 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006178 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6179 CompLHSTy = CompResultTy;
6180 if (!CompResultTy.isNull())
6181 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006182 break;
6183 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006184 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6185 if (!CompResultTy.isNull())
6186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006187 break;
6188 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006189 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6190 if (!CompResultTy.isNull())
6191 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006192 break;
6193 case BinaryOperator::ShlAssign:
6194 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006195 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6196 CompLHSTy = CompResultTy;
6197 if (!CompResultTy.isNull())
6198 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006199 break;
6200 case BinaryOperator::AndAssign:
6201 case BinaryOperator::XorAssign:
6202 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006203 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6204 CompLHSTy = CompResultTy;
6205 if (!CompResultTy.isNull())
6206 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006207 break;
6208 case BinaryOperator::Comma:
6209 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6210 break;
6211 }
6212 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006213 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006214 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006215 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6216 else
6217 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006218 CompLHSTy, CompResultTy,
6219 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006220}
6221
Sebastian Redlaee3c932009-10-27 12:10:02 +00006222/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6223/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006224static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6225 const PartialDiagnostic &PD,
Douglas Gregor827feec2010-01-08 00:20:23 +00006226 SourceRange ParenRange,
6227 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6228 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006229 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6230 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6231 // We can't display the parentheses, so just dig the
6232 // warning/error and return.
6233 Self.Diag(Loc, PD);
6234 return;
6235 }
6236
6237 Self.Diag(Loc, PD)
6238 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6239 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00006240
6241 if (!SecondPD.getDiagID())
6242 return;
6243
6244 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6245 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6246 // We can't display the parentheses, so just dig the
6247 // warning/error and return.
6248 Self.Diag(Loc, SecondPD);
6249 return;
6250 }
6251
6252 Self.Diag(Loc, SecondPD)
6253 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6254 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006255}
6256
Sebastian Redlaee3c932009-10-27 12:10:02 +00006257/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6258/// operators are mixed in a way that suggests that the programmer forgot that
6259/// comparison operators have higher precedence. The most typical example of
6260/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006261static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6262 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006263 typedef BinaryOperator BinOp;
6264 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6265 rhsopc = static_cast<BinOp::Opcode>(-1);
6266 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006267 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006268 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006269 rhsopc = BO->getOpcode();
6270
6271 // Subs are not binary operators.
6272 if (lhsopc == -1 && rhsopc == -1)
6273 return;
6274
6275 // Bitwise operations are sometimes used as eager logical ops.
6276 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006277 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6278 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006279 return;
6280
Sebastian Redlaee3c932009-10-27 12:10:02 +00006281 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006282 SuggestParentheses(Self, OpLoc,
6283 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006284 << SourceRange(lhs->getLocStart(), OpLoc)
6285 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006286 lhs->getSourceRange(),
6287 PDiag(diag::note_precedence_bitwise_first)
6288 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006289 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6290 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006291 SuggestParentheses(Self, OpLoc,
6292 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006293 << SourceRange(OpLoc, rhs->getLocEnd())
6294 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006295 rhs->getSourceRange(),
6296 PDiag(diag::note_precedence_bitwise_first)
6297 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006298 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006299}
6300
6301/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6302/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6303/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6304static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6305 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006306 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006307 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6308}
6309
Reid Spencer5f016e22007-07-11 17:01:13 +00006310// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006311Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6312 tok::TokenKind Kind,
6313 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006314 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006315 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006316
Steve Narofff69936d2007-09-16 03:34:24 +00006317 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6318 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006319
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006320 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6321 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6322
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006323 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6324}
6325
6326Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6327 BinaryOperator::Opcode Opc,
6328 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006329 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006330 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006331 rhs->getType()->isOverloadableType())) {
6332 // Find all of the overloaded operators visible from this
6333 // point. We perform both an operator-name lookup from the local
6334 // scope and an argument-dependent lookup based on the types of
6335 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006336 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006337 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6338 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006339 if (S)
6340 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6341 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006342 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006343 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006344 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006345 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006346 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006347
Douglas Gregor063daf62009-03-13 18:40:31 +00006348 // Build the (potentially-overloaded, potentially-dependent)
6349 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006350 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006351 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006352
Douglas Gregoreaebc752008-11-06 23:29:22 +00006353 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006354 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006355}
6356
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006357Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006358 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006359 ExprArg InputArg) {
6360 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006361
Mike Stump390b4cc2009-05-16 07:39:55 +00006362 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006363 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006364 QualType resultType;
6365 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006366 case UnaryOperator::OffsetOf:
6367 assert(false && "Invalid unary operator");
6368 break;
6369
Reid Spencer5f016e22007-07-11 17:01:13 +00006370 case UnaryOperator::PreInc:
6371 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006372 case UnaryOperator::PostInc:
6373 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006374 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006375 Opc == UnaryOperator::PreInc ||
6376 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006377 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006378 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006379 resultType = CheckAddressOfOperand(Input, OpLoc);
6380 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006381 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006382 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006383 resultType = CheckIndirectionOperand(Input, OpLoc);
6384 break;
6385 case UnaryOperator::Plus:
6386 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006387 UsualUnaryConversions(Input);
6388 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006389 if (resultType->isDependentType())
6390 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006391 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6392 break;
6393 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6394 resultType->isEnumeralType())
6395 break;
6396 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6397 Opc == UnaryOperator::Plus &&
6398 resultType->isPointerType())
6399 break;
6400
Sebastian Redl0eb23302009-01-19 00:08:26 +00006401 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6402 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006403 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006404 UsualUnaryConversions(Input);
6405 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006406 if (resultType->isDependentType())
6407 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006408 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6409 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6410 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006411 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006412 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006413 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006414 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6415 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006416 break;
6417 case UnaryOperator::LNot: // logical negation
6418 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006419 DefaultFunctionArrayConversion(Input);
6420 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006421 if (resultType->isDependentType())
6422 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006423 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006424 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6425 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006426 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006427 // In C++, it's bool. C++ 5.3.1p8
6428 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006429 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006430 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006431 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006432 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006433 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006434 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006435 resultType = Input->getType();
6436 break;
6437 }
6438 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006439 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006440
6441 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006442 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006443}
6444
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006445Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6446 UnaryOperator::Opcode Opc,
6447 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006448 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006449 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6450 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006451 // Find all of the overloaded operators visible from this
6452 // point. We perform both an operator-name lookup from the local
6453 // scope and an argument-dependent lookup based on the types of
6454 // the arguments.
6455 FunctionSet Functions;
6456 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6457 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006458 if (S)
6459 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6460 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006461 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006462 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006463 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006464 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006465
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006466 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6467 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006468
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006469 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6470}
6471
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006472// Unary Operators. 'Tok' is the token for the operator.
6473Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6474 tok::TokenKind Op, ExprArg input) {
6475 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6476}
6477
Steve Naroff1b273c42007-09-16 14:56:35 +00006478/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006479Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6480 SourceLocation LabLoc,
6481 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006482 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006483 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006484
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006485 // If we haven't seen this label yet, create a forward reference. It
6486 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006487 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006488 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006489
Reid Spencer5f016e22007-07-11 17:01:13 +00006490 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006491 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6492 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006493}
6494
Sebastian Redlf53597f2009-03-15 17:47:39 +00006495Sema::OwningExprResult
6496Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6497 SourceLocation RPLoc) { // "({..})"
6498 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006499 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6500 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6501
Eli Friedmandca2b732009-01-24 23:09:00 +00006502 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006503 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006504 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006505
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006506 // FIXME: there are a variety of strange constraints to enforce here, for
6507 // example, it is not possible to goto into a stmt expression apparently.
6508 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006509
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006510 // If there are sub stmts in the compound stmt, take the type of the last one
6511 // as the type of the stmtexpr.
6512 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006513
Chris Lattner611b2ec2008-07-26 19:51:01 +00006514 if (!Compound->body_empty()) {
6515 Stmt *LastStmt = Compound->body_back();
6516 // If LastStmt is a label, skip down through into the body.
6517 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6518 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006519
Chris Lattner611b2ec2008-07-26 19:51:01 +00006520 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006521 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006522 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006523
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006524 // FIXME: Check that expression type is complete/non-abstract; statement
6525 // expressions are not lvalues.
6526
Sebastian Redlf53597f2009-03-15 17:47:39 +00006527 substmt.release();
6528 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006529}
Steve Naroffd34e9152007-08-01 22:05:33 +00006530
Sebastian Redlf53597f2009-03-15 17:47:39 +00006531Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6532 SourceLocation BuiltinLoc,
6533 SourceLocation TypeLoc,
6534 TypeTy *argty,
6535 OffsetOfComponent *CompPtr,
6536 unsigned NumComponents,
6537 SourceLocation RPLoc) {
6538 // FIXME: This function leaks all expressions in the offset components on
6539 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006540 // FIXME: Preserve type source info.
6541 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006542 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006543
Sebastian Redl28507842009-02-26 14:39:58 +00006544 bool Dependent = ArgTy->isDependentType();
6545
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006546 // We must have at least one component that refers to the type, and the first
6547 // one is known to be a field designator. Verify that the ArgTy represents
6548 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006549 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006550 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006551
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006552 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6553 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006554
Eli Friedman35183ac2009-02-27 06:44:11 +00006555 // Otherwise, create a null pointer as the base, and iteratively process
6556 // the offsetof designators.
6557 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6558 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006559 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006560 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006561
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006562 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6563 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006564 // FIXME: This diagnostic isn't actually visible because the location is in
6565 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006566 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006567 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6568 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006569
Sebastian Redl28507842009-02-26 14:39:58 +00006570 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006571 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006572
John McCalld00f2002009-11-04 03:03:43 +00006573 if (RequireCompleteType(TypeLoc, Res->getType(),
6574 diag::err_offsetof_incomplete_type))
6575 return ExprError();
6576
Sebastian Redl28507842009-02-26 14:39:58 +00006577 // FIXME: Dependent case loses a lot of information here. And probably
6578 // leaks like a sieve.
6579 for (unsigned i = 0; i != NumComponents; ++i) {
6580 const OffsetOfComponent &OC = CompPtr[i];
6581 if (OC.isBrackets) {
6582 // Offset of an array sub-field. TODO: Should we allow vector elements?
6583 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6584 if (!AT) {
6585 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006586 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6587 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006588 }
6589
6590 // FIXME: C++: Verify that operator[] isn't overloaded.
6591
Eli Friedman35183ac2009-02-27 06:44:11 +00006592 // Promote the array so it looks more like a normal array subscript
6593 // expression.
6594 DefaultFunctionArrayConversion(Res);
6595
Sebastian Redl28507842009-02-26 14:39:58 +00006596 // C99 6.5.2.1p1
6597 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006598 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006599 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006600 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006601 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006602 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006603
6604 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6605 OC.LocEnd);
6606 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006607 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006608
Ted Kremenek6217b802009-07-29 21:53:49 +00006609 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006610 if (!RC) {
6611 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006612 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6613 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006614 }
Chris Lattner704fe352007-08-30 17:59:59 +00006615
Sebastian Redl28507842009-02-26 14:39:58 +00006616 // Get the decl corresponding to this.
6617 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006618 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006619 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6620 DiagRuntimeBehavior(BuiltinLoc,
6621 PDiag(diag::warn_offsetof_non_pod_type)
6622 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6623 << Res->getType()))
6624 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006625 }
Mike Stump1eb44332009-09-09 15:08:12 +00006626
John McCalla24dc2e2009-11-17 02:14:36 +00006627 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6628 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006629
John McCall1bcee0a2009-12-02 08:25:40 +00006630 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006631 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006632 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006633 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6634 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006635
Sebastian Redl28507842009-02-26 14:39:58 +00006636 // FIXME: C++: Verify that MemberDecl isn't a static field.
6637 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006638 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006639 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006640 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006641 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006642 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006643 // MemberDecl->getType() doesn't get the right qualifiers, but it
6644 // doesn't matter here.
6645 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6646 MemberDecl->getType().getNonReferenceType());
6647 }
Sebastian Redl28507842009-02-26 14:39:58 +00006648 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006649 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006650
Sebastian Redlf53597f2009-03-15 17:47:39 +00006651 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6652 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006653}
6654
6655
Sebastian Redlf53597f2009-03-15 17:47:39 +00006656Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6657 TypeTy *arg1,TypeTy *arg2,
6658 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006659 // FIXME: Preserve type source info.
6660 QualType argT1 = GetTypeFromParser(arg1);
6661 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006662
Steve Naroffd34e9152007-08-01 22:05:33 +00006663 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006664
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006665 if (getLangOptions().CPlusPlus) {
6666 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6667 << SourceRange(BuiltinLoc, RPLoc);
6668 return ExprError();
6669 }
6670
Sebastian Redlf53597f2009-03-15 17:47:39 +00006671 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6672 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006673}
6674
Sebastian Redlf53597f2009-03-15 17:47:39 +00006675Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6676 ExprArg cond,
6677 ExprArg expr1, ExprArg expr2,
6678 SourceLocation RPLoc) {
6679 Expr *CondExpr = static_cast<Expr*>(cond.get());
6680 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6681 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006682
Steve Naroffd04fdd52007-08-03 21:21:27 +00006683 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6684
Sebastian Redl28507842009-02-26 14:39:58 +00006685 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006686 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006687 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006688 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006689 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006690 } else {
6691 // The conditional expression is required to be a constant expression.
6692 llvm::APSInt condEval(32);
6693 SourceLocation ExpLoc;
6694 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006695 return ExprError(Diag(ExpLoc,
6696 diag::err_typecheck_choose_expr_requires_constant)
6697 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006698
Sebastian Redl28507842009-02-26 14:39:58 +00006699 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6700 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006701 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6702 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006703 }
6704
Sebastian Redlf53597f2009-03-15 17:47:39 +00006705 cond.release(); expr1.release(); expr2.release();
6706 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006707 resType, RPLoc,
6708 resType->isDependentType(),
6709 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006710}
6711
Steve Naroff4eb206b2008-09-03 18:15:37 +00006712//===----------------------------------------------------------------------===//
6713// Clang Extensions.
6714//===----------------------------------------------------------------------===//
6715
6716/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006717void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006718 // Analyze block parameters.
6719 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006720
Steve Naroff4eb206b2008-09-03 18:15:37 +00006721 // Add BSI to CurBlock.
6722 BSI->PrevBlockInfo = CurBlock;
6723 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006724
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006725 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006726 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006727 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006728 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006729 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6730 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006731
Steve Naroff090276f2008-10-10 01:28:17 +00006732 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006733 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006734 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006735}
6736
Mike Stump98eb8a72009-02-04 22:31:32 +00006737void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006738 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006739
6740 if (ParamInfo.getNumTypeObjects() == 0
6741 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006742 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006743 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6744
Mike Stump4eeab842009-04-28 01:10:27 +00006745 if (T->isArrayType()) {
6746 Diag(ParamInfo.getSourceRange().getBegin(),
6747 diag::err_block_returns_array);
6748 return;
6749 }
6750
Mike Stump98eb8a72009-02-04 22:31:32 +00006751 // The parameter list is optional, if there was none, assume ().
6752 if (!T->isFunctionType())
6753 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6754
6755 CurBlock->hasPrototype = true;
6756 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006757 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006758 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006759 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006760 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006761 // FIXME: remove the attribute.
6762 }
John McCall183700f2009-09-21 23:43:11 +00006763 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006764
Chris Lattner9097af12009-04-11 19:27:54 +00006765 // Do not allow returning a objc interface by-value.
6766 if (RetTy->isObjCInterfaceType()) {
6767 Diag(ParamInfo.getSourceRange().getBegin(),
6768 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6769 return;
6770 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006771 return;
6772 }
6773
Steve Naroff4eb206b2008-09-03 18:15:37 +00006774 // Analyze arguments to block.
6775 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6776 "Not a function declarator!");
6777 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006778
Steve Naroff090276f2008-10-10 01:28:17 +00006779 CurBlock->hasPrototype = FTI.hasPrototype;
6780 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006781
Steve Naroff4eb206b2008-09-03 18:15:37 +00006782 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6783 // no arguments, not a function that takes a single void argument.
6784 if (FTI.hasPrototype &&
6785 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006786 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6787 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006788 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006789 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006790 } else if (FTI.hasPrototype) {
6791 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006792 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006793 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006794 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006795 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006796 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006797 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006798 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006799 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6800 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6801 // If this has an identifier, add it to the scope stack.
6802 if ((*AI)->getIdentifier())
6803 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006804
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006805 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006806 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006807 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006808 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006809 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006810 // FIXME: remove the attribute.
6811 }
Mike Stump1eb44332009-09-09 15:08:12 +00006812
Chris Lattner9097af12009-04-11 19:27:54 +00006813 // Analyze the return type.
6814 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006815 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006816
Chris Lattner9097af12009-04-11 19:27:54 +00006817 // Do not allow returning a objc interface by-value.
6818 if (RetTy->isObjCInterfaceType()) {
6819 Diag(ParamInfo.getSourceRange().getBegin(),
6820 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6821 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006822 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006823}
6824
6825/// ActOnBlockError - If there is an error parsing a block, this callback
6826/// is invoked to pop the information about the block from the action impl.
6827void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6828 // Ensure that CurBlock is deleted.
6829 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006830
Chris Lattner17a78302009-04-19 05:28:12 +00006831 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6832
Steve Naroff4eb206b2008-09-03 18:15:37 +00006833 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006834 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006835 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006836 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006837}
6838
6839/// ActOnBlockStmtExpr - This is called when the body of a block statement
6840/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006841Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6842 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006843 // If blocks are disabled, emit an error.
6844 if (!LangOpts.Blocks)
6845 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006846
Steve Naroff4eb206b2008-09-03 18:15:37 +00006847 // Ensure that CurBlock is deleted.
6848 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006849
Steve Naroff090276f2008-10-10 01:28:17 +00006850 PopDeclContext();
6851
Steve Naroff4eb206b2008-09-03 18:15:37 +00006852 // Pop off CurBlock, handle nested blocks.
6853 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006854
Steve Naroff4eb206b2008-09-03 18:15:37 +00006855 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006856 if (!BSI->ReturnType.isNull())
6857 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006858
Steve Naroff4eb206b2008-09-03 18:15:37 +00006859 llvm::SmallVector<QualType, 8> ArgTypes;
6860 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6861 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006862
Mike Stump56925862009-07-28 22:04:01 +00006863 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006864 QualType BlockTy;
6865 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006866 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6867 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006868 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006869 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006870 BSI->isVariadic, 0, false, false, 0, 0,
6871 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006872
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006873 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006874 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006875 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006876
Chris Lattner17a78302009-04-19 05:28:12 +00006877 // If needed, diagnose invalid gotos and switches in the block.
6878 if (CurFunctionNeedsScopeChecking)
6879 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6880 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006881
Anders Carlssone9146f22009-05-01 19:49:17 +00006882 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpfa6ef182010-01-13 02:59:54 +00006883 AnalysisContext AC(BSI->TheDecl);
6884 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6885 CheckUnreachable(AC);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006886 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6887 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006888}
6889
Sebastian Redlf53597f2009-03-15 17:47:39 +00006890Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6891 ExprArg expr, TypeTy *type,
6892 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006893 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006894 Expr *E = static_cast<Expr*>(expr.get());
6895 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006896
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006897 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006898
6899 // Get the va_list type
6900 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006901 if (VaListType->isArrayType()) {
6902 // Deal with implicit array decay; for example, on x86-64,
6903 // va_list is an array, but it's supposed to decay to
6904 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006905 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006906 // Make sure the input expression also decays appropriately.
6907 UsualUnaryConversions(E);
6908 } else {
6909 // Otherwise, the va_list argument must be an l-value because
6910 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006911 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006912 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006913 return ExprError();
6914 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006915
Douglas Gregordd027302009-05-19 23:10:31 +00006916 if (!E->isTypeDependent() &&
6917 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006918 return ExprError(Diag(E->getLocStart(),
6919 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006920 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006921 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006922
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006923 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006924 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006925
Sebastian Redlf53597f2009-03-15 17:47:39 +00006926 expr.release();
6927 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6928 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006929}
6930
Sebastian Redlf53597f2009-03-15 17:47:39 +00006931Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006932 // The type of __null will be int or long, depending on the size of
6933 // pointers on the target.
6934 QualType Ty;
6935 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6936 Ty = Context.IntTy;
6937 else
6938 Ty = Context.LongTy;
6939
Sebastian Redlf53597f2009-03-15 17:47:39 +00006940 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006941}
6942
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006943static void
6944MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6945 QualType DstType,
6946 Expr *SrcExpr,
6947 CodeModificationHint &Hint) {
6948 if (!SemaRef.getLangOptions().ObjC1)
6949 return;
6950
6951 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6952 if (!PT)
6953 return;
6954
6955 // Check if the destination is of type 'id'.
6956 if (!PT->isObjCIdType()) {
6957 // Check if the destination is the 'NSString' interface.
6958 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6959 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6960 return;
6961 }
6962
6963 // Strip off any parens and casts.
6964 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6965 if (!SL || SL->isWide())
6966 return;
6967
6968 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6969}
6970
Chris Lattner5cf216b2008-01-04 18:04:52 +00006971bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6972 SourceLocation Loc,
6973 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00006974 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00006975 // Decode the result (notice that AST's are still created for extensions).
6976 bool isInvalid = false;
6977 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006978 CodeModificationHint Hint;
6979
Chris Lattner5cf216b2008-01-04 18:04:52 +00006980 switch (ConvTy) {
6981 default: assert(0 && "Unknown conversion type");
6982 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006983 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006984 DiagKind = diag::ext_typecheck_convert_pointer_int;
6985 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006986 case IntToPointer:
6987 DiagKind = diag::ext_typecheck_convert_int_pointer;
6988 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006989 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006990 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006991 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6992 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006993 case IncompatiblePointerSign:
6994 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6995 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006996 case FunctionVoidPointer:
6997 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6998 break;
6999 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007000 // If the qualifiers lost were because we were applying the
7001 // (deprecated) C++ conversion from a string literal to a char*
7002 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7003 // Ideally, this check would be performed in
7004 // CheckPointerTypesForAssignment. However, that would require a
7005 // bit of refactoring (so that the second argument is an
7006 // expression, rather than a type), which should be done as part
7007 // of a larger effort to fix CheckPointerTypesForAssignment for
7008 // C++ semantics.
7009 if (getLangOptions().CPlusPlus &&
7010 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7011 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007012 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7013 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007014 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007015 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007016 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007017 case IntToBlockPointer:
7018 DiagKind = diag::err_int_to_block_pointer;
7019 break;
7020 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007021 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007022 break;
Steve Naroff39579072008-10-14 22:18:38 +00007023 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007024 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007025 // it can give a more specific diagnostic.
7026 DiagKind = diag::warn_incompatible_qualified_id;
7027 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007028 case IncompatibleVectors:
7029 DiagKind = diag::warn_incompatible_vectors;
7030 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007031 case Incompatible:
7032 DiagKind = diag::err_typecheck_convert_incompatible;
7033 isInvalid = true;
7034 break;
7035 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007036
Douglas Gregor68647482009-12-16 03:45:30 +00007037 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007038 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007039 return isInvalid;
7040}
Anders Carlssone21555e2008-11-30 19:50:32 +00007041
Chris Lattner3bf68932009-04-25 21:59:05 +00007042bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007043 llvm::APSInt ICEResult;
7044 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7045 if (Result)
7046 *Result = ICEResult;
7047 return false;
7048 }
7049
Anders Carlssone21555e2008-11-30 19:50:32 +00007050 Expr::EvalResult EvalResult;
7051
Mike Stumpeed9cac2009-02-19 03:04:26 +00007052 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007053 EvalResult.HasSideEffects) {
7054 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7055
7056 if (EvalResult.Diag) {
7057 // We only show the note if it's not the usual "invalid subexpression"
7058 // or if it's actually in a subexpression.
7059 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7060 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7061 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7062 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007063
Anders Carlssone21555e2008-11-30 19:50:32 +00007064 return true;
7065 }
7066
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007067 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7068 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007069
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007070 if (EvalResult.Diag &&
7071 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7072 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007073
Anders Carlssone21555e2008-11-30 19:50:32 +00007074 if (Result)
7075 *Result = EvalResult.Val.getInt();
7076 return false;
7077}
Douglas Gregore0762c92009-06-19 23:52:42 +00007078
Douglas Gregor2afce722009-11-26 00:44:06 +00007079void
Mike Stump1eb44332009-09-09 15:08:12 +00007080Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007081 ExprEvalContexts.push_back(
7082 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007083}
7084
Mike Stump1eb44332009-09-09 15:08:12 +00007085void
Douglas Gregor2afce722009-11-26 00:44:06 +00007086Sema::PopExpressionEvaluationContext() {
7087 // Pop the current expression evaluation context off the stack.
7088 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7089 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007090
Douglas Gregor06d33692009-12-12 07:57:52 +00007091 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7092 if (Rec.PotentiallyReferenced) {
7093 // Mark any remaining declarations in the current position of the stack
7094 // as "referenced". If they were not meant to be referenced, semantic
7095 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7096 for (PotentiallyReferencedDecls::iterator
7097 I = Rec.PotentiallyReferenced->begin(),
7098 IEnd = Rec.PotentiallyReferenced->end();
7099 I != IEnd; ++I)
7100 MarkDeclarationReferenced(I->first, I->second);
7101 }
7102
7103 if (Rec.PotentiallyDiagnosed) {
7104 // Emit any pending diagnostics.
7105 for (PotentiallyEmittedDiagnostics::iterator
7106 I = Rec.PotentiallyDiagnosed->begin(),
7107 IEnd = Rec.PotentiallyDiagnosed->end();
7108 I != IEnd; ++I)
7109 Diag(I->first, I->second);
7110 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007111 }
7112
7113 // When are coming out of an unevaluated context, clear out any
7114 // temporaries that we may have created as part of the evaluation of
7115 // the expression in that context: they aren't relevant because they
7116 // will never be constructed.
7117 if (Rec.Context == Unevaluated &&
7118 ExprTemporaries.size() > Rec.NumTemporaries)
7119 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7120 ExprTemporaries.end());
7121
7122 // Destroy the popped expression evaluation record.
7123 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007124}
Douglas Gregore0762c92009-06-19 23:52:42 +00007125
7126/// \brief Note that the given declaration was referenced in the source code.
7127///
7128/// This routine should be invoke whenever a given declaration is referenced
7129/// in the source code, and where that reference occurred. If this declaration
7130/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7131/// C99 6.9p3), then the declaration will be marked as used.
7132///
7133/// \param Loc the location where the declaration was referenced.
7134///
7135/// \param D the declaration that has been referenced by the source code.
7136void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7137 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007138
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007139 if (D->isUsed())
7140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007141
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007142 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7143 // template or not. The reason for this is that unevaluated expressions
7144 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7145 // -Wunused-parameters)
7146 if (isa<ParmVarDecl>(D) ||
7147 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007148 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007149
Douglas Gregore0762c92009-06-19 23:52:42 +00007150 // Do not mark anything as "used" within a dependent context; wait for
7151 // an instantiation.
7152 if (CurContext->isDependentContext())
7153 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007154
Douglas Gregor2afce722009-11-26 00:44:06 +00007155 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007156 case Unevaluated:
7157 // We are in an expression that is not potentially evaluated; do nothing.
7158 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007159
Douglas Gregorac7610d2009-06-22 20:57:11 +00007160 case PotentiallyEvaluated:
7161 // We are in a potentially-evaluated expression, so this declaration is
7162 // "used"; handle this below.
7163 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007164
Douglas Gregorac7610d2009-06-22 20:57:11 +00007165 case PotentiallyPotentiallyEvaluated:
7166 // We are in an expression that may be potentially evaluated; queue this
7167 // declaration reference until we know whether the expression is
7168 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007169 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007170 return;
7171 }
Mike Stump1eb44332009-09-09 15:08:12 +00007172
Douglas Gregore0762c92009-06-19 23:52:42 +00007173 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007174 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007175 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007176 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7177 if (!Constructor->isUsed())
7178 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007179 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007180 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007181 if (!Constructor->isUsed())
7182 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7183 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007184
7185 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007186 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7187 if (Destructor->isImplicit() && !Destructor->isUsed())
7188 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007189
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007190 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7191 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7192 MethodDecl->getOverloadedOperator() == OO_Equal) {
7193 if (!MethodDecl->isUsed())
7194 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7195 }
7196 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007197 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007198 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007199 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007200 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007201 bool AlreadyInstantiated = false;
7202 if (FunctionTemplateSpecializationInfo *SpecInfo
7203 = Function->getTemplateSpecializationInfo()) {
7204 if (SpecInfo->getPointOfInstantiation().isInvalid())
7205 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007206 else if (SpecInfo->getTemplateSpecializationKind()
7207 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007208 AlreadyInstantiated = true;
7209 } else if (MemberSpecializationInfo *MSInfo
7210 = Function->getMemberSpecializationInfo()) {
7211 if (MSInfo->getPointOfInstantiation().isInvalid())
7212 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007213 else if (MSInfo->getTemplateSpecializationKind()
7214 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007215 AlreadyInstantiated = true;
7216 }
7217
Douglas Gregor60406be2010-01-16 22:29:39 +00007218 if (!AlreadyInstantiated) {
7219 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7220 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7221 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7222 Loc));
7223 else
7224 PendingImplicitInstantiations.push_back(std::make_pair(Function,
7225 Loc));
7226 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007227 }
7228
Douglas Gregore0762c92009-06-19 23:52:42 +00007229 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007230 Function->setUsed(true);
7231 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007232 }
Mike Stump1eb44332009-09-09 15:08:12 +00007233
Douglas Gregore0762c92009-06-19 23:52:42 +00007234 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007235 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007236 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007237 Var->getInstantiatedFromStaticDataMember()) {
7238 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7239 assert(MSInfo && "Missing member specialization information?");
7240 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7241 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7242 MSInfo->setPointOfInstantiation(Loc);
7243 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7244 }
7245 }
Mike Stump1eb44332009-09-09 15:08:12 +00007246
Douglas Gregore0762c92009-06-19 23:52:42 +00007247 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007248
Douglas Gregore0762c92009-06-19 23:52:42 +00007249 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007250 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007251 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007252}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007253
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007254/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7255/// of the program being compiled.
7256///
7257/// This routine emits the given diagnostic when the code currently being
7258/// type-checked is "potentially evaluated", meaning that there is a
7259/// possibility that the code will actually be executable. Code in sizeof()
7260/// expressions, code used only during overload resolution, etc., are not
7261/// potentially evaluated. This routine will suppress such diagnostics or,
7262/// in the absolutely nutty case of potentially potentially evaluated
7263/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7264/// later.
7265///
7266/// This routine should be used for all diagnostics that describe the run-time
7267/// behavior of a program, such as passing a non-POD value through an ellipsis.
7268/// Failure to do so will likely result in spurious diagnostics or failures
7269/// during overload resolution or within sizeof/alignof/typeof/typeid.
7270bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7271 const PartialDiagnostic &PD) {
7272 switch (ExprEvalContexts.back().Context ) {
7273 case Unevaluated:
7274 // The argument will never be evaluated, so don't complain.
7275 break;
7276
7277 case PotentiallyEvaluated:
7278 Diag(Loc, PD);
7279 return true;
7280
7281 case PotentiallyPotentiallyEvaluated:
7282 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7283 break;
7284 }
7285
7286 return false;
7287}
7288
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007289bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7290 CallExpr *CE, FunctionDecl *FD) {
7291 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7292 return false;
7293
7294 PartialDiagnostic Note =
7295 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7296 << FD->getDeclName() : PDiag();
7297 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7298
7299 if (RequireCompleteType(Loc, ReturnType,
7300 FD ?
7301 PDiag(diag::err_call_function_incomplete_return)
7302 << CE->getSourceRange() << FD->getDeclName() :
7303 PDiag(diag::err_call_incomplete_return)
7304 << CE->getSourceRange(),
7305 std::make_pair(NoteLoc, Note)))
7306 return true;
7307
7308 return false;
7309}
7310
John McCall5a881bb2009-10-12 21:59:07 +00007311// Diagnose the common s/=/==/ typo. Note that adding parentheses
7312// will prevent this condition from triggering, which is what we want.
7313void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7314 SourceLocation Loc;
7315
John McCalla52ef082009-11-11 02:41:58 +00007316 unsigned diagnostic = diag::warn_condition_is_assignment;
7317
John McCall5a881bb2009-10-12 21:59:07 +00007318 if (isa<BinaryOperator>(E)) {
7319 BinaryOperator *Op = cast<BinaryOperator>(E);
7320 if (Op->getOpcode() != BinaryOperator::Assign)
7321 return;
7322
John McCallc8d8ac52009-11-12 00:06:05 +00007323 // Greylist some idioms by putting them into a warning subcategory.
7324 if (ObjCMessageExpr *ME
7325 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7326 Selector Sel = ME->getSelector();
7327
John McCallc8d8ac52009-11-12 00:06:05 +00007328 // self = [<foo> init...]
7329 if (isSelfExpr(Op->getLHS())
7330 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7331 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7332
7333 // <foo> = [<bar> nextObject]
7334 else if (Sel.isUnarySelector() &&
7335 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7336 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7337 }
John McCalla52ef082009-11-11 02:41:58 +00007338
John McCall5a881bb2009-10-12 21:59:07 +00007339 Loc = Op->getOperatorLoc();
7340 } else if (isa<CXXOperatorCallExpr>(E)) {
7341 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7342 if (Op->getOperator() != OO_Equal)
7343 return;
7344
7345 Loc = Op->getOperatorLoc();
7346 } else {
7347 // Not an assignment.
7348 return;
7349 }
7350
John McCall5a881bb2009-10-12 21:59:07 +00007351 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007352 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007353
John McCalla52ef082009-11-11 02:41:58 +00007354 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007355 << E->getSourceRange()
7356 << CodeModificationHint::CreateInsertion(Open, "(")
7357 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00007358 Diag(Loc, diag::note_condition_assign_to_comparison)
7359 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00007360}
7361
7362bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7363 DiagnoseAssignmentAsCondition(E);
7364
7365 if (!E->isTypeDependent()) {
7366 DefaultFunctionArrayConversion(E);
7367
7368 QualType T = E->getType();
7369
7370 if (getLangOptions().CPlusPlus) {
7371 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7372 return true;
7373 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7374 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7375 << T << E->getSourceRange();
7376 return true;
7377 }
7378 }
7379
7380 return false;
7381}