blob: eaf392116fdbe6c7506b4e87cd26ab69f842e88b [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Mike Stump1bacb812010-01-13 02:59:54 +000017#include "clang/Analysis/PathSensitive/AnalysisContext.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000032using namespace clang;
33
David Chisnall9f57c292009-08-17 16:35:33 +000034
Douglas Gregor171c45a2009-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 Lattnerb7df3c62009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor171c45a2009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000049///
John McCall28a6aea2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000054 }
55
Chris Lattnera27dd592009-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 Gregor171c45a2009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-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 Gregorde681d42009-02-24 04:26:15 +000069 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000070
Douglas Gregor171c45a2009-02-18 21:56:37 +000071 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-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 Stump11289f42009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000082 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000083 int sentinelPos = attr->getSentinel();
84 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000085
Mike Stump87c57ac2009-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 Jahanian9e877212009-05-13 23:20:50 +000088 unsigned int i = 0;
Fariborz Jahanian4a528032009-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 Stump12b8ce12009-08-04 21:02:39 +0000102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-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 Stump12b8ce12009-08-04 21:02:39 +0000112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000113 // block or function pointer call.
114 QualType Ty = V->getType();
115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000116 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-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 Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000133 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000134 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000135 return;
136
137 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-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 Jahanian4a528032009-05-14 18:00:00 +0000149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000150 return;
151 }
152 while (i < NumArgs-1) {
153 ++i;
154 ++sentinel;
155 }
156 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
158 (!sentinelExpr->getType()->isPointerType() ||
159 !sentinelExpr->isNullPointerConstant(Context,
160 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000161 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000163 }
164 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000165}
166
Douglas Gregor87f95b02009-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 Lattner513165e2008-07-25 21:10:04 +0000172//===----------------------------------------------------------------------===//
173// Standard Promotions and Conversions
174//===----------------------------------------------------------------------===//
175
Chris Lattner513165e2008-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 Lattner513165e2008-07-25 21:10:04 +0000181 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000182 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000183 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-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 Kyrtzidis9321c742008-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 Carlsson8fc489d2009-08-07 23:48:20 +0000198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
199 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000200 }
Chris Lattner513165e2008-07-25 21:10:04 +0000201}
202
203/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000204/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-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 Stump11289f42009-09-09 15:08:12 +0000211
Douglas Gregor8d9c5092009-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 Friedman629ffb92009-08-20 04:21:42 +0000225 QualType PTy = Context.isPromotableBitField(Expr);
226 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000227 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000228 return Expr;
229 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000230 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000231 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000232 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000233 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000234 }
235
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000236 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000237 return Expr;
238}
239
Chris Lattner2ce500f2008-07-25 22:25:12 +0000240/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000241/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-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 Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner2ce500f2008-07-25 22:25:12 +0000247 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000248 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000249 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000250 return ImpCastExprToType(Expr, Context.DoubleTy,
251 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000252
Chris Lattner2ce500f2008-07-25 22:25:12 +0000253 UsualUnaryConversions(Expr);
254}
255
Chris Lattnera8a7d0f2009-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 Carlssona7d069d2009-01-16 16:48:51 +0000261 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000262
Douglas Gregorda8cdbc2009-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 Gregor7ca84af2009-12-12 07:25:49 +0000268
Douglas Gregorda8cdbc2009-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 Lattnera8a7d0f2009-04-12 08:11:20 +0000274
275 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000276}
277
278
Chris Lattner513165e2008-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 Stump11289f42009-09-09 15:08:12 +0000281/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-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 Friedman8b7b1b12009-03-28 01:22:36 +0000287 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000288 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000289
290 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000291
Mike Stump11289f42009-09-09 15:08:12 +0000292 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000293 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000294 QualType lhs =
295 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000296 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000297 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-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 Gregord2c2d172009-05-02 00:36:19 +0000308 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000309 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000310 if (!LHSBitfieldPromoteTy.isNull())
311 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000312 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000313 if (!RHSBitfieldPromoteTy.isNull())
314 rhs = RHSBitfieldPromoteTy;
315
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000316 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000317 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000318 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
319 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000320 return destType;
321}
322
Chris Lattner513165e2008-07-25 21:10:04 +0000323//===----------------------------------------------------------------------===//
324// Semantic Analysis for various Expression Types
325//===----------------------------------------------------------------------===//
326
327
Steve Naroff83895f72007-09-16 03:34:24 +0000328/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +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 Redlffbcf962009-01-18 18:53:16 +0000333///
334Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000335Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000336 assert(NumStringToks && "Must have at least one string!");
337
Chris Lattner8a24e582009-01-16 18:51:42 +0000338 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000339 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000340 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000341
Chris Lattner23b7eb62007-06-15 23:05:46 +0000342 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000343 for (unsigned i = 0; i != NumStringToks; ++i)
344 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000345
Chris Lattner36fc8792008-02-11 00:02:17 +0000346 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000347 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000348 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-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 Redlffbcf962009-01-18 18:53:16 +0000353
Chris Lattner36fc8792008-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 Lattnerd42c29f2009-02-26 23:01:51 +0000358 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000359 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000360
Chris Lattner5b183d82006-11-10 05:03:26 +0000361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000362 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000363 Literal.GetStringLength(),
364 Literal.AnyWide, StrTy,
365 &StringTokLocs[0],
366 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000367}
368
Chris Lattner2a9d9892008-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 Lattner497d7b02009-04-21 22:26:47 +0000374/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
375/// up-to-date.
376///
Chris Lattner2a9d9892008-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 Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattner2a9d9892008-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 Lattner497d7b02009-04-21 22:26:47 +0000392 if (!Var->hasLocalStorage())
393 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattner497d7b02009-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 Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner497d7b02009-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 Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner2a9d9892008-10-20 05:16:36 +0000414 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000415}
416
Chris Lattner2a9d9892008-10-20 05:16:36 +0000417
418
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000419/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000420Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000421Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000422 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000423 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
424 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000425 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000426 << D->getDeclName();
427 return ExprError();
428 }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Anders Carlsson946b86d2009-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 Stump11289f42009-09-09 15:08:12 +0000434 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000435 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000436 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000437 << D->getIdentifier();
438 return ExprError();
439 }
440 }
441 }
442 }
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000444 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000445
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000446 return Owned(DeclRefExpr::Create(Context,
447 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
448 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000449 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000450}
451
Douglas Gregor9ac7a072009-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 Gregorbcced4e2009-04-09 21:40:53 +0000455static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
456 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000457 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000458 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000459
Mike Stump87c57ac2009-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 Gregor9ac7a072009-01-07 00:43:41 +0000463 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000464 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000465 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-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 Gregor6e6ad602009-01-20 01:17:11 +0000472 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-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 Gregord5846a12009-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 Gregor9ac7a072009-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 Gregord5846a12009-04-15 06:41:24 +0000500 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000501 VarDecl *BaseObject = 0;
502 DeclContext *Ctx = Field->getDeclContext();
503 do {
504 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000505 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000506 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000507 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000508 else {
509 BaseObject = cast<VarDecl>(AnonObject);
510 break;
511 }
512 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000513 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000514 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-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 Stump11289f42009-09-09 15:08:12 +0000525 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000526 AnonFields);
527
Douglas Gregor9ac7a072009-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 McCall8ccfcb52009-09-24 19:53:00 +0000533 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-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 Kremenek5a201952009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000538 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000539 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000540 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000541 BaseQuals
542 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-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 Kremenekc23c7e62009-07-29 21:53:49 +0000548 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000549 BaseObjectIsPointer = true;
550 ObjectType = ObjectPtr->getPointeeType();
551 }
John McCall8ccfcb52009-09-24 19:53:00 +0000552 BaseQuals
553 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-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 Stump11289f42009-09-09 15:08:12 +0000560 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000561 = Context.getTagDeclType(
562 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
563 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000564 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000565 == Context.getCanonicalType(ThisType)) ||
566 IsDerivedFrom(ThisType, AnonFieldType)) {
567 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000568 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000569 MD->getThisType(Context),
570 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 }
573 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000574 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
575 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 }
John McCall8ccfcb52009-09-24 19:53:00 +0000577 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000578 }
579
Mike Stump11289f42009-09-09 15:08:12 +0000580 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000581 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
582 << Field->getDeclName());
Douglas Gregor9ac7a072009-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 McCall8ccfcb52009-09-24 19:53:00 +0000588 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-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 McCall8ccfcb52009-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 Gregorc9c02ed2009-06-19 23:52:42 +0000611 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000612 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000613 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000614 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
615 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000616 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000617 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000618 }
619
Sebastian Redlffbcf962009-01-18 18:53:16 +0000620 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000621}
622
John McCall10eae182009-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 McCalle66edc12009-11-24 19:00:30 +0000671 if (TemplateDecl *TD = TName.getAsTemplateDecl())
672 R.addDecl(TD);
John McCalld28ae272009-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 McCalle66edc12009-11-24 19:00:30 +0000676 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000677
John McCalle66edc12009-11-24 19:00:30 +0000678 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000679}
680
John McCall10eae182009-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 McCallf786fb12009-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 McCall10eae182009-11-30 22:42:35 +0000700 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000701
John McCallf786fb12009-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 McCall2d74de92009-12-01 22:10:20 +0000711 return false;
712}
John McCallf786fb12009-11-30 23:50:49 +0000713
John McCall2d74de92009-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 McCalla6d407c2009-12-01 22:28:41 +0000719 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000720 return false;
721
John McCalla6d407c2009-12-01 22:28:41 +0000722 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
723 if (!RD) return false;
724 Record = cast<CXXRecordDecl>(RD);
725
John McCall2d74de92009-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 McCall2d74de92009-12-01 22:10:20 +0000733 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
734 return false;
735 }
736
737 return true;
738}
739
John McCall5af04502009-12-02 20:26:00 +0000740/// Determines if this is an instance member of a class.
741static bool IsInstanceMember(NamedDecl *D) {
John McCall57500772009-12-16 12:17:52 +0000742 assert(D->isCXXClassMember() &&
John McCall2d74de92009-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 McCall57500772009-12-16 12:17:52 +0000804 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-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 McCall10eae182009-11-30 22:42:35 +0000879}
880
John McCalld681c392009-12-16 08:11:27 +0000881/// Diagnose an empty lookup.
882///
883/// \return false if new lookup candidates were found
Douglas Gregor598b08f2009-12-31 05:20:13 +0000884bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCalld681c392009-12-16 08:11:27 +0000885 LookupResult &R) {
886 DeclarationName Name = R.getLookupName();
887
John McCalld681c392009-12-16 08:11:27 +0000888 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000889 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000890 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
891 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000892 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000893 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000894 diagnostic_suggest = diag::err_undeclared_use_suggest;
895 }
John McCalld681c392009-12-16 08:11:27 +0000896
Douglas Gregor598b08f2009-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 McCalld681c392009-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 Gregor598b08f2009-12-31 05:20:13 +0000935 // We didn't find anything, so try to correct for a typo.
Douglas Gregor25363982010-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 Gregor598b08f2009-12-31 05:20:13 +0000941 R.getLookupName().getAsString());
Douglas Gregor25363982010-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 Gregor598b08f2009-12-31 05:20:13 +0000947 R.getLookupName().getAsString());
Douglas Gregor6da83622010-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 Gregor25363982010-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 Gregor598b08f2009-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 McCalld681c392009-12-16 08:11:27 +0000985 // Give up, we can't recover.
986 Diag(R.getNameLoc(), diagnostic) << Name;
987 return true;
988}
989
John McCalle66edc12009-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 Gregored8f2882009-01-30 01:04:22 +0000999 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001000
John McCall10eae182009-11-30 22:42:35 +00001001 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-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 McCall10eae182009-11-30 22:42:35 +00001007 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1008 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001009
Douglas Gregor4ea80432008-11-18 15:03:34 +00001010 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +00001011
John McCalle66edc12009-11-24 19:00:30 +00001012 // C++ [temp.dep.expr]p3:
1013 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-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 McCalle66edc12009-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 Gregorea0a0a92010-01-11 18:40:55 +00001023 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1024 Name.getCXXNameType()->isDependentType()) ||
1025 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCalle66edc12009-11-24 19:00:30 +00001026 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001027 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001028 TemplateArgs);
1029 }
John McCalld14a8642009-11-21 08:51:07 +00001030
John McCalle66edc12009-11-24 19:00:30 +00001031 // Perform the required lookup.
1032 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1033 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001034 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001035 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001036 } else {
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001037 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1038 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001039
John McCalle66edc12009-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 Jahanian6fada5b2010-01-12 23:58:59 +00001042 if (IvarLookupFollowUp) {
1043 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001044 if (E.isInvalid())
1045 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001046
John McCalle66edc12009-11-24 19:00:30 +00001047 Expr *Ex = E.takeAs<Expr>();
1048 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001049 }
Chris Lattner59a25942008-03-31 00:36:02 +00001050 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001051
John McCalle66edc12009-11-24 19:00:30 +00001052 if (R.isAmbiguous())
1053 return ExprError();
1054
Douglas Gregor171c45a2009-02-18 21:56:37 +00001055 // Determine whether this name might be a candidate for
1056 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001057 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001058
John McCalle66edc12009-11-24 19:00:30 +00001059 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001060 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-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 Gregor598b08f2009-12-31 05:20:13 +00001070 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001071 return ExprError();
1072
1073 assert(!R.empty() &&
1074 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-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 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001085 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001086 }
Mike Stump11289f42009-09-09 15:08:12 +00001087
John McCalle66edc12009-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 Gregor3256d042009-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 Stump11289f42009-09-09 15:08:12 +00001095
Douglas Gregor3256d042009-06-30 15:47:41 +00001096 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1097 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001098 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001099 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001100 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001101 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001102 << Var->getDeclName()
1103 << (Var->getType()->isPointerType()? 2 :
1104 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001105 break;
1106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregor13a2c032009-11-05 17:49:26 +00001108 // Move to the parent of this scope.
1109 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001110 }
1111 }
John McCalle66edc12009-11-24 19:00:30 +00001112 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-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 McCalle66edc12009-11-24 19:00:30 +00001119 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001120 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001121
Douglas Gregor3256d042009-06-30 15:47:41 +00001122 QualType T = Func->getType();
1123 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001124 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001125 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001126 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001127 }
1128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
John McCall2d74de92009-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 McCall57500772009-12-16 12:17:52 +00001137 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001138 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001139 if (!isAbstractMemberPointer)
1140 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001141 }
1142
John McCalle66edc12009-11-24 19:00:30 +00001143 if (TemplateArgs)
1144 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001145
John McCalle66edc12009-11-24 19:00:30 +00001146 return BuildDeclarationNameExpr(SS, R, ADL);
1147}
1148
John McCall57500772009-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 McCall10eae182009-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 McCalle66edc12009-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 Jahanian6fada5b2010-01-12 23:58:59 +00001223 IdentifierInfo *II,
1224 bool AllowBuiltinCreation) {
John McCalle66edc12009-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 Jahanian6fada5b2010-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 McCalle66edc12009-11-24 19:00:30 +00001317 // Sentinel value saying that we didn't do anything special.
1318 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001319}
John McCalld14a8642009-11-21 08:51:07 +00001320
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001321/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001322bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001323Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1324 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001325 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001326 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001327 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001328 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-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 Kremenekc23c7e62009-07-29 21:53:49 +00001333 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001334 DestType = Context.getPointerType(DestType);
1335 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001336 }
Fariborz Jahanian4b12ed12009-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 Carlssona076d142009-07-31 01:23:52 +00001343 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1344 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001345 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001346 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001347}
Douglas Gregor3256d042009-06-30 15:47:41 +00001348
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001349/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001350static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001351 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001352 SourceLocation Loc, QualType Ty,
1353 const TemplateArgumentListInfo *TemplateArgs = 0) {
1354 NestedNameSpecifier *Qualifier = 0;
1355 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001356 if (SS.isSet()) {
1357 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1358 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
John McCalle66edc12009-11-24 19:00:30 +00001361 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1362 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001363}
1364
John McCall2d74de92009-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 McCallb53bbd42009-11-22 01:44:31 +00001369Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001370Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1371 LookupResult &R,
1372 const TemplateArgumentListInfo *TemplateArgs,
1373 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001374 assert(!R.empty() && !R.isAmbiguous());
1375
John McCalld14a8642009-11-21 08:51:07 +00001376 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001377
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001378 // We may have found a field within an anonymous union or struct
1379 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001380 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001381 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001382 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001383 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001384 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001385
John McCall2d74de92009-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 Gregorb15af892010-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 Gregor97fd6e22008-12-22 05:46:06 +00001395 }
1396
John McCall2d74de92009-12-01 22:10:20 +00001397 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1398 /*OpLoc*/ SourceLocation(),
1399 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001400 SS,
1401 /*FirstQualifierInScope*/ 0,
1402 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001403}
1404
John McCalle66edc12009-11-24 19:00:30 +00001405bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001406 const LookupResult &R,
1407 bool HasTrailingLParen) {
John McCalld14a8642009-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 McCalle66edc12009-11-24 19:00:30 +00001413 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001414 return false;
1415
1416 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001417 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-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 McCall57500772009-12-16 12:17:52 +00001429 if (D->isCXXClassMember())
John McCalld14a8642009-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 McCalld14a8642009-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 McCalle66edc12009-11-24 19:00:30 +00001485Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001486 LookupResult &R,
1487 bool NeedsADL) {
John McCall3a60c872009-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 McCallb53bbd42009-11-22 01:44:31 +00001491 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-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 McCallb53bbd42009-11-22 01:44:31 +00001496 if (R.isSingleResult() &&
1497 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001498 return ExprError();
1499
John McCalle66edc12009-11-24 19:00:30 +00001500 bool Dependent
1501 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001502 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001503 = UnresolvedLookupExpr::Create(Context, Dependent,
1504 (NestedNameSpecifier*) SS.getScopeRep(),
1505 SS.getRange(),
John McCallb53bbd42009-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 McCalld14a8642009-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 McCalle66edc12009-11-24 19:00:30 +00001517Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001518 SourceLocation Loc, NamedDecl *D) {
1519 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001520 assert(!isa<FunctionTemplateDecl>(D) &&
1521 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001522
1523 if (CheckDeclInExpr(*this, Loc, D))
1524 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001525
Douglas Gregore7488b92009-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 McCallb48971d2009-12-18 18:35:10 +00001540 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001541 return ExprError();
1542 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001543
Douglas Gregor171c45a2009-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 McCalld14a8642009-11-21 08:51:07 +00001548 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001549 return ExprError();
1550
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001551 // Only create DeclRefExpr's for valid Decl's.
1552 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001553 return ExprError();
1554
Chris Lattner2a9d9892008-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 Naroff8de9c3a2008-09-05 22:11:13 +00001559 //
Chris Lattner2a9d9892008-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 Stump7dafa0d2010-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 Stump8971a862010-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 Gregorc9c02ed2009-06-19 23:52:42 +00001576 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001577 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001578 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001579 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001580 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001581 // This is to record that a 'const' was actually synthesize and added.
1582 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001583 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001584
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001585 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001586 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001587 constAdded));
Steve Naroff1d95e5a2008-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 Gregor4619e432008-12-05 23:32:09 +00001591
John McCalle66edc12009-11-24 19:00:30 +00001592 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001593}
Chris Lattnere168f762006-11-10 05:29:30 +00001594
Sebastian Redlffbcf962009-01-18 18:53:16 +00001595Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1596 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001597 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001598
Chris Lattnere168f762006-11-10 05:29:30 +00001599 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001600 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-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;
Chris Lattnere168f762006-11-10 05:29:30 +00001604 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001605
Chris Lattnera81a0272008-01-12 08:14:25 +00001606 // Pre-defined identifiers are of type char[x], where x is the length of the
1607 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001608
Anders Carlsson2fb08242009-09-08 18:24:21 +00001609 Decl *currentDecl = getCurFunctionOrMethodDecl();
1610 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001611 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001612 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001613 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001614
Anders Carlsson0b209a82009-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 Redlffbcf962009-01-18 18:53:16 +00001621
Anders Carlsson0b209a82009-09-11 01:22:35 +00001622 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001623 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001624 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1625 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001626 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001627}
1628
Sebastian Redlffbcf962009-01-18 18:53:16 +00001629Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001630 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001631 CharBuffer.resize(Tok.getLength());
1632 const char *ThisTokBegin = &CharBuffer[0];
1633 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001634
Steve Naroffae4143e2007-04-26 20:39:23 +00001635 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1636 Tok.getLocation(), PP);
1637 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001638 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001639
Chris Lattnerc3847ba2009-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 Lattneref24b382008-03-01 08:32:21 +00001647
Sebastian Redl20614a72009-01-20 22:23:13 +00001648 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1649 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001650 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001651}
1652
Sebastian Redlffbcf962009-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
Steve Narofff2fb89e2007-03-13 20:29:44 +00001655 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1656 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001657 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001658 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001659 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001660 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001661 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001662
Chris Lattner23b7eb62007-06-15 23:05:46 +00001663 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001664 // Add padding so that NumericLiteralParser can overread by one character.
1665 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001666 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001667
Chris Lattner67ca9252007-05-21 01:08:44 +00001668 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001669 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001670
Mike Stump11289f42009-09-09 15:08:12 +00001671 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001672 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001673 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001674 return ExprError();
1675
Chris Lattner1c20a172007-08-26 03:42:43 +00001676 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001677
Chris Lattner1c20a172007-08-26 03:42:43 +00001678 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001679 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001680 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001681 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001682 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001683 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001684 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001685 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001686
1687 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1688
John McCall53b93a02009-12-24 09:08:04 +00001689 using llvm::APFloat;
1690 APFloat Val(Format);
1691
1692 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-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 McCall53b93a02009-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 Lattnere4edb8e2009-06-29 17:34:55 +00001714 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001715
Chris Lattner1c20a172007-08-26 03:42:43 +00001716 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001717 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001718 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001719 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001720
Neil Boothac582c52007-08-29 22:00:19 +00001721 // long long is a C99 feature.
1722 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001723 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001724 Diag(Tok.getLocation(), diag::ext_longlong);
1725
Chris Lattner67ca9252007-05-21 01:08:44 +00001726 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001727 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001728
Chris Lattner67ca9252007-05-21 01:08:44 +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 Lattner24d5bfe2008-04-02 04:24:33 +00001732 Ty = Context.UnsignedLongLongTy;
1733 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001734 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001735 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001736 // 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 Redlffbcf962009-01-18 18:53:16 +00001738
Chris Lattner67ca9252007-05-21 01:08:44 +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 Lattner55258cf2008-05-09 05:59:00 +00001744 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001745 if (!Literal.isLong && !Literal.isLongLong) {
1746 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001747 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001748
Chris Lattner67ca9252007-05-21 01:08:44 +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 Lattner24d5bfe2008-04-02 04:24:33 +00001753 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001754 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001755 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001756 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001757 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001758 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001759
Chris Lattner67ca9252007-05-21 01:08:44 +00001760 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001761 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001762 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001763
Chris Lattner67ca9252007-05-21 01:08:44 +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 Lattner24d5bfe2008-04-02 04:24:33 +00001768 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001769 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001770 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001771 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001772 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001773 }
1774
Chris Lattner67ca9252007-05-21 01:08:44 +00001775 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001776 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001777 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001778
Chris Lattner67ca9252007-05-21 01:08:44 +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 Lattner24d5bfe2008-04-02 04:24:33 +00001783 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001784 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001785 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001786 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001787 }
1788 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001789
Chris Lattner67ca9252007-05-21 01:08:44 +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 Lattner24d5bfe2008-04-02 04:24:33 +00001792 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001793 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001794 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001795 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001796 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001797
Chris Lattner55258cf2008-05-09 05:59:00 +00001798 if (ResultVal.getBitWidth() != Width)
1799 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001800 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001801 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001802 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001803
Chris Lattner1c20a172007-08-26 03:42:43 +00001804 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1805 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001806 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001807 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001808
1809 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001810}
1811
Sebastian Redlffbcf962009-01-18 18:53:16 +00001812Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1813 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001814 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001815 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001816 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001817}
1818
Steve Naroff71b59a92007-06-04 22:22:31 +00001819/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001820/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001821bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001822 SourceLocation OpLoc,
1823 const SourceRange &ExprRange,
1824 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001825 if (exprType->isDependentType())
1826 return false;
1827
Sebastian Redl22e2e5c2009-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
Steve Naroff043d45d2007-05-15 02:32:35 +00001835 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001836 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001837 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001838 if (isSizeof)
1839 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1840 return false;
1841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Chris Lattner62975a72009-04-24 00:30:45 +00001843 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001844 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001845 Diag(OpLoc, diag::ext_sizeof_void_type)
1846 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001847 return false;
1848 }
Mike Stump11289f42009-09-09 15:08:12 +00001849
Chris Lattner62975a72009-04-24 00:30:45 +00001850 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001851 PDiag(diag::err_sizeof_alignof_incomplete_type)
1852 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001853 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001854
Chris Lattner62975a72009-04-24 00:30:45 +00001855 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001856 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001857 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001858 << exprType << isSizeof << ExprRange;
1859 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattner62975a72009-04-24 00:30:45 +00001862 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001863}
1864
Chris Lattner8dff0172009-01-24 20:17:12 +00001865bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1866 const SourceRange &ExprRange) {
1867 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001868
Mike Stump11289f42009-09-09 15:08:12 +00001869 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001870 if (isa<DeclRefExpr>(E))
1871 return false;
Sebastian Redl8d2ccae2009-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 Gregor71235ec2009-05-02 02:18:30 +00001877 if (E->getBitField()) {
1878 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1879 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001880 }
Douglas Gregor71235ec2009-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 Stump212005c2009-07-22 18:58:19 +00001885 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001886 return false;
1887
Chris Lattner8dff0172009-01-24 20:17:12 +00001888 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1889}
1890
Douglas Gregor0950e412009-03-13 21:01:28 +00001891/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001892Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001893Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001894 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001895 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001896 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001897 return ExprError();
1898
John McCallbcd03502009-12-07 02:54:59 +00001899 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001900
Douglas Gregor0950e412009-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 McCallbcd03502009-12-07 02:54:59 +00001906 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-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 Stump11289f42009-09-09 15:08:12 +00001913Action::OwningExprResult
1914Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-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 Gregor71235ec2009-05-02 02:18:30 +00001922 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-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 Redl6f282892008-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 Redlc215cfc2009-01-19 00:08:26 +00001941Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001942Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1943 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001944 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001945 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001946
Sebastian Redl6f282892008-11-11 17:56:53 +00001947 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001948 TypeSourceInfo *TInfo;
1949 (void) GetTypeFromParser(TyOrEx, &TInfo);
1950 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001951 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001952
Douglas Gregor0950e412009-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);
Chris Lattnere168f762006-11-10 05:29:30 +00001961}
1962
Chris Lattner709322b2009-02-17 08:12:06 +00001963QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001964 if (V->isTypeDependent())
1965 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001966
Chris Lattnere267f5d2007-08-26 05:39:26 +00001967 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001968 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001969 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattnere267f5d2007-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 Stump11289f42009-09-09 15:08:12 +00001974
Chris Lattnere267f5d2007-08-26 05:39:26 +00001975 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001976 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1977 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001978 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001979}
1980
1981
Chris Lattnere168f762006-11-10 05:29:30 +00001982
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001983Action::OwningExprResult
1984Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1985 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +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 Redlc215cfc2009-01-19 00:08:26 +00001992
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001993 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001994}
1995
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001996Action::OwningExprResult
1997Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1998 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-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 Redlc215cfc2009-01-19 00:08:26 +00002002 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2003 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00002004
Douglas Gregor40412ac2008-11-19 17:17:41 +00002005 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-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 Stump11289f42009-09-09 15:08:12 +00002013 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002014 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002015 LHSExp->getType()->isEnumeralType() ||
2016 RHSExp->getType()->isRecordType() ||
2017 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00002018 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00002019 }
2020
Sebastian Redladba46e2009-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 Lattner36d572b2007-07-16 00:14:47 +00002031 // Perform default conversions.
2032 DefaultFunctionArrayConversion(LHSExp);
2033 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002034
Chris Lattner36d572b2007-07-16 00:14:47 +00002035 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002036
Steve Naroffc1aadb12007-03-28 21:49:40 +00002037 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002038 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002039 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002040 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002041 Expr *BaseExpr, *IndexExpr;
2042 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002043 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2044 BaseExpr = LHSExp;
2045 IndexExpr = RHSExp;
2046 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002047 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002048 BaseExpr = LHSExp;
2049 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002050 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002051 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002052 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002053 BaseExpr = RHSExp;
2054 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002055 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002056 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002057 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002058 BaseExpr = LHSExp;
2059 IndexExpr = RHSExp;
2060 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002061 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002062 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002063 // Handle the uncommon case of "123[Ptr]".
2064 BaseExpr = RHSExp;
2065 IndexExpr = LHSExp;
2066 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002067 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002068 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002069 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002070
Chris Lattner36d572b2007-07-16 00:14:47 +00002071 // FIXME: need to deal with const...
2072 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-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 Friedman06ed2a52009-10-20 08:27:19 +00002081 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2082 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002083 LHSTy = LHSExp->getType();
2084
2085 BaseExpr = LHSExp;
2086 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002087 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-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 Friedman06ed2a52009-10-20 08:27:19 +00002092 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2093 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002094 RHSTy = RHSExp->getType();
2095
2096 BaseExpr = RHSExp;
2097 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002098 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002099 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002100 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2101 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002102 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002103 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002104 if (!(IndexExpr->getType()->isIntegerType() &&
2105 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002106 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2107 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002108
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002109 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002110 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2111 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002112 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2113
Douglas Gregorac1fb652009-03-24 19:52:54 +00002114 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-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 Gregorac1fb652009-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 Stump11289f42009-09-09 15:08:12 +00002123
Douglas Gregorac1fb652009-03-24 19:52:54 +00002124 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002125 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002126 PDiag(diag::err_subscript_incomplete_type)
2127 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002128 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattner62975a72009-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 Stump11289f42009-09-09 15:08:12 +00002136
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002137 Base.release();
2138 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002139 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002140 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002141}
2142
Steve Narofff8fd09e2007-07-27 22:15:19 +00002143QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002144CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002145 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002146 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-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 McCall9dd450b2009-09-21 23:43:11 +00002152 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002153
Steve Narofff8fd09e2007-07-27 22:15:19 +00002154 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002155 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002156
Mike Stump4e1f26a2009-02-19 03:04:26 +00002157 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-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 Stump4e1f26a2009-02-19 03:04:26 +00002161
Nate Begemanbb70bf62009-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 Begeman0359e122009-06-25 21:06:09 +00002164 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-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 Stump4e1f26a2009-02-19 03:04:26 +00002168 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002169 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2170 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002171 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002172 do
2173 compStr++;
2174 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002175 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002176 do
2177 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002178 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002179 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002180
Mike Stump4e1f26a2009-02-19 03:04:26 +00002181 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-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 Lattner3b054132008-11-19 05:08:23 +00002184 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2185 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002186 return QualType();
2187 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002188
Nate Begemanbb70bf62009-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 Dunbar2c422dc92009-10-18 20:26:12 +00002192 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002193
2194 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002195 compStr++;
Nate Begemanbb70bf62009-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 Narofff8fd09e2007-07-27 22:15:19 +00002204 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002205
Steve Narofff8fd09e2007-07-27 22:15:19 +00002206 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002207 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002208 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002209 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002210 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002211 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002212 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002213 if (HexSwizzle)
2214 CompSize--;
2215
Steve Narofff8fd09e2007-07-27 22:15:19 +00002216 if (CompSize == 1)
2217 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002218
Nate Begemance4d7fc2008-04-18 23:10:10 +00002219 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002220 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-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 Naroffddf5a1d2007-07-29 16:33:31 +00002225 }
2226 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002227}
2228
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002229static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002230 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002231 const Selector &Sel,
2232 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002233
Anders Carlssonf571c112009-08-26 18:25:21 +00002234 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002235 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002236 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002237 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002238
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002239 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2240 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002241 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002242 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002243 return D;
2244 }
2245 return 0;
2246}
2247
Steve Narofffb4330f2009-06-17 22:40:22 +00002248static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002249 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002250 const Selector &Sel,
2251 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002252 // Check protocols on qualified interfaces.
2253 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002254 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002255 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002256 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002257 GDecl = PD;
2258 break;
2259 }
2260 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002261 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002262 GDecl = OMD;
2263 break;
2264 }
2265 }
2266 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002267 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002268 E = QIdTy->qual_end(); I != E; ++I) {
2269 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002270 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002271 if (GDecl)
2272 return GDecl;
2273 }
2274 }
2275 return GDecl;
2276}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002277
John McCall10eae182009-11-30 22:42:35 +00002278Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002279Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2280 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-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 McCall2d74de92009-12-01 22:10:20 +00002297 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002298 if (PT && (!getLangOptions().ObjC1 ||
2299 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002300 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002301 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002302 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002303 return ExprError();
2304 }
2305 }
2306
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002307 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall10eae182009-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 McCall2d74de92009-12-01 22:10:20 +00002311 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-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 McCallcd4b4772009-12-02 03:53:29 +00002326 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002327 const LookupResult &R) {
John McCallcd4b4772009-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 McCall10eae182009-11-30 22:42:35 +00002332
2333 // FIXME: this is an exceedingly lame diagnostic for some of the more
2334 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002335 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002336 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002337 << SS.getRange() << DC << BaseType;
John McCall10eae182009-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 McCallcd4b4772009-12-02 03:53:29 +00002354 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002355 const LookupResult &R) {
John McCall2d74de92009-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 McCall10eae182009-11-30 22:42:35 +00002364
2365 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-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 McCall10eae182009-11-30 22:42:35 +00002370
John McCall2d74de92009-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 McCallcd4b4772009-12-02 03:53:29 +00002383 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-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 McCallcd4b4772009-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 McCall2d74de92009-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 McCall10eae182009-11-30 22:42:35 +00002415 }
2416 }
2417
John McCall2d74de92009-12-01 22:10:20 +00002418 // The record definition is complete, now look up the member.
2419 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002420
Douglas Gregoraf2bd472009-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 Gregor6da83622010-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 Gregoraf2bd472009-12-31 07:42:17 +00002436 return false;
2437 } else {
2438 R.clear();
2439 }
2440
John McCall10eae182009-11-30 22:42:35 +00002441 return false;
2442}
2443
2444Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002445Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-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 McCallcd4b4772009-12-02 03:53:29 +00002453 if (BaseType->isDependentType() ||
2454 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002455 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-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 McCall10eae182009-11-30 22:42:35 +00002462
John McCall2d74de92009-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 McCall38836f02010-01-15 08:34:02 +00002476 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCall2d74de92009-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 McCall10eae182009-11-30 22:42:35 +00002485 }
2486
John McCall2d74de92009-12-01 22:10:20 +00002487 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCall38836f02010-01-15 08:34:02 +00002488 OpLoc, IsArrow, SS, FirstQualifierInScope,
2489 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002490}
2491
2492Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002493Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2494 SourceLocation OpLoc, bool IsArrow,
2495 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002496 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002497 LookupResult &R,
2498 const TemplateArgumentListInfo *TemplateArgs) {
2499 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002500 QualType BaseType = BaseExprType;
John McCall10eae182009-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 Gregord8061562009-08-06 03:17:00 +00002512 return ExprError();
2513
John McCall10eae182009-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 Begeman5ec4b312009-08-10 23:49:36 +00002519
John McCall10eae182009-11-30 22:42:35 +00002520 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002521 << MemberName << DC
2522 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002523 return ExprError();
2524 }
2525
John McCall38836f02010-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 McCall10eae182009-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 McCall2d74de92009-12-01 22:10:20 +00002542 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002543 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002544 R.isUnresolvableResult() ||
2545 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002546
2547 UnresolvedMemberExpr *MemExpr
2548 = UnresolvedMemberExpr::Create(Context, Dependent,
2549 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002550 BaseExpr, BaseExprType,
2551 IsArrow, OpLoc,
John McCall10eae182009-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 McCall2d74de92009-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 Gregorb15af892010-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 McCall2d74de92009-12-01 22:10:20 +00002582 }
2583
John McCall10eae182009-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 Friedman78cde142009-12-04 07:18:51 +00002601 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2602 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-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 McCalla928c652009-12-07 22:46:59 +00002676 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002677 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002678 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002679 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002680
Steve Naroffeaaae462007-12-16 21:42:28 +00002681 // Perform default conversions.
2682 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002683
Steve Naroff185616f2007-07-26 03:11:44 +00002684 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002685 assert(!BaseType->isDependentType());
2686
2687 DeclarationName MemberName = R.getLookupName();
2688 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002689
2690 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002691 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-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 McCall10eae182009-11-30 22:42:35 +00002699 ((!IsArrow && ResultTy->isRecordType()) ||
2700 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-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 McCall10eae182009-11-30 22:42:35 +00002709 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002710 MultiExprArg(*this, 0, 0), 0, Loc);
2711 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002712 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002713
2714 BaseExpr = NewBase.takeAs<Expr>();
2715 DefaultFunctionArrayConversion(BaseExpr);
2716 BaseType = BaseExpr->getType();
2717 }
2718 }
2719 }
2720
David Chisnall9f57c292009-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 Jahanianc2949f92009-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 Jahaniana5fee262009-12-09 19:05:56 +00002730 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2731 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002732 }
2733 }
David Chisnall9f57c292009-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 Friedman06ed2a52009-10-20 08:27:19 +00002738 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002739 }
David Chisnall9f57c292009-08-17 16:35:33 +00002740 }
John McCall10eae182009-11-30 22:42:35 +00002741
Fariborz Jahanian04b258c2009-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 McCall10eae182009-11-30 22:42:35 +00002752
Steve Naroff185616f2007-07-26 03:11:44 +00002753 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002754
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002755 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002756 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-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 Naroffbb69c942009-10-01 23:46:04 +00002778 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-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 Friedman06ed2a52009-10-20 08:27:19 +00002808 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002809 }
Mike Stump11289f42009-09-09 15:08:12 +00002810
John McCall10eae182009-11-30 22:42:35 +00002811 if (IsArrow) {
2812 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002813 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002814 else if (BaseType->isObjCObjectPointerType())
2815 ;
John McCalla928c652009-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 McCall10eae182009-11-30 22:42:35 +00002828 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2829 << BaseType << BaseExpr->getSourceRange();
2830 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002831 }
John McCalla928c652009-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 McCall10eae182009-11-30 22:42:35 +00002850 }
John McCalla928c652009-12-07 22:46:59 +00002851
John McCall10eae182009-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 Kremenekc23c7e62009-07-29 21:53:49 +00002854 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002855 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2856 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002857 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002858 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002859 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002860
Douglas Gregorad8a3362009-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 Stump11289f42009-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 Gregorad8a3362009-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 Stump11289f42009-09-09 15:08:12 +00002872
Douglas Gregorad8a3362009-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 Stump11289f42009-09-09 15:08:12 +00002880
2881 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002882 // the form
2883 //
Mike Stump11289f42009-09-09 15:08:12 +00002884 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2885 //
Douglas Gregorad8a3362009-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 Stump11289f42009-09-09 15:08:12 +00002890
Douglas Gregorad8a3362009-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 McCall10eae182009-11-30 22:42:35 +00002894 IsArrow, OpLoc,
2895 (NestedNameSpecifier *) SS.getScopeRep(),
2896 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002897 MemberName.getCXXNameType(),
2898 MemberLoc));
2899 }
Mike Stump11289f42009-09-09 15:08:12 +00002900
Chris Lattnerdc420f42008-07-21 04:59:05 +00002901 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2902 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002903 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2904 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002905 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002906 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002907 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002908 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002909 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2910
Steve Naroffa057ba92009-07-16 00:25:06 +00002911 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2912 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002913 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002914
Douglas Gregor35b0bac2010-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 Gregor6da83622010-01-07 00:17:44 +00002926 Diag(IV->getLocation(), diag::note_previous_decl)
2927 << IV->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002928 }
2929 }
2930
Steve Naroffa057ba92009-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 Gregor171c45a2009-02-18 21:56:37 +00002937
Steve Naroffa057ba92009-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 Stump11289f42009-09-09 15:08:12 +00002954 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-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 Stump11289f42009-09-09 15:08:12 +00002961
2962 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2963 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002964 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002965 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002966 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002967 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2968 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002969 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002970 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002971 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002972
2973 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2974 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002975 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002976 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002977 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002978 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002979 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002980 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002981 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002982 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002983 if (!IsArrow && (BaseType->isObjCIdType() ||
2984 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002985 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002986 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002987
Steve Naroff7cae42b2009-07-10 23:34:53 +00002988 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002989 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-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 Stump11289f42009-09-09 15:08:12 +00002995
Steve Naroff7cae42b2009-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 Stump11289f42009-09-09 15:08:12 +00003003
Steve Naroff7cae42b2009-07-10 23:34:53 +00003004 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00003005 OMD->getResultType(),
3006 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003007 NULL, 0));
3008 }
3009 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003010
Steve Naroff7cae42b2009-07-10 23:34:53 +00003011 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003012 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003013 }
Chris Lattnerdc420f42008-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 Naroff7cae42b2009-07-10 23:34:53 +00003016 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00003017 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003018 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3019 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00003020 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003021
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003022 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00003023 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003024 // Check whether we can reference this property.
3025 if (DiagnoseUseOfDecl(PD, MemberLoc))
3026 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003027 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00003028 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003029 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00003030 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3031 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003032 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00003033 MemberLoc, BaseExpr));
3034 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003035 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00003036 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3037 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00003038 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003039 // Check whether we can reference this property.
3040 if (DiagnoseUseOfDecl(PD, MemberLoc))
3041 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00003042
Steve Narofff6009ed2009-01-21 00:14:39 +00003043 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00003044 MemberLoc, BaseExpr));
3045 }
Daniel Dunbaref89086c2008-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 Carlssonf571c112009-08-26 18:25:21 +00003052 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003053 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003054
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003055 // If this reference is in an @implementation, check for 'private' methods.
3056 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00003057 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003058
Steve Naroff1df62692008-10-22 19:16:27 +00003059 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003060 if (!Getter)
3061 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003062 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003063 // Check if we can reference this property.
3064 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3065 return ExprError();
Steve Naroff1d984fe2009-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 Stump11289f42009-09-09 15:08:12 +00003069 Selector SetterSel =
3070 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00003071 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003073 if (!Setter) {
3074 // If this reference is in an @implementation, also check for 'private'
3075 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003076 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003077 }
3078 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003079 if (!Setter)
3080 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003081
Steve Naroff1d984fe2009-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 Jahanian88cc2342009-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 Naroff1d984fe2009-03-11 13:48:17 +00003093 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00003094 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00003095 Setter, MemberLoc, BaseExpr));
3096 }
Douglas Gregor35b0bac2010-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 Gregor6da83622010-01-07 00:17:44 +00003107 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3108 Diag(Property->getLocation(), diag::note_previous_decl)
3109 << Property->getDeclName();
3110
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003111 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCall38836f02010-01-15 08:34:02 +00003112 ObjCImpDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003113 }
3114
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003115 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003116 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00003117 }
Mike Stump11289f42009-09-09 15:08:12 +00003118
Steve Naroffe87026a2009-07-24 17:54:45 +00003119 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003120 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00003121 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003122 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003123 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003124 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003125
Chris Lattnerb63a7452008-07-21 04:28:12 +00003126 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003127 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003128 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003129 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3130 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003131 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003132 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003133 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003134 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003135
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003136 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3137 << BaseType << BaseExpr->getSourceRange();
3138
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003139 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003140}
3141
John McCall10eae182009-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 Gregor30d60cb2009-11-03 19:44:04 +00003148 << isa<CXXPseudoDestructorExpr>(E)
3149 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3150
John McCall10eae182009-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 Gregorea0a0a92010-01-11 18:40:55 +00003202 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCall2d74de92009-12-01 22:10:20 +00003203 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-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 McCall38836f02010-01-15 08:34:02 +00003215 SS, ObjCImpDecl);
John McCall10eae182009-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 McCall2d74de92009-12-01 22:10:20 +00003235 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003236 OpLoc, IsArrow, SS, FirstQualifierInScope,
3237 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003238 }
3239
3240 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003241}
3242
Anders Carlsson355933d2009-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 Stump11289f42009-09-09 15:08:12 +00003250 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-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 Gregor01afeef2009-08-28 20:31:08 +00003257 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003258
Mike Stump11289f42009-09-09 15:08:12 +00003259 InstantiatingTemplate Inst(*this, CallLoc, Param,
3260 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003261 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003262
John McCall76d824f2009-08-25 22:02:44 +00003263 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003264 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003265 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003266
Douglas Gregor25ab25f2009-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 Carlsson355933d2009-08-25 03:49:14 +00003279 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003280
3281 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003282 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003283 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003284 }
Mike Stump11289f42009-09-09 15:08:12 +00003285
Anders Carlsson355933d2009-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 Gregor25ab25f2009-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 Carlsson714d0962009-12-15 19:16:31 +00003291 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3292 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003293 }
3294
3295 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003296 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003297}
3298
Douglas Gregor97fd6e22008-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 Stump4e1f26a2009-02-19 03:04:26 +00003305bool
3306Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003307 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003308 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003309 Expr **Args, unsigned NumArgs,
3310 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003311 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003312 // assignment, to the types of the corresponding parameter, ...
3313 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003314 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003315
Douglas Gregor97fd6e22008-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 Kremenek5a201952009-02-07 01:47:29 +00003322 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-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 Kremenek5a201952009-02-07 01:47:29 +00003335 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003336 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003337 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003338 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003339 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-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 Jahanian835026e2009-11-24 18:29:37 +00003346 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003347 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-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 Stump4e1f26a2009-02-19 03:04:26 +00003356
Fariborz Jahanian835026e2009-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 Jahanian6f2d25e2009-11-24 19:27:49 +00003363 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-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 Gregor97fd6e22008-12-22 05:46:06 +00003371 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003372 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003373 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003374
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003375 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003376 if (ArgIx < NumArgs) {
3377 Arg = Args[ArgIx++];
3378
Eli Friedman3164fb12009-03-22 22:00:50 +00003379 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3380 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003381 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003382 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003383 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003384
Douglas Gregorbbeb5c32009-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 Gregor96596c92009-12-22 07:24:36 +00003389
Douglas Gregorbbeb5c32009-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 Carlsson84613c42009-06-12 16:51:40 +00003401 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003402 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003403
Mike Stump11289f42009-09-09 15:08:12 +00003404 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003405 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003406 if (ArgExpr.isInvalid())
3407 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003408
Anders Carlsson355933d2009-08-25 03:49:14 +00003409 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003410 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003411 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003412 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003413
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003414 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003415 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003416 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003417 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003418 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003419 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003420 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003421 }
3422 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003423 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003424}
3425
Steve Naroff83895f72007-09-16 03:34:24 +00003426/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003427/// This provides the location of the left/right parens and a list of comma
3428/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003429Action::OwningExprResult
3430Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3431 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003432 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003433 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-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 Stump11289f42009-09-09 15:08:12 +00003437
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003438 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003439 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003440 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003441
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003442 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-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 Stump11289f42009-09-09 15:08:12 +00003451
Douglas Gregorad8a3362009-09-04 17:36:40 +00003452 for (unsigned I = 0; I != NumArgs; ++I)
3453 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003454
Douglas Gregorad8a3362009-09-04 17:36:40 +00003455 NumArgs = 0;
3456 }
Mike Stump11289f42009-09-09 15:08:12 +00003457
Douglas Gregorad8a3362009-09-04 17:36:40 +00003458 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3459 RParenLoc));
3460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003462 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003463 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003464 // FIXME: Will need to cache the results of name lookup (including ADL) in
3465 // Fn.
Douglas Gregorb8a9a412009-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 Kremenekd7b4f402009-02-09 20:51:47 +00003473 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-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 McCall10eae182009-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 Gregor8f184a32009-12-01 03:34:29 +00003492 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003493
John McCall2d74de92009-12-01 22:10:20 +00003494 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3495 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003496 }
3497
Douglas Gregore254f902009-02-04 00:32:51 +00003498 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003499 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003500 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003501 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003502 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3503 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003504 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003505
3506 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003507 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003508 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3509 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003510 if (const FunctionProtoType *FPT =
3511 dyn_cast<FunctionProtoType>(BO->getType())) {
3512 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003513
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003514 ExprOwningPtr<CXXMemberCallExpr>
3515 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3516 NumArgs, ResultTy,
3517 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003518
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003519 if (CheckCallReturnType(FPT->getResultType(),
3520 BO->getRHS()->getSourceRange().getBegin(),
3521 TheCall.get(), 0))
3522 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003523
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003524 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3525 RParenLoc))
3526 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003527
Fariborz Jahanian42f66632009-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 Carlsson61914b52009-10-03 17:40:22 +00003533 }
3534 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003535 }
3536
Douglas Gregore254f902009-02-04 00:32:51 +00003537 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003538 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003539 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003540
Eli Friedmane14b1992009-12-26 03:35:45 +00003541 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-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 Gregor5251f1b2008-10-21 16:13:35 +00003546 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003547
John McCall57500772009-12-16 12:17:52 +00003548 NamedDecl *NDecl = 0;
3549 if (isa<DeclRefExpr>(NakedFn))
3550 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3551
John McCall2d74de92009-12-01 22:10:20 +00003552 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3553}
3554
John McCall57500772009-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 McCall2d74de92009-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 Lattneraa9c7ae2008-04-08 04:40:51 +00003568 // Promote the function operand.
3569 UsualUnaryConversions(Fn);
3570
Chris Lattner08464942007-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 Kremenekd7b4f402009-02-09 20:51:47 +00003573 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3574 Args, NumArgs,
3575 Context.BoolTy,
3576 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003577
Steve Naroff8de9c3a2008-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 Kremenekc23c7e62009-07-29 21:53:49 +00003582 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003583 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003584 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3585 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003586 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003587 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003588 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003589 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003590 }
Chris Lattner08464942007-12-28 05:29:59 +00003591 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003592 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3593 << Fn->getType() << Fn->getSourceRange());
3594
Eli Friedman3164fb12009-03-22 22:00:50 +00003595 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003596 if (CheckCallReturnType(FuncT->getResultType(),
3597 Fn->getSourceRange().getBegin(), TheCall.get(),
3598 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003599 return ExprError();
3600
Chris Lattner08464942007-12-28 05:29:59 +00003601 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003602 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003603
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003604 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003605 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003606 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003607 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003608 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003609 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003610
Douglas Gregord8e97de2009-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 Kyrtzidisddcd1322009-06-30 02:35:26 +00003615 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003616 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003617 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-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 Gregord8e97de2009-04-02 15:37:10 +00003623 }
3624
Steve Naroff0b661582007-08-28 23:30:39 +00003625 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003626 for (unsigned i = 0; i != NumArgs; i++) {
3627 Expr *Arg = Args[i];
3628 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003629 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3630 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003631 PDiag(diag::err_call_incomplete_argument)
3632 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003633 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003634 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003635 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003636 }
Chris Lattner08464942007-12-28 05:29:59 +00003637
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003638 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3639 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003640 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3641 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003642
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003643 // Check for sentinels
3644 if (NDecl)
3645 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003646
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003647 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003648 if (FDecl) {
3649 if (CheckFunctionCall(FDecl, TheCall.get()))
3650 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003651
Douglas Gregor15fc9562009-09-12 00:22:50 +00003652 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-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 Lattnerb87b1b32007-08-10 20:18:51 +00003658
Anders Carlssonf8984012009-08-16 03:06:32 +00003659 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003660}
3661
Sebastian Redlb5d49352009-01-19 22:31:54 +00003662Action::OwningExprResult
3663Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3664 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003665 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003666 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003667 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003668
3669 TypeSourceInfo *TInfo;
3670 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3671 if (!TInfo)
3672 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3673
3674 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3675}
3676
3677Action::OwningExprResult
3678Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3679 SourceLocation RParenLoc, ExprArg InitExpr) {
3680 QualType literalType = TInfo->getType();
Sebastian Redlb5d49352009-01-19 22:31:54 +00003681 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003682
Eli Friedman37a186d2008-05-20 05:22:08 +00003683 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003684 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003685 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3686 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003687 } else if (!literalType->isDependentType() &&
3688 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003689 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003690 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003691 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003692 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003693
Douglas Gregor85dabae2009-12-16 01:38:02 +00003694 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003695 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003696 InitializationKind Kind
3697 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3698 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003699 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3700 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3701 MultiExprArg(*this, (void**)&literalExpr, 1),
3702 &literalType);
3703 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003704 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003705 InitExpr.release();
3706 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003707
Chris Lattner79413952008-12-04 23:50:19 +00003708 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003709 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003710 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003711 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003712 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003713
3714 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003715
John McCalle15bbff2010-01-18 19:35:47 +00003716 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo,
Steve Narofff6009ed2009-01-21 00:14:39 +00003717 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003718}
3719
Sebastian Redlb5d49352009-01-19 22:31:54 +00003720Action::OwningExprResult
3721Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003722 SourceLocation RBraceLoc) {
3723 unsigned NumInit = initlist.size();
3724 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003725
Steve Naroff30d242c2007-09-15 18:49:24 +00003726 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003727 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003728
Mike Stump4e1f26a2009-02-19 03:04:26 +00003729 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003730 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003731 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003732 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003733}
3734
Anders Carlsson094c4592009-10-18 18:12:03 +00003735static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3736 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003737 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003738 return CastExpr::CK_NoOp;
3739
3740 if (SrcTy->hasPointerRepresentation()) {
3741 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003742 return DestTy->isObjCObjectPointerType() ?
3743 CastExpr::CK_AnyPointerToObjCPointerCast :
3744 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003745 if (DestTy->isIntegerType())
3746 return CastExpr::CK_PointerToIntegral;
3747 }
3748
3749 if (SrcTy->isIntegerType()) {
3750 if (DestTy->isIntegerType())
3751 return CastExpr::CK_IntegralCast;
3752 if (DestTy->hasPointerRepresentation())
3753 return CastExpr::CK_IntegralToPointer;
3754 if (DestTy->isRealFloatingType())
3755 return CastExpr::CK_IntegralToFloating;
3756 }
3757
3758 if (SrcTy->isRealFloatingType()) {
3759 if (DestTy->isRealFloatingType())
3760 return CastExpr::CK_FloatingCast;
3761 if (DestTy->isIntegerType())
3762 return CastExpr::CK_FloatingToIntegral;
3763 }
3764
3765 // FIXME: Assert here.
3766 // assert(false && "Unhandled cast combination!");
3767 return CastExpr::CK_Unknown;
3768}
3769
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003770/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003771bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003772 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003773 CXXMethodDecl *& ConversionDecl,
3774 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003775 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003776 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3777 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003778
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003779 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003780
3781 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3782 // type needs to be scalar.
3783 if (castType->isVoidType()) {
3784 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003785 Kind = CastExpr::CK_ToVoid;
3786 return false;
3787 }
3788
3789 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003790 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003791 (castType->isStructureType() || castType->isUnionType())) {
3792 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003793 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003794 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3795 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003796 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003797 return false;
3798 }
3799
3800 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003801 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003802 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003803 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003804 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003805 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003806 if (Context.hasSameUnqualifiedType(Field->getType(),
3807 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003808 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3809 << castExpr->getSourceRange();
3810 break;
3811 }
3812 }
3813 if (Field == FieldEnd)
3814 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3815 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003816 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003817 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003818 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003819
3820 // Reject any other conversions to non-scalar types.
3821 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3822 << castType << castExpr->getSourceRange();
3823 }
3824
3825 if (!castExpr->getType()->isScalarType() &&
3826 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003827 return Diag(castExpr->getLocStart(),
3828 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003829 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003830 }
3831
Anders Carlsson43d70f82009-10-16 05:23:41 +00003832 if (castType->isExtVectorType())
3833 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3834
Anders Carlsson525b76b2009-10-16 02:48:28 +00003835 if (castType->isVectorType())
3836 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3837 if (castExpr->getType()->isVectorType())
3838 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3839
3840 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003841 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003842
Anders Carlsson43d70f82009-10-16 05:23:41 +00003843 if (isa<ObjCSelectorExpr>(castExpr))
3844 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3845
Anders Carlsson525b76b2009-10-16 02:48:28 +00003846 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003847 QualType castExprType = castExpr->getType();
3848 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3849 return Diag(castExpr->getLocStart(),
3850 diag::err_cast_pointer_from_non_pointer_int)
3851 << castExprType << castExpr->getSourceRange();
3852 } else if (!castExpr->getType()->isArithmeticType()) {
3853 if (!castType->isIntegralType() && castType->isArithmeticType())
3854 return Diag(castExpr->getLocStart(),
3855 diag::err_cast_pointer_to_non_pointer_int)
3856 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003857 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003858
3859 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003860 return false;
3861}
3862
Anders Carlsson525b76b2009-10-16 02:48:28 +00003863bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3864 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003865 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003866
Anders Carlssonde71adf2007-11-27 05:51:55 +00003867 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003868 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003869 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003870 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003871 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003872 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003873 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003874 } else
3875 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003876 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003877 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003878
Anders Carlsson525b76b2009-10-16 02:48:28 +00003879 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003880 return false;
3881}
3882
Anders Carlsson43d70f82009-10-16 05:23:41 +00003883bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3884 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003885 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003886
3887 QualType SrcTy = CastExpr->getType();
3888
Nate Begemanc8961a42009-06-27 22:05:55 +00003889 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3890 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003891 if (SrcTy->isVectorType()) {
3892 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3893 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3894 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003895 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003896 return false;
3897 }
3898
Nate Begemanbd956c42009-06-28 02:36:38 +00003899 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003900 // conversion will take place first from scalar to elt type, and then
3901 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003902 if (SrcTy->isPointerType())
3903 return Diag(R.getBegin(),
3904 diag::err_invalid_conversion_between_vector_and_scalar)
3905 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003906
3907 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3908 ImpCastExprToType(CastExpr, DestElemTy,
3909 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003910
3911 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003912 return false;
3913}
3914
Sebastian Redlb5d49352009-01-19 22:31:54 +00003915Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003916Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003917 SourceLocation RParenLoc, ExprArg Op) {
3918 assert((Ty != 0) && (Op.get() != 0) &&
3919 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003920
John McCall97513962010-01-15 18:39:57 +00003921 TypeSourceInfo *castTInfo;
3922 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3923 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00003924 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00003925
Nate Begeman5ec4b312009-08-10 23:49:36 +00003926 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallebe54742010-01-15 18:56:44 +00003927 Expr *castExpr = (Expr *)Op.get();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003928 if (isa<ParenListExpr>(castExpr))
John McCalle15bbff2010-01-18 19:35:47 +00003929 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3930 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00003931
3932 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3933}
3934
3935Action::OwningExprResult
3936Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3937 SourceLocation RParenLoc, ExprArg Op) {
3938 Expr *castExpr = static_cast<Expr*>(Op.get());
3939
Anders Carlssone9766d52009-09-09 21:33:21 +00003940 CXXMethodDecl *Method = 0;
John McCallebe54742010-01-15 18:56:44 +00003941 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3942 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003943 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003944 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003945
3946 if (Method) {
John McCallebe54742010-01-15 18:56:44 +00003947 // FIXME: preserve type source info here
3948 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
3949 Kind, Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003950
Anders Carlssone9766d52009-09-09 21:33:21 +00003951 if (CastArg.isInvalid())
3952 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003953
Anders Carlssone9766d52009-09-09 21:33:21 +00003954 castExpr = CastArg.takeAs<Expr>();
3955 } else {
3956 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003957 }
Mike Stump11289f42009-09-09 15:08:12 +00003958
John McCallebe54742010-01-15 18:56:44 +00003959 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3960 Kind, castExpr, Ty,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003961 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003962}
3963
Nate Begeman5ec4b312009-08-10 23:49:36 +00003964/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3965/// of comma binary operators.
3966Action::OwningExprResult
3967Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3968 Expr *expr = EA.takeAs<Expr>();
3969 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3970 if (!E)
3971 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003972
Nate Begeman5ec4b312009-08-10 23:49:36 +00003973 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003974
Nate Begeman5ec4b312009-08-10 23:49:36 +00003975 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3976 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3977 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003978
Nate Begeman5ec4b312009-08-10 23:49:36 +00003979 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3980}
3981
3982Action::OwningExprResult
3983Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3984 SourceLocation RParenLoc, ExprArg Op,
John McCalle15bbff2010-01-18 19:35:47 +00003985 TypeSourceInfo *TInfo) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003986 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCalle15bbff2010-01-18 19:35:47 +00003987 QualType Ty = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003988
3989 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003990 // then handle it as such.
3991 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3992 if (PE->getNumExprs() == 0) {
3993 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3994 return ExprError();
3995 }
3996
3997 llvm::SmallVector<Expr *, 8> initExprs;
3998 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3999 initExprs.push_back(PE->getExpr(i));
4000
4001 // FIXME: This means that pretty-printing the final AST will produce curly
4002 // braces instead of the original commas.
4003 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00004004 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004005 initExprs.size(), RParenLoc);
4006 E->setType(Ty);
John McCalle15bbff2010-01-18 19:35:47 +00004007 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004008 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004009 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004010 // sequence of BinOp comma operators.
4011 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCalle15bbff2010-01-18 19:35:47 +00004012 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004013 }
4014}
4015
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004016Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004017 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004018 MultiExprArg Val,
4019 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004020 unsigned nexprs = Val.size();
4021 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004022 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4023 Expr *expr;
4024 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4025 expr = new (Context) ParenExpr(L, R, exprs[0]);
4026 else
4027 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004028 return Owned(expr);
4029}
4030
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004031/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4032/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004033/// C99 6.5.15
4034QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4035 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004036 // C++ is sufficiently different to merit its own checker.
4037 if (getLangOptions().CPlusPlus)
4038 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4039
John McCall1fa36b72009-11-05 09:23:39 +00004040 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4041
Chris Lattner432cff52009-02-18 04:28:32 +00004042 UsualUnaryConversions(Cond);
4043 UsualUnaryConversions(LHS);
4044 UsualUnaryConversions(RHS);
4045 QualType CondTy = Cond->getType();
4046 QualType LHSTy = LHS->getType();
4047 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004048
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004049 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004050 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4051 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4052 << CondTy;
4053 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004054 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004055
Chris Lattnere2949f42008-01-06 22:42:25 +00004056 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004057 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4058 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004059
Chris Lattnere2949f42008-01-06 22:42:25 +00004060 // If both operands have arithmetic type, do the usual arithmetic conversions
4061 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004062 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4063 UsualArithmeticConversions(LHS, RHS);
4064 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004065 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004066
Chris Lattnere2949f42008-01-06 22:42:25 +00004067 // If both operands are the same structure or union type, the result is that
4068 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004069 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4070 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004071 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004072 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004073 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004074 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004075 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004076 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004077
Chris Lattnere2949f42008-01-06 22:42:25 +00004078 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004079 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004080 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4081 if (!LHSTy->isVoidType())
4082 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4083 << RHS->getSourceRange();
4084 if (!RHSTy->isVoidType())
4085 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4086 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004087 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4088 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004089 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004090 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004091 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4092 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004093 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004094 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004095 // promote the null to a pointer.
4096 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004097 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004098 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004099 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004100 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004101 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004102 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004103 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004104
4105 // All objective-c pointer type analysis is done here.
4106 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4107 QuestionLoc);
4108 if (!compositeType.isNull())
4109 return compositeType;
4110
4111
Steve Naroff05efa972009-07-01 14:36:47 +00004112 // Handle block pointer types.
4113 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4114 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4115 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4116 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004117 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4118 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004119 return destType;
4120 }
4121 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004122 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004123 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004124 }
Steve Naroff05efa972009-07-01 14:36:47 +00004125 // We have 2 block pointer types.
4126 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4127 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004128 return LHSTy;
4129 }
Steve Naroff05efa972009-07-01 14:36:47 +00004130 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004131 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4132 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004133
Steve Naroff05efa972009-07-01 14:36:47 +00004134 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4135 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004136 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004137 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004138 // In this situation, we assume void* type. No especially good
4139 // reason, but this is what gcc does, and we do have to pick
4140 // to get a consistent AST.
4141 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004142 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4143 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004144 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004145 }
Steve Naroff05efa972009-07-01 14:36:47 +00004146 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004147 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4148 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004149 return LHSTy;
4150 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004151
Steve Naroff05efa972009-07-01 14:36:47 +00004152 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4153 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4154 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004155 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4156 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004157
4158 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4159 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4160 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004161 QualType destPointee
4162 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004163 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004164 // Add qualifiers if necessary.
4165 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4166 // Promote to void*.
4167 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004168 return destType;
4169 }
4170 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004171 QualType destPointee
4172 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004173 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004174 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004175 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004176 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004177 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004178 return destType;
4179 }
4180
4181 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4182 // Two identical pointer types are always compatible.
4183 return LHSTy;
4184 }
4185 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4186 rhptee.getUnqualifiedType())) {
4187 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4188 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4189 // In this situation, we assume void* type. No especially good
4190 // reason, but this is what gcc does, and we do have to pick
4191 // to get a consistent AST.
4192 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004193 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4194 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004195 return incompatTy;
4196 }
4197 // The pointer types are compatible.
4198 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4199 // differently qualified versions of compatible types, the result type is
4200 // a pointer to an appropriately qualified version of the *composite*
4201 // type.
4202 // FIXME: Need to calculate the composite type.
4203 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004204 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4205 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004206 return LHSTy;
4207 }
Mike Stump11289f42009-09-09 15:08:12 +00004208
Steve Naroff05efa972009-07-01 14:36:47 +00004209 // GCC compatibility: soften pointer/integer mismatch.
4210 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4211 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4212 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004213 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004214 return RHSTy;
4215 }
4216 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4217 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4218 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004219 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004220 return LHSTy;
4221 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004222
Chris Lattnere2949f42008-01-06 22:42:25 +00004223 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004224 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4225 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004226 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004227}
4228
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004229/// FindCompositeObjCPointerType - Helper method to find composite type of
4230/// two objective-c pointer types of the two input expressions.
4231QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4232 SourceLocation QuestionLoc) {
4233 QualType LHSTy = LHS->getType();
4234 QualType RHSTy = RHS->getType();
4235
4236 // Handle things like Class and struct objc_class*. Here we case the result
4237 // to the pseudo-builtin, because that will be implicitly cast back to the
4238 // redefinition type if an attempt is made to access its fields.
4239 if (LHSTy->isObjCClassType() &&
4240 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4241 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4242 return LHSTy;
4243 }
4244 if (RHSTy->isObjCClassType() &&
4245 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4246 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4247 return RHSTy;
4248 }
4249 // And the same for struct objc_object* / id
4250 if (LHSTy->isObjCIdType() &&
4251 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4252 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4253 return LHSTy;
4254 }
4255 if (RHSTy->isObjCIdType() &&
4256 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4257 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4258 return RHSTy;
4259 }
4260 // And the same for struct objc_selector* / SEL
4261 if (Context.isObjCSelType(LHSTy) &&
4262 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4263 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4264 return LHSTy;
4265 }
4266 if (Context.isObjCSelType(RHSTy) &&
4267 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4268 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4269 return RHSTy;
4270 }
4271 // Check constraints for Objective-C object pointers types.
4272 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4273
4274 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4275 // Two identical object pointer types are always compatible.
4276 return LHSTy;
4277 }
4278 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4279 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4280 QualType compositeType = LHSTy;
4281
4282 // If both operands are interfaces and either operand can be
4283 // assigned to the other, use that type as the composite
4284 // type. This allows
4285 // xxx ? (A*) a : (B*) b
4286 // where B is a subclass of A.
4287 //
4288 // Additionally, as for assignment, if either type is 'id'
4289 // allow silent coercion. Finally, if the types are
4290 // incompatible then make sure to use 'id' as the composite
4291 // type so the result is acceptable for sending messages to.
4292
4293 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4294 // It could return the composite type.
4295 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4296 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4297 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4298 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4299 } else if ((LHSTy->isObjCQualifiedIdType() ||
4300 RHSTy->isObjCQualifiedIdType()) &&
4301 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4302 // Need to handle "id<xx>" explicitly.
4303 // GCC allows qualified id and any Objective-C type to devolve to
4304 // id. Currently localizing to here until clear this should be
4305 // part of ObjCQualifiedIdTypesAreCompatible.
4306 compositeType = Context.getObjCIdType();
4307 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4308 compositeType = Context.getObjCIdType();
4309 } else if (!(compositeType =
4310 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4311 ;
4312 else {
4313 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4314 << LHSTy << RHSTy
4315 << LHS->getSourceRange() << RHS->getSourceRange();
4316 QualType incompatTy = Context.getObjCIdType();
4317 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4318 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4319 return incompatTy;
4320 }
4321 // The object pointer types are compatible.
4322 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4323 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4324 return compositeType;
4325 }
4326 // Check Objective-C object pointer types and 'void *'
4327 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4328 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4329 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4330 QualType destPointee
4331 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4332 QualType destType = Context.getPointerType(destPointee);
4333 // Add qualifiers if necessary.
4334 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4335 // Promote to void*.
4336 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4337 return destType;
4338 }
4339 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4340 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4341 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4342 QualType destPointee
4343 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4344 QualType destType = Context.getPointerType(destPointee);
4345 // Add qualifiers if necessary.
4346 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4347 // Promote to void*.
4348 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4349 return destType;
4350 }
4351 return QualType();
4352}
4353
Steve Naroff83895f72007-09-16 03:34:24 +00004354/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004355/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004356Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4357 SourceLocation ColonLoc,
4358 ExprArg Cond, ExprArg LHS,
4359 ExprArg RHS) {
4360 Expr *CondExpr = (Expr *) Cond.get();
4361 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004362
4363 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4364 // was the condition.
4365 bool isLHSNull = LHSExpr == 0;
4366 if (isLHSNull)
4367 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004368
4369 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004370 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004371 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004372 return ExprError();
4373
4374 Cond.release();
4375 LHS.release();
4376 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004377 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004378 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004379 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004380}
4381
Steve Naroff3f597292007-05-11 22:18:03 +00004382// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004383// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004384// routine is it effectively iqnores the qualifiers on the top level pointee.
4385// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4386// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004387Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004388Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004389 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004390
David Chisnall9f57c292009-08-17 16:35:33 +00004391 if ((lhsType->isObjCClassType() &&
4392 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4393 (rhsType->isObjCClassType() &&
4394 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4395 return Compatible;
4396 }
4397
Steve Naroff1f4d7272007-05-11 04:00:31 +00004398 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004399 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4400 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004401
Steve Naroff1f4d7272007-05-11 04:00:31 +00004402 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004403 lhptee = Context.getCanonicalType(lhptee);
4404 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004405
Chris Lattner9bad62c2008-01-04 18:04:52 +00004406 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004407
4408 // C99 6.5.16.1p1: This following citation is common to constraints
4409 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4410 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004411 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004412 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004413 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004414
Mike Stump4e1f26a2009-02-19 03:04:26 +00004415 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4416 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004417 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004418 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004419 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004420 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004421
Chris Lattner0a788432008-01-03 22:56:36 +00004422 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004423 assert(rhptee->isFunctionType());
4424 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004425 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004426
Chris Lattner0a788432008-01-03 22:56:36 +00004427 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004428 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004429 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004430
4431 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004432 assert(lhptee->isFunctionType());
4433 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004434 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004435 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004436 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004437 lhptee = lhptee.getUnqualifiedType();
4438 rhptee = rhptee.getUnqualifiedType();
4439 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4440 // Check if the pointee types are compatible ignoring the sign.
4441 // We explicitly check for char so that we catch "char" vs
4442 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004443 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004444 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004445 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004446 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004447
4448 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004449 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004450 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004451 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004452
Eli Friedman80160bd2009-03-22 23:59:44 +00004453 if (lhptee == rhptee) {
4454 // Types are compatible ignoring the sign. Qualifier incompatibility
4455 // takes priority over sign incompatibility because the sign
4456 // warning can be disabled.
4457 if (ConvTy != Compatible)
4458 return ConvTy;
4459 return IncompatiblePointerSign;
4460 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004461
4462 // If we are a multi-level pointer, it's possible that our issue is simply
4463 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4464 // the eventual target type is the same and the pointers have the same
4465 // level of indirection, this must be the issue.
4466 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4467 do {
4468 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4469 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4470
4471 lhptee = Context.getCanonicalType(lhptee);
4472 rhptee = Context.getCanonicalType(rhptee);
4473 } while (lhptee->isPointerType() && rhptee->isPointerType());
4474
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004475 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004476 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004477 }
4478
Eli Friedman80160bd2009-03-22 23:59:44 +00004479 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004480 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004481 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004482 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004483}
4484
Steve Naroff081c7422008-09-04 15:10:53 +00004485/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4486/// block pointer types are compatible or whether a block and normal pointer
4487/// are compatible. It is more restrict than comparing two function pointer
4488// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004489Sema::AssignConvertType
4490Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004491 QualType rhsType) {
4492 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004493
Steve Naroff081c7422008-09-04 15:10:53 +00004494 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004495 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4496 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004497
Steve Naroff081c7422008-09-04 15:10:53 +00004498 // make sure we operate on the canonical type
4499 lhptee = Context.getCanonicalType(lhptee);
4500 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004501
Steve Naroff081c7422008-09-04 15:10:53 +00004502 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004503
Steve Naroff081c7422008-09-04 15:10:53 +00004504 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004505 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004506 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004507
Eli Friedmana6638ca2009-06-08 05:08:54 +00004508 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004509 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004510 return ConvTy;
4511}
4512
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004513/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4514/// for assignment compatibility.
4515Sema::AssignConvertType
4516Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4517 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4518 return Compatible;
4519 QualType lhptee =
4520 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4521 QualType rhptee =
4522 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4523 // make sure we operate on the canonical type
4524 lhptee = Context.getCanonicalType(lhptee);
4525 rhptee = Context.getCanonicalType(rhptee);
4526 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4527 return CompatiblePointerDiscardsQualifiers;
4528
4529 if (Context.typesAreCompatible(lhsType, rhsType))
4530 return Compatible;
4531 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4532 return IncompatibleObjCQualifiedId;
4533 return IncompatiblePointer;
4534}
4535
Mike Stump4e1f26a2009-02-19 03:04:26 +00004536/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4537/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004538/// pointers. Here are some objectionable examples that GCC considers warnings:
4539///
4540/// int a, *pint;
4541/// short *pshort;
4542/// struct foo *pfoo;
4543///
4544/// pint = pshort; // warning: assignment from incompatible pointer type
4545/// a = pint; // warning: assignment makes integer from pointer without a cast
4546/// pint = a; // warning: assignment makes pointer from integer without a cast
4547/// pint = pfoo; // warning: assignment from incompatible pointer type
4548///
4549/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004550/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004551///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004552Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004553Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004554 // Get canonical types. We're not formatting these types, just comparing
4555 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004556 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4557 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004558
4559 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004560 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004561
David Chisnall9f57c292009-08-17 16:35:33 +00004562 if ((lhsType->isObjCClassType() &&
4563 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4564 (rhsType->isObjCClassType() &&
4565 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4566 return Compatible;
4567 }
4568
Douglas Gregor6b754842008-10-28 00:22:11 +00004569 // If the left-hand side is a reference type, then we are in a
4570 // (rare!) case where we've allowed the use of references in C,
4571 // e.g., as a parameter type in a built-in function. In this case,
4572 // just make sure that the type referenced is compatible with the
4573 // right-hand side type. The caller is responsible for adjusting
4574 // lhsType so that the resulting expression does not have reference
4575 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004576 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004577 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004578 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004579 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004580 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004581 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4582 // to the same ExtVector type.
4583 if (lhsType->isExtVectorType()) {
4584 if (rhsType->isExtVectorType())
4585 return lhsType == rhsType ? Compatible : Incompatible;
4586 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4587 return Compatible;
4588 }
Mike Stump11289f42009-09-09 15:08:12 +00004589
Nate Begeman191a6b12008-07-14 18:02:46 +00004590 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004591 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004592 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004593 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004594 if (getLangOptions().LaxVectorConversions &&
4595 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004596 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004597 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004598 }
4599 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004600 }
Eli Friedman3360d892008-05-30 18:07:22 +00004601
Chris Lattner881a2122008-01-04 23:32:24 +00004602 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004603 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004604
Chris Lattnerec646832008-04-07 06:49:41 +00004605 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004606 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004607 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004608
Chris Lattnerec646832008-04-07 06:49:41 +00004609 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004610 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004611
Steve Naroffaccc4882009-07-20 17:56:53 +00004612 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004613 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004614 if (lhsType->isVoidPointerType()) // an exception to the rule.
4615 return Compatible;
4616 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004617 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004618 if (rhsType->getAs<BlockPointerType>()) {
4619 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004620 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004621
4622 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004623 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004624 return Compatible;
4625 }
Steve Naroff081c7422008-09-04 15:10:53 +00004626 return Incompatible;
4627 }
4628
4629 if (isa<BlockPointerType>(lhsType)) {
4630 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004631 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004632
Steve Naroff32d072c2008-09-29 18:10:17 +00004633 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004634 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004635 return Compatible;
4636
Steve Naroff081c7422008-09-04 15:10:53 +00004637 if (rhsType->isBlockPointerType())
4638 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004639
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004640 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004641 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004642 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004643 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004644 return Incompatible;
4645 }
4646
Steve Naroff7cae42b2009-07-10 23:34:53 +00004647 if (isa<ObjCObjectPointerType>(lhsType)) {
4648 if (rhsType->isIntegerType())
4649 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Naroffaccc4882009-07-20 17:56:53 +00004651 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004652 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004653 if (rhsType->isVoidPointerType()) // an exception to the rule.
4654 return Compatible;
4655 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004656 }
4657 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004658 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004659 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004660 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004661 if (RHSPT->getPointeeType()->isVoidType())
4662 return Compatible;
4663 }
4664 // Treat block pointers as objects.
4665 if (rhsType->isBlockPointerType())
4666 return Compatible;
4667 return Incompatible;
4668 }
Chris Lattnerec646832008-04-07 06:49:41 +00004669 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004670 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004671 if (lhsType == Context.BoolTy)
4672 return Compatible;
4673
4674 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004675 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004676
Mike Stump4e1f26a2009-02-19 03:04:26 +00004677 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004678 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004679
4680 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004681 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004682 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004683 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004684 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004685 if (isa<ObjCObjectPointerType>(rhsType)) {
4686 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4687 if (lhsType == Context.BoolTy)
4688 return Compatible;
4689
4690 if (lhsType->isIntegerType())
4691 return PointerToInt;
4692
Steve Naroffaccc4882009-07-20 17:56:53 +00004693 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004694 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004695 if (lhsType->isVoidPointerType()) // an exception to the rule.
4696 return Compatible;
4697 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004698 }
4699 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004700 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004701 return Compatible;
4702 return Incompatible;
4703 }
Eli Friedman3360d892008-05-30 18:07:22 +00004704
Chris Lattnera52c2f22008-01-04 23:18:45 +00004705 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004706 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004707 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004708 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004709 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004710}
4711
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004712/// \brief Constructs a transparent union from an expression that is
4713/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004714static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004715 QualType UnionType, FieldDecl *Field) {
4716 // Build an initializer list that designates the appropriate member
4717 // of the transparent union.
4718 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4719 &E, 1,
4720 SourceLocation());
4721 Initializer->setType(UnionType);
4722 Initializer->setInitializedFieldInUnion(Field);
4723
4724 // Build a compound literal constructing a value of the transparent
4725 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004726 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
4727 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo,
4728 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004729}
4730
4731Sema::AssignConvertType
4732Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4733 QualType FromType = rExpr->getType();
4734
Mike Stump11289f42009-09-09 15:08:12 +00004735 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004736 // transparent_union GCC extension.
4737 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004738 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004739 return Incompatible;
4740
4741 // The field to initialize within the transparent union.
4742 RecordDecl *UD = UT->getDecl();
4743 FieldDecl *InitField = 0;
4744 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004745 for (RecordDecl::field_iterator it = UD->field_begin(),
4746 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004747 it != itend; ++it) {
4748 if (it->getType()->isPointerType()) {
4749 // If the transparent union contains a pointer type, we allow:
4750 // 1) void pointer
4751 // 2) null pointer constant
4752 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004753 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004754 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004755 InitField = *it;
4756 break;
4757 }
Mike Stump11289f42009-09-09 15:08:12 +00004758
Douglas Gregor56751b52009-09-25 04:25:58 +00004759 if (rExpr->isNullPointerConstant(Context,
4760 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004761 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004762 InitField = *it;
4763 break;
4764 }
4765 }
4766
4767 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4768 == Compatible) {
4769 InitField = *it;
4770 break;
4771 }
4772 }
4773
4774 if (!InitField)
4775 return Incompatible;
4776
4777 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4778 return Compatible;
4779}
4780
Chris Lattner9bad62c2008-01-04 18:04:52 +00004781Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004782Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004783 if (getLangOptions().CPlusPlus) {
4784 if (!lhsType->isRecordType()) {
4785 // C++ 5.17p3: If the left operand is not of class type, the
4786 // expression is implicitly converted (C++ 4) to the
4787 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004788 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004789 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004790 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004791 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004792 }
4793
4794 // FIXME: Currently, we fall through and treat C++ classes like C
4795 // structures.
4796 }
4797
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004798 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4799 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004800 if ((lhsType->isPointerType() ||
4801 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004802 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004803 && rExpr->isNullPointerConstant(Context,
4804 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004805 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004806 return Compatible;
4807 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004808
Chris Lattnere6dcd502007-10-16 02:55:40 +00004809 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004810 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004811 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004812 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004813 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004814 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004815 if (!lhsType->isReferenceType())
4816 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004817
Chris Lattner9bad62c2008-01-04 18:04:52 +00004818 Sema::AssignConvertType result =
4819 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004820
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004821 // C99 6.5.16.1p2: The value of the right operand is converted to the
4822 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004823 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4824 // so that we can use references in built-in functions even in C.
4825 // The getNonReferenceType() call makes sure that the resulting expression
4826 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004827 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004828 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4829 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004830 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004831}
4832
Chris Lattner326f7572008-11-18 01:30:42 +00004833QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004834 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004835 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004836 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004837 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004838}
4839
Chris Lattnerfaa54172010-01-12 21:23:57 +00004840QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004841 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004842 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004843 QualType lhsType =
4844 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4845 QualType rhsType =
4846 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004847
Nate Begeman191a6b12008-07-14 18:02:46 +00004848 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004849 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004850 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004851
Nate Begeman191a6b12008-07-14 18:02:46 +00004852 // Handle the case of a vector & extvector type of the same size and element
4853 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004854 if (getLangOptions().LaxVectorConversions) {
4855 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004856 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4857 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004858 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004859 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004860 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004861 }
4862 }
4863 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004864
Nate Begemanbd956c42009-06-28 02:36:38 +00004865 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4866 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4867 bool swapped = false;
4868 if (rhsType->isExtVectorType()) {
4869 swapped = true;
4870 std::swap(rex, lex);
4871 std::swap(rhsType, lhsType);
4872 }
Mike Stump11289f42009-09-09 15:08:12 +00004873
Nate Begeman886448d2009-06-28 19:12:57 +00004874 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004875 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004876 QualType EltTy = LV->getElementType();
4877 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4878 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004879 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004880 if (swapped) std::swap(rex, lex);
4881 return lhsType;
4882 }
4883 }
4884 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4885 rhsType->isRealFloatingType()) {
4886 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004887 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004888 if (swapped) std::swap(rex, lex);
4889 return lhsType;
4890 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004891 }
4892 }
Mike Stump11289f42009-09-09 15:08:12 +00004893
Nate Begeman886448d2009-06-28 19:12:57 +00004894 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004895 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004896 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004897 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004898 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004899}
4900
Chris Lattnerfaa54172010-01-12 21:23:57 +00004901QualType Sema::CheckMultiplyDivideOperands(
4902 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004903 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004904 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004905
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004906 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004907
Chris Lattnerfaa54172010-01-12 21:23:57 +00004908 if (!lex->getType()->isArithmeticType() ||
4909 !rex->getType()->isArithmeticType())
4910 return InvalidOperands(Loc, lex, rex);
4911
4912 // Check for division by zero.
4913 if (isDiv &&
4914 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004915 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4916 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004917
4918 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004919}
4920
Chris Lattnerfaa54172010-01-12 21:23:57 +00004921QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004922 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004923 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4924 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4925 return CheckVectorOperands(Loc, lex, rex);
4926 return InvalidOperands(Loc, lex, rex);
4927 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004928
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004929 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004930
Chris Lattnerfaa54172010-01-12 21:23:57 +00004931 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4932 return InvalidOperands(Loc, lex, rex);
4933
4934 // Check for remainder by zero.
4935 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004936 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4937 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004938
4939 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004940}
4941
Chris Lattnerfaa54172010-01-12 21:23:57 +00004942QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004943 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004944 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4945 QualType compType = CheckVectorOperands(Loc, lex, rex);
4946 if (CompLHSTy) *CompLHSTy = compType;
4947 return compType;
4948 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004949
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004950 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004951
Steve Naroffe4718892007-04-27 18:30:00 +00004952 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004953 if (lex->getType()->isArithmeticType() &&
4954 rex->getType()->isArithmeticType()) {
4955 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004956 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004957 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004958
Eli Friedman8e122982008-05-18 18:08:51 +00004959 // Put any potential pointer into PExp
4960 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004961 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004962 std::swap(PExp, IExp);
4963
Steve Naroff6b712a72009-07-14 18:25:06 +00004964 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004965
Eli Friedman8e122982008-05-18 18:08:51 +00004966 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004967 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004968
Chris Lattner12bdebb2009-04-24 23:50:08 +00004969 // Check for arithmetic on pointers to incomplete types.
4970 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004971 if (getLangOptions().CPlusPlus) {
4972 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004973 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004974 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004975 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004976
4977 // GNU extension: arithmetic on pointer to void
4978 Diag(Loc, diag::ext_gnu_void_ptr)
4979 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004980 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004981 if (getLangOptions().CPlusPlus) {
4982 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4983 << lex->getType() << lex->getSourceRange();
4984 return QualType();
4985 }
4986
4987 // GNU extension: arithmetic on pointer to function
4988 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4989 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004990 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004991 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004992 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004993 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004994 PExp->getType()->isObjCObjectPointerType()) &&
4995 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004996 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4997 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004998 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004999 return QualType();
5000 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005001 // Diagnose bad cases where we step over interface counts.
5002 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5003 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5004 << PointeeTy << PExp->getSourceRange();
5005 return QualType();
5006 }
Mike Stump11289f42009-09-09 15:08:12 +00005007
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005008 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005009 QualType LHSTy = Context.isPromotableBitField(lex);
5010 if (LHSTy.isNull()) {
5011 LHSTy = lex->getType();
5012 if (LHSTy->isPromotableIntegerType())
5013 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005014 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005015 *CompLHSTy = LHSTy;
5016 }
Eli Friedman8e122982008-05-18 18:08:51 +00005017 return PExp->getType();
5018 }
5019 }
5020
Chris Lattner326f7572008-11-18 01:30:42 +00005021 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005022}
5023
Chris Lattner2a3569b2008-04-07 05:30:13 +00005024// C99 6.5.6
5025QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005026 SourceLocation Loc, QualType* CompLHSTy) {
5027 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5028 QualType compType = CheckVectorOperands(Loc, lex, rex);
5029 if (CompLHSTy) *CompLHSTy = compType;
5030 return compType;
5031 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005032
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005033 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005034
Chris Lattner4d62f422007-12-09 21:53:25 +00005035 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005036
Chris Lattner4d62f422007-12-09 21:53:25 +00005037 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005038 if (lex->getType()->isArithmeticType()
5039 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005040 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005041 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005042 }
Mike Stump11289f42009-09-09 15:08:12 +00005043
Chris Lattner4d62f422007-12-09 21:53:25 +00005044 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005045 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005046 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005047
Douglas Gregorac1fb652009-03-24 19:52:54 +00005048 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005049
Douglas Gregorac1fb652009-03-24 19:52:54 +00005050 bool ComplainAboutVoid = false;
5051 Expr *ComplainAboutFunc = 0;
5052 if (lpointee->isVoidType()) {
5053 if (getLangOptions().CPlusPlus) {
5054 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5055 << lex->getSourceRange() << rex->getSourceRange();
5056 return QualType();
5057 }
5058
5059 // GNU C extension: arithmetic on pointer to void
5060 ComplainAboutVoid = true;
5061 } else if (lpointee->isFunctionType()) {
5062 if (getLangOptions().CPlusPlus) {
5063 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005064 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005065 return QualType();
5066 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005067
5068 // GNU C extension: arithmetic on pointer to function
5069 ComplainAboutFunc = lex;
5070 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005071 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005072 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005073 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005074 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005075 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005076
Chris Lattner12bdebb2009-04-24 23:50:08 +00005077 // Diagnose bad cases where we step over interface counts.
5078 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5079 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5080 << lpointee << lex->getSourceRange();
5081 return QualType();
5082 }
Mike Stump11289f42009-09-09 15:08:12 +00005083
Chris Lattner4d62f422007-12-09 21:53:25 +00005084 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005085 if (rex->getType()->isIntegerType()) {
5086 if (ComplainAboutVoid)
5087 Diag(Loc, diag::ext_gnu_void_ptr)
5088 << lex->getSourceRange() << rex->getSourceRange();
5089 if (ComplainAboutFunc)
5090 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005091 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005092 << ComplainAboutFunc->getSourceRange();
5093
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005094 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005095 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005096 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005097
Chris Lattner4d62f422007-12-09 21:53:25 +00005098 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005099 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005100 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005101
Douglas Gregorac1fb652009-03-24 19:52:54 +00005102 // RHS must be a completely-type object type.
5103 // Handle the GNU void* extension.
5104 if (rpointee->isVoidType()) {
5105 if (getLangOptions().CPlusPlus) {
5106 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5107 << lex->getSourceRange() << rex->getSourceRange();
5108 return QualType();
5109 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005110
Douglas Gregorac1fb652009-03-24 19:52:54 +00005111 ComplainAboutVoid = true;
5112 } else if (rpointee->isFunctionType()) {
5113 if (getLangOptions().CPlusPlus) {
5114 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005115 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005116 return QualType();
5117 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005118
5119 // GNU extension: arithmetic on pointer to function
5120 if (!ComplainAboutFunc)
5121 ComplainAboutFunc = rex;
5122 } else if (!rpointee->isDependentType() &&
5123 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005124 PDiag(diag::err_typecheck_sub_ptr_object)
5125 << rex->getSourceRange()
5126 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005127 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005128
Eli Friedman168fe152009-05-16 13:54:38 +00005129 if (getLangOptions().CPlusPlus) {
5130 // Pointee types must be the same: C++ [expr.add]
5131 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5132 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5133 << lex->getType() << rex->getType()
5134 << lex->getSourceRange() << rex->getSourceRange();
5135 return QualType();
5136 }
5137 } else {
5138 // Pointee types must be compatible C99 6.5.6p3
5139 if (!Context.typesAreCompatible(
5140 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5141 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5142 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5143 << lex->getType() << rex->getType()
5144 << lex->getSourceRange() << rex->getSourceRange();
5145 return QualType();
5146 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005147 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005148
Douglas Gregorac1fb652009-03-24 19:52:54 +00005149 if (ComplainAboutVoid)
5150 Diag(Loc, diag::ext_gnu_void_ptr)
5151 << lex->getSourceRange() << rex->getSourceRange();
5152 if (ComplainAboutFunc)
5153 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005154 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005155 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005156
5157 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005158 return Context.getPointerDiffType();
5159 }
5160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005161
Chris Lattner326f7572008-11-18 01:30:42 +00005162 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005163}
5164
Chris Lattner2a3569b2008-04-07 05:30:13 +00005165// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005166QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005167 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005168 // C99 6.5.7p2: Each of the operands shall have integer type.
5169 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005170 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005171
Nate Begemane46ee9a2009-10-25 02:26:48 +00005172 // Vector shifts promote their scalar inputs to vector type.
5173 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5174 return CheckVectorOperands(Loc, lex, rex);
5175
Chris Lattner5c11c412007-12-12 05:47:28 +00005176 // Shifts don't perform usual arithmetic conversions, they just do integer
5177 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005178 QualType LHSTy = Context.isPromotableBitField(lex);
5179 if (LHSTy.isNull()) {
5180 LHSTy = lex->getType();
5181 if (LHSTy->isPromotableIntegerType())
5182 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005183 }
Chris Lattner3c133402007-12-13 07:28:16 +00005184 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005185 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005186
Chris Lattner5c11c412007-12-12 05:47:28 +00005187 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005188
Ryan Flynnf53fab82009-08-07 16:20:20 +00005189 // Sanity-check shift operands
5190 llvm::APSInt Right;
5191 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005192 if (!rex->isValueDependent() &&
5193 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005194 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005195 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5196 else {
5197 llvm::APInt LeftBits(Right.getBitWidth(),
5198 Context.getTypeSize(lex->getType()));
5199 if (Right.uge(LeftBits))
5200 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5201 }
5202 }
5203
Chris Lattner5c11c412007-12-12 05:47:28 +00005204 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005205 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005206}
5207
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005208// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005209QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005210 unsigned OpaqueOpc, bool isRelational) {
5211 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5212
Chris Lattner9a152e22009-12-05 05:40:13 +00005213 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005214 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005215 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005216
John McCall99ce6bf2009-11-06 08:49:08 +00005217 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5218 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005219
Chris Lattnerb620c342007-08-26 01:18:55 +00005220 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005221 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5222 UsualArithmeticConversions(lex, rex);
5223 else {
5224 UsualUnaryConversions(lex);
5225 UsualUnaryConversions(rex);
5226 }
Steve Naroff31090012007-07-16 21:54:35 +00005227 QualType lType = lex->getType();
5228 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005229
Mike Stumpf70bcf72009-05-07 18:43:07 +00005230 if (!lType->isFloatingType()
5231 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005232 // For non-floating point types, check for self-comparisons of the form
5233 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5234 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005235 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005236 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005237 Expr *LHSStripped = lex->IgnoreParens();
5238 Expr *RHSStripped = rex->IgnoreParens();
5239 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5240 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005241 if (DRL->getDecl() == DRR->getDecl() &&
5242 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregor49862b82010-01-12 23:18:54 +00005243 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump11289f42009-09-09 15:08:12 +00005244
Chris Lattner222b8bd2009-03-08 19:39:53 +00005245 if (isa<CastExpr>(LHSStripped))
5246 LHSStripped = LHSStripped->IgnoreParenCasts();
5247 if (isa<CastExpr>(RHSStripped))
5248 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005249
Chris Lattner222b8bd2009-03-08 19:39:53 +00005250 // Warn about comparisons against a string constant (unless the other
5251 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005252 Expr *literalString = 0;
5253 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005254 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005255 !RHSStripped->isNullPointerConstant(Context,
5256 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005257 literalString = lex;
5258 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005259 } else if ((isa<StringLiteral>(RHSStripped) ||
5260 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005261 !LHSStripped->isNullPointerConstant(Context,
5262 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005263 literalString = rex;
5264 literalStringStripped = RHSStripped;
5265 }
5266
5267 if (literalString) {
5268 std::string resultComparison;
5269 switch (Opc) {
5270 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5271 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5272 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5273 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5274 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5275 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5276 default: assert(false && "Invalid comparison operator");
5277 }
Douglas Gregor49862b82010-01-12 23:18:54 +00005278
5279 DiagRuntimeBehavior(Loc,
5280 PDiag(diag::warn_stringcompare)
5281 << isa<ObjCEncodeExpr>(literalStringStripped)
5282 << literalString->getSourceRange()
5283 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5284 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5285 "strcmp(")
5286 << CodeModificationHint::CreateInsertion(
5287 PP.getLocForEndOfToken(rex->getLocEnd()),
5288 resultComparison));
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005289 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005290 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005291
Douglas Gregorca63811b2008-11-19 03:25:36 +00005292 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005293 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005294
Chris Lattnerb620c342007-08-26 01:18:55 +00005295 if (isRelational) {
5296 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005297 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005298 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005299 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005300 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005301 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005302
Chris Lattnerb620c342007-08-26 01:18:55 +00005303 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005304 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005305 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005306
Douglas Gregor56751b52009-09-25 04:25:58 +00005307 bool LHSIsNull = lex->isNullPointerConstant(Context,
5308 Expr::NPC_ValueDependentIsNull);
5309 bool RHSIsNull = rex->isNullPointerConstant(Context,
5310 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005311
Chris Lattnerb620c342007-08-26 01:18:55 +00005312 // All of the following pointer related warnings are GCC extensions, except
5313 // when handling null pointer constants. One day, we can consider making them
5314 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005315 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005316 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005317 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005318 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005319 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005320
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005321 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005322 if (LCanPointeeTy == RCanPointeeTy)
5323 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005324 if (!isRelational &&
5325 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5326 // Valid unless comparison between non-null pointer and function pointer
5327 // This is a gcc extension compatibility comparison.
5328 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5329 && !LHSIsNull && !RHSIsNull) {
5330 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5331 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5332 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5333 return ResultTy;
5334 }
5335 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005336 // C++ [expr.rel]p2:
5337 // [...] Pointer conversions (4.10) and qualification
5338 // conversions (4.4) are performed on pointer operands (or on
5339 // a pointer operand and a null pointer constant) to bring
5340 // them to their composite pointer type. [...]
5341 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005342 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005343 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005344 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005345 if (T.isNull()) {
5346 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5347 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5348 return QualType();
5349 }
5350
Eli Friedman06ed2a52009-10-20 08:27:19 +00005351 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5352 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005353 return ResultTy;
5354 }
Eli Friedman16c209612009-08-23 00:27:47 +00005355 // C99 6.5.9p2 and C99 6.5.8p2
5356 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5357 RCanPointeeTy.getUnqualifiedType())) {
5358 // Valid unless a relational comparison of function pointers
5359 if (isRelational && LCanPointeeTy->isFunctionType()) {
5360 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5361 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5362 }
5363 } else if (!isRelational &&
5364 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5365 // Valid unless comparison between non-null pointer and function pointer
5366 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5367 && !LHSIsNull && !RHSIsNull) {
5368 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5369 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5370 }
5371 } else {
5372 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005373 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005374 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005375 }
Eli Friedman16c209612009-08-23 00:27:47 +00005376 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005377 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005378 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005379 }
Mike Stump11289f42009-09-09 15:08:12 +00005380
Sebastian Redl576fd422009-05-10 18:38:11 +00005381 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005382 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005383 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005384 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005385 (lType->isPointerType() ||
5386 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005387 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005388 return ResultTy;
5389 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005390 if (LHSIsNull &&
5391 (rType->isPointerType() ||
5392 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005393 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005394 return ResultTy;
5395 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005396
5397 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005398 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005399 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5400 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005401 // In addition, pointers to members can be compared, or a pointer to
5402 // member and a null pointer constant. Pointer to member conversions
5403 // (4.11) and qualification conversions (4.4) are performed to bring
5404 // them to a common type. If one operand is a null pointer constant,
5405 // the common type is the type of the other operand. Otherwise, the
5406 // common type is a pointer to member type similar (4.4) to the type
5407 // of one of the operands, with a cv-qualification signature (4.4)
5408 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005409 // types.
5410 QualType T = FindCompositePointerType(lex, rex);
5411 if (T.isNull()) {
5412 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5413 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5414 return QualType();
5415 }
Mike Stump11289f42009-09-09 15:08:12 +00005416
Eli Friedman06ed2a52009-10-20 08:27:19 +00005417 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5418 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005419 return ResultTy;
5420 }
Mike Stump11289f42009-09-09 15:08:12 +00005421
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005422 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005423 if (lType->isNullPtrType() && rType->isNullPtrType())
5424 return ResultTy;
5425 }
Mike Stump11289f42009-09-09 15:08:12 +00005426
Steve Naroff081c7422008-09-04 15:10:53 +00005427 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005428 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005429 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5430 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005431
Steve Naroff081c7422008-09-04 15:10:53 +00005432 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005433 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005434 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005435 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005436 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005437 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005438 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005439 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005440 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005441 if (!isRelational
5442 && ((lType->isBlockPointerType() && rType->isPointerType())
5443 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005444 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005445 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005446 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005447 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005448 ->getPointeeType()->isVoidType())))
5449 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5450 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005451 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005452 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005453 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005454 }
Steve Naroff081c7422008-09-04 15:10:53 +00005455
Steve Naroff7cae42b2009-07-10 23:34:53 +00005456 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005457 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005458 const PointerType *LPT = lType->getAs<PointerType>();
5459 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005460 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005461 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005462 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005463 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005464
Steve Naroff753567f2008-11-17 19:49:16 +00005465 if (!LPtrToVoid && !RPtrToVoid &&
5466 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005467 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005468 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005469 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005470 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005471 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005472 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005473 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005474 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5476 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005477 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005478 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005479 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005480 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005481 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005482 unsigned DiagID = 0;
5483 if (RHSIsNull) {
5484 if (isRelational)
5485 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5486 } else if (isRelational)
5487 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5488 else
5489 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005490
Chris Lattnerd99bd522009-08-23 00:03:44 +00005491 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005492 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005493 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005494 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005495 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005496 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005497 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005498 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005499 unsigned DiagID = 0;
5500 if (LHSIsNull) {
5501 if (isRelational)
5502 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5503 } else if (isRelational)
5504 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5505 else
5506 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005507
Chris Lattnerd99bd522009-08-23 00:03:44 +00005508 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005509 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005510 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005511 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005512 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005513 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005514 }
Steve Naroff4b191572008-09-04 16:56:14 +00005515 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005516 if (!isRelational && RHSIsNull
5517 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005518 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005519 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005520 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005521 if (!isRelational && LHSIsNull
5522 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005523 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005524 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005525 }
Chris Lattner326f7572008-11-18 01:30:42 +00005526 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005527}
5528
Nate Begeman191a6b12008-07-14 18:02:46 +00005529/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005530/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005531/// like a scalar comparison, a vector comparison produces a vector of integer
5532/// types.
5533QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005534 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005535 bool isRelational) {
5536 // Check to make sure we're operating on vectors of the same type and width,
5537 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005538 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005539 if (vType.isNull())
5540 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005541
Nate Begeman191a6b12008-07-14 18:02:46 +00005542 QualType lType = lex->getType();
5543 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005544
Nate Begeman191a6b12008-07-14 18:02:46 +00005545 // For non-floating point types, check for self-comparisons of the form
5546 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5547 // often indicate logic errors in the program.
5548 if (!lType->isFloatingType()) {
5549 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5550 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5551 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregor49862b82010-01-12 23:18:54 +00005552 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begeman191a6b12008-07-14 18:02:46 +00005553 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005554
Nate Begeman191a6b12008-07-14 18:02:46 +00005555 // Check for comparisons of floating point operands using != and ==.
5556 if (!isRelational && lType->isFloatingType()) {
5557 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005558 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005559 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005560
Nate Begeman191a6b12008-07-14 18:02:46 +00005561 // Return the type for the comparison, which is the same as vector type for
5562 // integer vectors, or an integer type of identical size and number of
5563 // elements for floating point vectors.
5564 if (lType->isIntegerType())
5565 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005566
John McCall9dd450b2009-09-21 23:43:11 +00005567 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005568 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005569 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005570 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005571 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005572 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5573
Mike Stump4e1f26a2009-02-19 03:04:26 +00005574 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005575 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005576 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5577}
5578
Steve Naroff218bc2b2007-05-04 21:54:46 +00005579inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005580 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005581 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005582 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005583
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005584 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005585
Steve Naroffdbd9e892007-07-17 00:58:39 +00005586 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005587 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005588 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005589}
5590
Steve Naroff218bc2b2007-05-04 21:54:46 +00005591inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005592 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005593 if (!Context.getLangOptions().CPlusPlus) {
5594 UsualUnaryConversions(lex);
5595 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005596
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005597 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5598 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005599
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005600 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005601 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005602
5603 // C++ [expr.log.and]p1
5604 // C++ [expr.log.or]p1
5605 // The operands are both implicitly converted to type bool (clause 4).
5606 StandardConversionSequence LHS;
5607 if (!IsStandardConversion(lex, Context.BoolTy,
5608 /*InOverloadResolution=*/false, LHS))
5609 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005610
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005611 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005612 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005613 return InvalidOperands(Loc, lex, rex);
5614
5615 StandardConversionSequence RHS;
5616 if (!IsStandardConversion(rex, Context.BoolTy,
5617 /*InOverloadResolution=*/false, RHS))
5618 return InvalidOperands(Loc, lex, rex);
5619
5620 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005621 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005622 return InvalidOperands(Loc, lex, rex);
5623
5624 // C++ [expr.log.and]p2
5625 // C++ [expr.log.or]p2
5626 // The result is a bool.
5627 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005628}
5629
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005630/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5631/// is a read-only property; return true if so. A readonly property expression
5632/// depends on various declarations and thus must be treated specially.
5633///
Mike Stump11289f42009-09-09 15:08:12 +00005634static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005635 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5636 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5637 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5638 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005639 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005640 BaseType->getAsObjCInterfacePointerType())
5641 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5642 if (S.isPropertyReadonly(PDecl, IFace))
5643 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005644 }
5645 }
5646 return false;
5647}
5648
Chris Lattner30bd3272008-11-18 01:22:49 +00005649/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5650/// emit an error and return true. If so, return false.
5651static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005652 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005653 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005654 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005655 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5656 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005657 if (IsLV == Expr::MLV_Valid)
5658 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005659
Chris Lattner30bd3272008-11-18 01:22:49 +00005660 unsigned Diag = 0;
5661 bool NeedType = false;
5662 switch (IsLV) { // C99 6.5.16p2
5663 default: assert(0 && "Unknown result from isModifiableLvalue!");
5664 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005665 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005666 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5667 NeedType = true;
5668 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005669 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005670 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5671 NeedType = true;
5672 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005673 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005674 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5675 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005676 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005677 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5678 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005679 case Expr::MLV_IncompleteType:
5680 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005681 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005682 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5683 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005684 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005685 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5686 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005687 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005688 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5689 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005690 case Expr::MLV_ReadonlyProperty:
5691 Diag = diag::error_readonly_property_assignment;
5692 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005693 case Expr::MLV_NoSetterProperty:
5694 Diag = diag::error_nosetter_property_assignment;
5695 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005696 case Expr::MLV_SubObjCPropertySetting:
5697 Diag = diag::error_no_subobject_property_setting;
5698 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005699 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005700
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005701 SourceRange Assign;
5702 if (Loc != OrigLoc)
5703 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005704 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005705 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005706 else
Mike Stump11289f42009-09-09 15:08:12 +00005707 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005708 return true;
5709}
5710
5711
5712
5713// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005714QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5715 SourceLocation Loc,
5716 QualType CompoundType) {
5717 // Verify that LHS is a modifiable lvalue, and emit error if not.
5718 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005719 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005720
5721 QualType LHSType = LHS->getType();
5722 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005723
Chris Lattner9bad62c2008-01-04 18:04:52 +00005724 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005725 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005726 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005727 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005728 // Special case of NSObject attributes on c-style pointer types.
5729 if (ConvTy == IncompatiblePointer &&
5730 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005731 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005732 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005733 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005734 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005735
Chris Lattnerea714382008-08-21 18:04:13 +00005736 // If the RHS is a unary plus or minus, check to see if they = and + are
5737 // right next to each other. If so, the user may have typo'd "x =+ 4"
5738 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005739 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005740 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5741 RHSCheck = ICE->getSubExpr();
5742 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5743 if ((UO->getOpcode() == UnaryOperator::Plus ||
5744 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005745 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005746 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005747 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5748 // And there is a space or other character before the subexpr of the
5749 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005750 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5751 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005752 Diag(Loc, diag::warn_not_compound_assign)
5753 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5754 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005755 }
Chris Lattnerea714382008-08-21 18:04:13 +00005756 }
5757 } else {
5758 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005759 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005760 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005761
Chris Lattner326f7572008-11-18 01:30:42 +00005762 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005763 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005764 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005765
Steve Naroff98cf3e92007-06-06 18:38:38 +00005766 // C99 6.5.16p3: The type of an assignment expression is the type of the
5767 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005768 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005769 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5770 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005771 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005772 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005773 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005774}
5775
Chris Lattner326f7572008-11-18 01:30:42 +00005776// C99 6.5.17
5777QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005778 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005779 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005780
5781 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5782 // incomplete in C++).
5783
Chris Lattner326f7572008-11-18 01:30:42 +00005784 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005785}
5786
Steve Naroff7a5af782007-07-13 16:58:59 +00005787/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5788/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005789QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5790 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005791 if (Op->isTypeDependent())
5792 return Context.DependentTy;
5793
Chris Lattner6b0cf142008-11-21 07:05:48 +00005794 QualType ResType = Op->getType();
5795 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005796
Sebastian Redle10c2c32008-12-20 09:35:34 +00005797 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5798 // Decrement of bool is not allowed.
5799 if (!isInc) {
5800 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5801 return QualType();
5802 }
5803 // Increment of bool sets it to true, but is deprecated.
5804 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5805 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005806 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005807 } else if (ResType->isAnyPointerType()) {
5808 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005809
Chris Lattner6b0cf142008-11-21 07:05:48 +00005810 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005811 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005812 if (getLangOptions().CPlusPlus) {
5813 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5814 << Op->getSourceRange();
5815 return QualType();
5816 }
5817
5818 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005819 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005820 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005821 if (getLangOptions().CPlusPlus) {
5822 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5823 << Op->getType() << Op->getSourceRange();
5824 return QualType();
5825 }
5826
5827 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005828 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005829 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005830 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005831 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005832 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005833 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005834 // Diagnose bad cases where we step over interface counts.
5835 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5836 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5837 << PointeeTy << Op->getSourceRange();
5838 return QualType();
5839 }
Eli Friedman090addd2010-01-03 00:20:48 +00005840 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005841 // C99 does not support ++/-- on complex types, we allow as an extension.
5842 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005843 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005844 } else {
5845 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005846 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005847 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005848 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005849 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005850 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005851 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005852 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005853 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005854}
5855
Anders Carlsson806700f2008-02-01 07:15:58 +00005856/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005857/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005858/// where the declaration is needed for type checking. We only need to
5859/// handle cases when the expression references a function designator
5860/// or is an lvalue. Here are some examples:
5861/// - &(x) => x
5862/// - &*****f => f for f a function designator.
5863/// - &s.xx => s
5864/// - &s.zz[1].yy -> s, if zz is an array
5865/// - *(x + 1) -> x, if x is an array
5866/// - &"123"[2] -> 0
5867/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005868static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005869 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005870 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005871 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005872 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005873 // If this is an arrow operator, the address is an offset from
5874 // the base's value, so the object the base refers to is
5875 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005876 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005877 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005878 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005879 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005880 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005881 // FIXME: This code shouldn't be necessary! We should catch the implicit
5882 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005883 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5884 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5885 if (ICE->getSubExpr()->getType()->isArrayType())
5886 return getPrimaryDecl(ICE->getSubExpr());
5887 }
5888 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005889 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005890 case Stmt::UnaryOperatorClass: {
5891 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005892
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005893 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005894 case UnaryOperator::Real:
5895 case UnaryOperator::Imag:
5896 case UnaryOperator::Extension:
5897 return getPrimaryDecl(UO->getSubExpr());
5898 default:
5899 return 0;
5900 }
5901 }
Steve Naroff47500512007-04-19 23:00:49 +00005902 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005903 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005904 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005905 // If the result of an implicit cast is an l-value, we care about
5906 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005907 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005908 default:
5909 return 0;
5910 }
5911}
5912
5913/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005914/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005915/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005916/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005917/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005918/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005919/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005920QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005921 // Make sure to ignore parentheses in subsequent checks
5922 op = op->IgnoreParens();
5923
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005924 if (op->isTypeDependent())
5925 return Context.DependentTy;
5926
Steve Naroff826e91a2008-01-13 17:10:08 +00005927 if (getLangOptions().C99) {
5928 // Implement C99-only parts of addressof rules.
5929 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5930 if (uOp->getOpcode() == UnaryOperator::Deref)
5931 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5932 // (assuming the deref expression is valid).
5933 return uOp->getSubExpr()->getType();
5934 }
5935 // Technically, there should be a check for array subscript
5936 // expressions here, but the result of one is always an lvalue anyway.
5937 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005938 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005939 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005940
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005941 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5942 if (lval == Expr::LV_MemberFunction && ME &&
5943 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5944 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5945 // &f where f is a member of the current object, or &o.f, or &p->f
5946 // All these are not allowed, and we need to catch them before the dcl
5947 // branch of the if, below.
5948 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5949 << dcl;
5950 // FIXME: Improve this diagnostic and provide a fixit.
5951
5952 // Now recover by acting as if the function had been accessed qualified.
5953 return Context.getMemberPointerType(op->getType(),
5954 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5955 .getTypePtr());
5956 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00005957 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005958 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005959 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005960 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005961 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5962 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005963 return QualType();
5964 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005965 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005966 // The operand cannot be a bit-field
5967 Diag(OpLoc, diag::err_typecheck_address_of)
5968 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005969 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005970 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5971 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005972 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005973 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005974 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005975 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005976 } else if (isa<ObjCPropertyRefExpr>(op)) {
5977 // cannot take address of a property expression.
5978 Diag(OpLoc, diag::err_typecheck_address_of)
5979 << "property expression" << op->getSourceRange();
5980 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005981 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5982 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005983 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5984 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005985 } else if (isa<UnresolvedLookupExpr>(op)) {
5986 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005987 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005988 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005989 // with the register storage-class specifier.
5990 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005991 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005992 Diag(OpLoc, diag::err_typecheck_address_of)
5993 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005994 return QualType();
5995 }
John McCalld14a8642009-11-21 08:51:07 +00005996 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005997 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005998 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005999 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006000 // Could be a pointer to member, though, if there is an explicit
6001 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006002 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006003 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006004 if (Ctx && Ctx->isRecord()) {
6005 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006006 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006007 diag::err_cannot_form_pointer_to_member_of_reference_type)
6008 << FD->getDeclName() << FD->getType();
6009 return QualType();
6010 }
Mike Stump11289f42009-09-09 15:08:12 +00006011
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006012 return Context.getMemberPointerType(op->getType(),
6013 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006014 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006015 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006016 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00006017 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006018 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006019 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6020 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00006021 return Context.getMemberPointerType(op->getType(),
6022 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6023 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006024 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006025 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006026
Eli Friedmance7f9002009-05-16 23:27:50 +00006027 if (lval == Expr::LV_IncompleteVoidType) {
6028 // Taking the address of a void variable is technically illegal, but we
6029 // allow it in cases which are otherwise valid.
6030 // Example: "extern void x; void* y = &x;".
6031 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6032 }
6033
Steve Naroff47500512007-04-19 23:00:49 +00006034 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00006035 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006036}
6037
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006038QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006039 if (Op->isTypeDependent())
6040 return Context.DependentTy;
6041
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006042 UsualUnaryConversions(Op);
6043 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006044
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006045 // Note that per both C89 and C99, this is always legal, even if ptype is an
6046 // incomplete type or void. It would be possible to warn about dereferencing
6047 // a void pointer, but it's completely well-defined, and such a warning is
6048 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006049 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00006050 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006051
John McCall9dd450b2009-09-21 23:43:11 +00006052 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00006053 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006054
Chris Lattner29e812b2008-11-20 06:06:08 +00006055 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006056 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006057 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00006058}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006059
6060static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6061 tok::TokenKind Kind) {
6062 BinaryOperator::Opcode Opc;
6063 switch (Kind) {
6064 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006065 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6066 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006067 case tok::star: Opc = BinaryOperator::Mul; break;
6068 case tok::slash: Opc = BinaryOperator::Div; break;
6069 case tok::percent: Opc = BinaryOperator::Rem; break;
6070 case tok::plus: Opc = BinaryOperator::Add; break;
6071 case tok::minus: Opc = BinaryOperator::Sub; break;
6072 case tok::lessless: Opc = BinaryOperator::Shl; break;
6073 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6074 case tok::lessequal: Opc = BinaryOperator::LE; break;
6075 case tok::less: Opc = BinaryOperator::LT; break;
6076 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6077 case tok::greater: Opc = BinaryOperator::GT; break;
6078 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6079 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6080 case tok::amp: Opc = BinaryOperator::And; break;
6081 case tok::caret: Opc = BinaryOperator::Xor; break;
6082 case tok::pipe: Opc = BinaryOperator::Or; break;
6083 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6084 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6085 case tok::equal: Opc = BinaryOperator::Assign; break;
6086 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6087 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6088 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6089 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6090 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6091 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6092 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6093 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6094 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6095 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6096 case tok::comma: Opc = BinaryOperator::Comma; break;
6097 }
6098 return Opc;
6099}
6100
Steve Naroff35d85152007-05-07 00:24:15 +00006101static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6102 tok::TokenKind Kind) {
6103 UnaryOperator::Opcode Opc;
6104 switch (Kind) {
6105 default: assert(0 && "Unknown unary op!");
6106 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6107 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6108 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6109 case tok::star: Opc = UnaryOperator::Deref; break;
6110 case tok::plus: Opc = UnaryOperator::Plus; break;
6111 case tok::minus: Opc = UnaryOperator::Minus; break;
6112 case tok::tilde: Opc = UnaryOperator::Not; break;
6113 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006114 case tok::kw___real: Opc = UnaryOperator::Real; break;
6115 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006116 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006117 }
6118 return Opc;
6119}
6120
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006121/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6122/// operator @p Opc at location @c TokLoc. This routine only supports
6123/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006124Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6125 unsigned Op,
6126 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006127 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006128 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006129 // The following two variables are used for compound assignment operators
6130 QualType CompLHSTy; // Type of LHS after promotions for computation
6131 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006132
6133 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006134 case BinaryOperator::Assign:
6135 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6136 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006137 case BinaryOperator::PtrMemD:
6138 case BinaryOperator::PtrMemI:
6139 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6140 Opc == BinaryOperator::PtrMemI);
6141 break;
6142 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006143 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006144 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6145 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006146 break;
6147 case BinaryOperator::Rem:
6148 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6149 break;
6150 case BinaryOperator::Add:
6151 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6152 break;
6153 case BinaryOperator::Sub:
6154 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6155 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006156 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006157 case BinaryOperator::Shr:
6158 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6159 break;
6160 case BinaryOperator::LE:
6161 case BinaryOperator::LT:
6162 case BinaryOperator::GE:
6163 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006164 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006165 break;
6166 case BinaryOperator::EQ:
6167 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006168 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006169 break;
6170 case BinaryOperator::And:
6171 case BinaryOperator::Xor:
6172 case BinaryOperator::Or:
6173 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6174 break;
6175 case BinaryOperator::LAnd:
6176 case BinaryOperator::LOr:
6177 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6178 break;
6179 case BinaryOperator::MulAssign:
6180 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006181 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6182 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006183 CompLHSTy = CompResultTy;
6184 if (!CompResultTy.isNull())
6185 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006186 break;
6187 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006188 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6189 CompLHSTy = CompResultTy;
6190 if (!CompResultTy.isNull())
6191 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006192 break;
6193 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006194 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6195 if (!CompResultTy.isNull())
6196 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006197 break;
6198 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006199 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6200 if (!CompResultTy.isNull())
6201 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006202 break;
6203 case BinaryOperator::ShlAssign:
6204 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006205 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6206 CompLHSTy = CompResultTy;
6207 if (!CompResultTy.isNull())
6208 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006209 break;
6210 case BinaryOperator::AndAssign:
6211 case BinaryOperator::XorAssign:
6212 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006213 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6214 CompLHSTy = CompResultTy;
6215 if (!CompResultTy.isNull())
6216 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006217 break;
6218 case BinaryOperator::Comma:
6219 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6220 break;
6221 }
6222 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006223 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006224 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006225 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6226 else
6227 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006228 CompLHSTy, CompResultTy,
6229 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006230}
6231
Sebastian Redl44615072009-10-27 12:10:02 +00006232/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6233/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006234static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6235 const PartialDiagnostic &PD,
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006236 SourceRange ParenRange,
6237 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6238 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006239 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6240 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6241 // We can't display the parentheses, so just dig the
6242 // warning/error and return.
6243 Self.Diag(Loc, PD);
6244 return;
6245 }
6246
6247 Self.Diag(Loc, PD)
6248 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6249 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006250
6251 if (!SecondPD.getDiagID())
6252 return;
6253
6254 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6255 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6256 // We can't display the parentheses, so just dig the
6257 // warning/error and return.
6258 Self.Diag(Loc, SecondPD);
6259 return;
6260 }
6261
6262 Self.Diag(Loc, SecondPD)
6263 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6264 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006265}
6266
Sebastian Redl44615072009-10-27 12:10:02 +00006267/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6268/// operators are mixed in a way that suggests that the programmer forgot that
6269/// comparison operators have higher precedence. The most typical example of
6270/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006271static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6272 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006273 typedef BinaryOperator BinOp;
6274 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6275 rhsopc = static_cast<BinOp::Opcode>(-1);
6276 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006277 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006278 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006279 rhsopc = BO->getOpcode();
6280
6281 // Subs are not binary operators.
6282 if (lhsopc == -1 && rhsopc == -1)
6283 return;
6284
6285 // Bitwise operations are sometimes used as eager logical ops.
6286 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006287 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6288 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006289 return;
6290
Sebastian Redl44615072009-10-27 12:10:02 +00006291 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006292 SuggestParentheses(Self, OpLoc,
6293 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006294 << SourceRange(lhs->getLocStart(), OpLoc)
6295 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006296 lhs->getSourceRange(),
6297 PDiag(diag::note_precedence_bitwise_first)
6298 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006299 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6300 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006301 SuggestParentheses(Self, OpLoc,
6302 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006303 << SourceRange(OpLoc, rhs->getLocEnd())
6304 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006305 rhs->getSourceRange(),
6306 PDiag(diag::note_precedence_bitwise_first)
6307 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006308 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006309}
6310
6311/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6312/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6313/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6314static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6315 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006316 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006317 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6318}
6319
Steve Naroff218bc2b2007-05-04 21:54:46 +00006320// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006321Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6322 tok::TokenKind Kind,
6323 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006324 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006325 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006326
Steve Naroff83895f72007-09-16 03:34:24 +00006327 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6328 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006329
Sebastian Redl43028242009-10-26 15:24:15 +00006330 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6331 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6332
Douglas Gregor5287f092009-11-05 00:51:44 +00006333 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6334}
6335
6336Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6337 BinaryOperator::Opcode Opc,
6338 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006339 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006340 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006341 rhs->getType()->isOverloadableType())) {
6342 // Find all of the overloaded operators visible from this
6343 // point. We perform both an operator-name lookup from the local
6344 // scope and an argument-dependent lookup based on the types of
6345 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006346 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006347 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6348 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006349 if (S)
6350 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6351 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006352 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006353 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006354 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006355 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006356 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006357
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006358 // Build the (potentially-overloaded, potentially-dependent)
6359 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006360 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006361 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006362
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006363 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006364 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006365}
6366
Douglas Gregor084d8552009-03-13 23:49:33 +00006367Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006368 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006369 ExprArg InputArg) {
6370 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006371
Mike Stump87c57ac2009-05-16 07:39:55 +00006372 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006373 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006374 QualType resultType;
6375 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006376 case UnaryOperator::OffsetOf:
6377 assert(false && "Invalid unary operator");
6378 break;
6379
Steve Naroff35d85152007-05-07 00:24:15 +00006380 case UnaryOperator::PreInc:
6381 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006382 case UnaryOperator::PostInc:
6383 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006384 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006385 Opc == UnaryOperator::PreInc ||
6386 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006387 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006388 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006389 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006390 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006391 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006392 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006393 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006394 break;
6395 case UnaryOperator::Plus:
6396 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006397 UsualUnaryConversions(Input);
6398 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006399 if (resultType->isDependentType())
6400 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006401 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6402 break;
6403 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6404 resultType->isEnumeralType())
6405 break;
6406 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6407 Opc == UnaryOperator::Plus &&
6408 resultType->isPointerType())
6409 break;
6410
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006411 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6412 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006413 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006414 UsualUnaryConversions(Input);
6415 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006416 if (resultType->isDependentType())
6417 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006418 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6419 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6420 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006421 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006422 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006423 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006424 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6425 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006426 break;
6427 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006428 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006429 DefaultFunctionArrayConversion(Input);
6430 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006431 if (resultType->isDependentType())
6432 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006433 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006434 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6435 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006436 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006437 // In C++, it's bool. C++ 5.3.1p8
6438 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006439 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006440 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006441 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006442 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006443 break;
Chris Lattner86554282007-06-08 22:32:33 +00006444 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006445 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006446 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006447 }
6448 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006449 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006450
6451 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006452 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006453}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006454
Douglas Gregor5287f092009-11-05 00:51:44 +00006455Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6456 UnaryOperator::Opcode Opc,
6457 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006458 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006459 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6460 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006461 // Find all of the overloaded operators visible from this
6462 // point. We perform both an operator-name lookup from the local
6463 // scope and an argument-dependent lookup based on the types of
6464 // the arguments.
6465 FunctionSet Functions;
6466 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6467 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006468 if (S)
6469 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6470 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006471 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006472 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006473 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006474 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006475
Douglas Gregor084d8552009-03-13 23:49:33 +00006476 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6477 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006478
Douglas Gregor084d8552009-03-13 23:49:33 +00006479 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6480}
6481
Douglas Gregor5287f092009-11-05 00:51:44 +00006482// Unary Operators. 'Tok' is the token for the operator.
6483Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6484 tok::TokenKind Op, ExprArg input) {
6485 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6486}
6487
Steve Naroff66356bd2007-09-16 14:56:35 +00006488/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006489Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6490 SourceLocation LabLoc,
6491 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006492 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006493 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006494
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006495 // If we haven't seen this label yet, create a forward reference. It
6496 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006497 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006498 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006499
Chris Lattnereefa10e2007-05-28 06:56:27 +00006500 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006501 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6502 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006503}
6504
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006505Sema::OwningExprResult
6506Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6507 SourceLocation RPLoc) { // "({..})"
6508 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006509 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6510 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6511
Eli Friedman52cc0162009-01-24 23:09:00 +00006512 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006513 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006514 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006515
Chris Lattner366727f2007-07-24 16:58:17 +00006516 // FIXME: there are a variety of strange constraints to enforce here, for
6517 // example, it is not possible to goto into a stmt expression apparently.
6518 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006519
Chris Lattner366727f2007-07-24 16:58:17 +00006520 // If there are sub stmts in the compound stmt, take the type of the last one
6521 // as the type of the stmtexpr.
6522 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Chris Lattner944d3062008-07-26 19:51:01 +00006524 if (!Compound->body_empty()) {
6525 Stmt *LastStmt = Compound->body_back();
6526 // If LastStmt is a label, skip down through into the body.
6527 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6528 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006529
Chris Lattner944d3062008-07-26 19:51:01 +00006530 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006531 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006532 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533
Eli Friedmanba961a92009-03-23 00:24:07 +00006534 // FIXME: Check that expression type is complete/non-abstract; statement
6535 // expressions are not lvalues.
6536
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006537 substmt.release();
6538 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006539}
Steve Naroff78864672007-08-01 22:05:33 +00006540
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006541Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6542 SourceLocation BuiltinLoc,
6543 SourceLocation TypeLoc,
6544 TypeTy *argty,
6545 OffsetOfComponent *CompPtr,
6546 unsigned NumComponents,
6547 SourceLocation RPLoc) {
6548 // FIXME: This function leaks all expressions in the offset components on
6549 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006550 // FIXME: Preserve type source info.
6551 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006552 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006553
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006554 bool Dependent = ArgTy->isDependentType();
6555
Chris Lattnerf17bd422007-08-30 17:45:32 +00006556 // We must have at least one component that refers to the type, and the first
6557 // one is known to be a field designator. Verify that the ArgTy represents
6558 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006559 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006560 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006561
Eli Friedmanba961a92009-03-23 00:24:07 +00006562 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6563 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006564
Eli Friedman988a16b2009-02-27 06:44:11 +00006565 // Otherwise, create a null pointer as the base, and iteratively process
6566 // the offsetof designators.
6567 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6568 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006569 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006570 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006571
Chris Lattner78502cf2007-08-31 21:49:13 +00006572 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6573 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006574 // FIXME: This diagnostic isn't actually visible because the location is in
6575 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006576 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006577 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6578 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006579
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006580 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006581 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006582
John McCall9eff4e62009-11-04 03:03:43 +00006583 if (RequireCompleteType(TypeLoc, Res->getType(),
6584 diag::err_offsetof_incomplete_type))
6585 return ExprError();
6586
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006587 // FIXME: Dependent case loses a lot of information here. And probably
6588 // leaks like a sieve.
6589 for (unsigned i = 0; i != NumComponents; ++i) {
6590 const OffsetOfComponent &OC = CompPtr[i];
6591 if (OC.isBrackets) {
6592 // Offset of an array sub-field. TODO: Should we allow vector elements?
6593 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6594 if (!AT) {
6595 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006596 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6597 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006598 }
6599
6600 // FIXME: C++: Verify that operator[] isn't overloaded.
6601
Eli Friedman988a16b2009-02-27 06:44:11 +00006602 // Promote the array so it looks more like a normal array subscript
6603 // expression.
6604 DefaultFunctionArrayConversion(Res);
6605
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006606 // C99 6.5.2.1p1
6607 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006608 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006609 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006610 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006611 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006612 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006613
6614 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6615 OC.LocEnd);
6616 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006617 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006618
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006619 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006620 if (!RC) {
6621 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006622 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6623 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006624 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006625
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006626 // Get the decl corresponding to this.
6627 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006628 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006629 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6630 DiagRuntimeBehavior(BuiltinLoc,
6631 PDiag(diag::warn_offsetof_non_pod_type)
6632 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6633 << Res->getType()))
6634 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006635 }
Mike Stump11289f42009-09-09 15:08:12 +00006636
John McCall27b18f82009-11-17 02:14:36 +00006637 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6638 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006639
John McCall67c00872009-12-02 08:25:40 +00006640 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006641 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006642 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006643 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6644 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006645
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006646 // FIXME: C++: Verify that MemberDecl isn't a static field.
6647 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006648 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006649 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006650 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006651 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006652 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006653 // MemberDecl->getType() doesn't get the right qualifiers, but it
6654 // doesn't matter here.
6655 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6656 MemberDecl->getType().getNonReferenceType());
6657 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006658 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006659 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006660
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006661 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6662 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006663}
6664
6665
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006666Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6667 TypeTy *arg1,TypeTy *arg2,
6668 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006669 // FIXME: Preserve type source info.
6670 QualType argT1 = GetTypeFromParser(arg1);
6671 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006672
Steve Naroff78864672007-08-01 22:05:33 +00006673 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006674
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006675 if (getLangOptions().CPlusPlus) {
6676 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6677 << SourceRange(BuiltinLoc, RPLoc);
6678 return ExprError();
6679 }
6680
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006681 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6682 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006683}
6684
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006685Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6686 ExprArg cond,
6687 ExprArg expr1, ExprArg expr2,
6688 SourceLocation RPLoc) {
6689 Expr *CondExpr = static_cast<Expr*>(cond.get());
6690 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6691 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006692
Steve Naroff9efdabc2007-08-03 21:21:27 +00006693 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6694
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006695 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006696 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006697 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006698 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006699 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006700 } else {
6701 // The conditional expression is required to be a constant expression.
6702 llvm::APSInt condEval(32);
6703 SourceLocation ExpLoc;
6704 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006705 return ExprError(Diag(ExpLoc,
6706 diag::err_typecheck_choose_expr_requires_constant)
6707 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006708
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006709 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6710 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006711 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6712 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006713 }
6714
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006715 cond.release(); expr1.release(); expr2.release();
6716 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006717 resType, RPLoc,
6718 resType->isDependentType(),
6719 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006720}
6721
Steve Naroffc540d662008-09-03 18:15:37 +00006722//===----------------------------------------------------------------------===//
6723// Clang Extensions.
6724//===----------------------------------------------------------------------===//
6725
6726/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006727void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006728 // Analyze block parameters.
6729 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730
Steve Naroffc540d662008-09-03 18:15:37 +00006731 // Add BSI to CurBlock.
6732 BSI->PrevBlockInfo = CurBlock;
6733 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006734
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006735 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006736 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006737 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006738 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006739 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6740 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006741
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006742 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006743 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006744 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006745}
6746
Mike Stump82f071f2009-02-04 22:31:32 +00006747void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006748 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006749
6750 if (ParamInfo.getNumTypeObjects() == 0
6751 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006752 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006753 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6754
Mike Stumpd456c482009-04-28 01:10:27 +00006755 if (T->isArrayType()) {
6756 Diag(ParamInfo.getSourceRange().getBegin(),
6757 diag::err_block_returns_array);
6758 return;
6759 }
6760
Mike Stump82f071f2009-02-04 22:31:32 +00006761 // The parameter list is optional, if there was none, assume ().
6762 if (!T->isFunctionType())
6763 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6764
6765 CurBlock->hasPrototype = true;
6766 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006767 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006768 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006769 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006770 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006771 // FIXME: remove the attribute.
6772 }
John McCall9dd450b2009-09-21 23:43:11 +00006773 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006774
Chris Lattner6de05082009-04-11 19:27:54 +00006775 // Do not allow returning a objc interface by-value.
6776 if (RetTy->isObjCInterfaceType()) {
6777 Diag(ParamInfo.getSourceRange().getBegin(),
6778 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6779 return;
6780 }
Mike Stump82f071f2009-02-04 22:31:32 +00006781 return;
6782 }
6783
Steve Naroffc540d662008-09-03 18:15:37 +00006784 // Analyze arguments to block.
6785 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6786 "Not a function declarator!");
6787 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006788
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006789 CurBlock->hasPrototype = FTI.hasPrototype;
6790 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006791
Steve Naroffc540d662008-09-03 18:15:37 +00006792 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6793 // no arguments, not a function that takes a single void argument.
6794 if (FTI.hasPrototype &&
6795 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006796 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6797 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006798 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006799 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006800 } else if (FTI.hasPrototype) {
6801 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006802 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006803 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006804 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006805 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006806 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006807 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006808 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006809 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6810 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6811 // If this has an identifier, add it to the scope stack.
6812 if ((*AI)->getIdentifier())
6813 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006814
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006815 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006816 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006817 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006818 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006819 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006820 // FIXME: remove the attribute.
6821 }
Mike Stump11289f42009-09-09 15:08:12 +00006822
Chris Lattner6de05082009-04-11 19:27:54 +00006823 // Analyze the return type.
6824 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006825 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006826
Chris Lattner6de05082009-04-11 19:27:54 +00006827 // Do not allow returning a objc interface by-value.
6828 if (RetTy->isObjCInterfaceType()) {
6829 Diag(ParamInfo.getSourceRange().getBegin(),
6830 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6831 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006832 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006833}
6834
6835/// ActOnBlockError - If there is an error parsing a block, this callback
6836/// is invoked to pop the information about the block from the action impl.
6837void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6838 // Ensure that CurBlock is deleted.
6839 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006840
Chris Lattner45542ea2009-04-19 05:28:12 +00006841 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6842
Steve Naroffc540d662008-09-03 18:15:37 +00006843 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006844 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006845 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006846 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006847}
6848
6849/// ActOnBlockStmtExpr - This is called when the body of a block statement
6850/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006851Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6852 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006853 // If blocks are disabled, emit an error.
6854 if (!LangOpts.Blocks)
6855 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006856
Steve Naroffc540d662008-09-03 18:15:37 +00006857 // Ensure that CurBlock is deleted.
6858 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006859
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006860 PopDeclContext();
6861
Steve Naroffc540d662008-09-03 18:15:37 +00006862 // Pop off CurBlock, handle nested blocks.
6863 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006864
Steve Naroffc540d662008-09-03 18:15:37 +00006865 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006866 if (!BSI->ReturnType.isNull())
6867 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006868
Steve Naroffc540d662008-09-03 18:15:37 +00006869 llvm::SmallVector<QualType, 8> ArgTypes;
6870 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6871 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006872
Mike Stump3bf1ab42009-07-28 22:04:01 +00006873 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006874 QualType BlockTy;
6875 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006876 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6877 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006878 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006879 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006880 BSI->isVariadic, 0, false, false, 0, 0,
6881 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006882
Eli Friedmanba961a92009-03-23 00:24:07 +00006883 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006884 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006885 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006886
Chris Lattner45542ea2009-04-19 05:28:12 +00006887 // If needed, diagnose invalid gotos and switches in the block.
6888 if (CurFunctionNeedsScopeChecking)
6889 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6890 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006891
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006892 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump1bacb812010-01-13 02:59:54 +00006893 AnalysisContext AC(BSI->TheDecl);
6894 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6895 CheckUnreachable(AC);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006896 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6897 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006898}
6899
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006900Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6901 ExprArg expr, TypeTy *type,
6902 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006903 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006904 Expr *E = static_cast<Expr*>(expr.get());
6905 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006906
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006907 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006908
6909 // Get the va_list type
6910 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006911 if (VaListType->isArrayType()) {
6912 // Deal with implicit array decay; for example, on x86-64,
6913 // va_list is an array, but it's supposed to decay to
6914 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006915 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006916 // Make sure the input expression also decays appropriately.
6917 UsualUnaryConversions(E);
6918 } else {
6919 // Otherwise, the va_list argument must be an l-value because
6920 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006921 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006922 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006923 return ExprError();
6924 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006925
Douglas Gregorad3150c2009-05-19 23:10:31 +00006926 if (!E->isTypeDependent() &&
6927 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006928 return ExprError(Diag(E->getLocStart(),
6929 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006930 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006931 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006932
Eli Friedmanba961a92009-03-23 00:24:07 +00006933 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006934 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006935
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006936 expr.release();
6937 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6938 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006939}
6940
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006941Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006942 // The type of __null will be int or long, depending on the size of
6943 // pointers on the target.
6944 QualType Ty;
6945 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6946 Ty = Context.IntTy;
6947 else
6948 Ty = Context.LongTy;
6949
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006950 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006951}
6952
Anders Carlssonace5d072009-11-10 04:46:30 +00006953static void
6954MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6955 QualType DstType,
6956 Expr *SrcExpr,
6957 CodeModificationHint &Hint) {
6958 if (!SemaRef.getLangOptions().ObjC1)
6959 return;
6960
6961 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6962 if (!PT)
6963 return;
6964
6965 // Check if the destination is of type 'id'.
6966 if (!PT->isObjCIdType()) {
6967 // Check if the destination is the 'NSString' interface.
6968 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6969 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6970 return;
6971 }
6972
6973 // Strip off any parens and casts.
6974 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6975 if (!SL || SL->isWide())
6976 return;
6977
6978 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6979}
6980
Chris Lattner9bad62c2008-01-04 18:04:52 +00006981bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6982 SourceLocation Loc,
6983 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006984 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00006985 // Decode the result (notice that AST's are still created for extensions).
6986 bool isInvalid = false;
6987 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006988 CodeModificationHint Hint;
6989
Chris Lattner9bad62c2008-01-04 18:04:52 +00006990 switch (ConvTy) {
6991 default: assert(0 && "Unknown conversion type");
6992 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006993 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006994 DiagKind = diag::ext_typecheck_convert_pointer_int;
6995 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006996 case IntToPointer:
6997 DiagKind = diag::ext_typecheck_convert_int_pointer;
6998 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006999 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00007000 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007001 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7002 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007003 case IncompatiblePointerSign:
7004 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7005 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007006 case FunctionVoidPointer:
7007 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7008 break;
7009 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007010 // If the qualifiers lost were because we were applying the
7011 // (deprecated) C++ conversion from a string literal to a char*
7012 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7013 // Ideally, this check would be performed in
7014 // CheckPointerTypesForAssignment. However, that would require a
7015 // bit of refactoring (so that the second argument is an
7016 // expression, rather than a type), which should be done as part
7017 // of a larger effort to fix CheckPointerTypesForAssignment for
7018 // C++ semantics.
7019 if (getLangOptions().CPlusPlus &&
7020 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7021 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007022 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7023 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007024 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007025 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007026 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007027 case IntToBlockPointer:
7028 DiagKind = diag::err_int_to_block_pointer;
7029 break;
7030 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007031 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007032 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007033 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007034 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007035 // it can give a more specific diagnostic.
7036 DiagKind = diag::warn_incompatible_qualified_id;
7037 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007038 case IncompatibleVectors:
7039 DiagKind = diag::warn_incompatible_vectors;
7040 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007041 case Incompatible:
7042 DiagKind = diag::err_typecheck_convert_incompatible;
7043 isInvalid = true;
7044 break;
7045 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007046
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007047 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007048 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007049 return isInvalid;
7050}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007051
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007052bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007053 llvm::APSInt ICEResult;
7054 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7055 if (Result)
7056 *Result = ICEResult;
7057 return false;
7058 }
7059
Anders Carlssone54e8a12008-11-30 19:50:32 +00007060 Expr::EvalResult EvalResult;
7061
Mike Stump4e1f26a2009-02-19 03:04:26 +00007062 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007063 EvalResult.HasSideEffects) {
7064 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7065
7066 if (EvalResult.Diag) {
7067 // We only show the note if it's not the usual "invalid subexpression"
7068 // or if it's actually in a subexpression.
7069 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7070 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7071 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7072 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007073
Anders Carlssone54e8a12008-11-30 19:50:32 +00007074 return true;
7075 }
7076
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007077 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7078 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007079
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007080 if (EvalResult.Diag &&
7081 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7082 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007083
Anders Carlssone54e8a12008-11-30 19:50:32 +00007084 if (Result)
7085 *Result = EvalResult.Val.getInt();
7086 return false;
7087}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007088
Douglas Gregorff790f12009-11-26 00:44:06 +00007089void
Mike Stump11289f42009-09-09 15:08:12 +00007090Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007091 ExprEvalContexts.push_back(
7092 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007093}
7094
Mike Stump11289f42009-09-09 15:08:12 +00007095void
Douglas Gregorff790f12009-11-26 00:44:06 +00007096Sema::PopExpressionEvaluationContext() {
7097 // Pop the current expression evaluation context off the stack.
7098 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7099 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007100
Douglas Gregorfab31f42009-12-12 07:57:52 +00007101 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7102 if (Rec.PotentiallyReferenced) {
7103 // Mark any remaining declarations in the current position of the stack
7104 // as "referenced". If they were not meant to be referenced, semantic
7105 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7106 for (PotentiallyReferencedDecls::iterator
7107 I = Rec.PotentiallyReferenced->begin(),
7108 IEnd = Rec.PotentiallyReferenced->end();
7109 I != IEnd; ++I)
7110 MarkDeclarationReferenced(I->first, I->second);
7111 }
7112
7113 if (Rec.PotentiallyDiagnosed) {
7114 // Emit any pending diagnostics.
7115 for (PotentiallyEmittedDiagnostics::iterator
7116 I = Rec.PotentiallyDiagnosed->begin(),
7117 IEnd = Rec.PotentiallyDiagnosed->end();
7118 I != IEnd; ++I)
7119 Diag(I->first, I->second);
7120 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007121 }
7122
7123 // When are coming out of an unevaluated context, clear out any
7124 // temporaries that we may have created as part of the evaluation of
7125 // the expression in that context: they aren't relevant because they
7126 // will never be constructed.
7127 if (Rec.Context == Unevaluated &&
7128 ExprTemporaries.size() > Rec.NumTemporaries)
7129 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7130 ExprTemporaries.end());
7131
7132 // Destroy the popped expression evaluation record.
7133 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007134}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007135
7136/// \brief Note that the given declaration was referenced in the source code.
7137///
7138/// This routine should be invoke whenever a given declaration is referenced
7139/// in the source code, and where that reference occurred. If this declaration
7140/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7141/// C99 6.9p3), then the declaration will be marked as used.
7142///
7143/// \param Loc the location where the declaration was referenced.
7144///
7145/// \param D the declaration that has been referenced by the source code.
7146void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7147 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007148
Douglas Gregor77b50e12009-06-22 23:06:13 +00007149 if (D->isUsed())
7150 return;
Mike Stump11289f42009-09-09 15:08:12 +00007151
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007152 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7153 // template or not. The reason for this is that unevaluated expressions
7154 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7155 // -Wunused-parameters)
7156 if (isa<ParmVarDecl>(D) ||
7157 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007158 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007159
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007160 // Do not mark anything as "used" within a dependent context; wait for
7161 // an instantiation.
7162 if (CurContext->isDependentContext())
7163 return;
Mike Stump11289f42009-09-09 15:08:12 +00007164
Douglas Gregorff790f12009-11-26 00:44:06 +00007165 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007166 case Unevaluated:
7167 // We are in an expression that is not potentially evaluated; do nothing.
7168 return;
Mike Stump11289f42009-09-09 15:08:12 +00007169
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007170 case PotentiallyEvaluated:
7171 // We are in a potentially-evaluated expression, so this declaration is
7172 // "used"; handle this below.
7173 break;
Mike Stump11289f42009-09-09 15:08:12 +00007174
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007175 case PotentiallyPotentiallyEvaluated:
7176 // We are in an expression that may be potentially evaluated; queue this
7177 // declaration reference until we know whether the expression is
7178 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007179 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007180 return;
7181 }
Mike Stump11289f42009-09-09 15:08:12 +00007182
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007183 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007184 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007185 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007186 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7187 if (!Constructor->isUsed())
7188 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007189 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007190 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007191 if (!Constructor->isUsed())
7192 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7193 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007194
7195 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007196 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7197 if (Destructor->isImplicit() && !Destructor->isUsed())
7198 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007199
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007200 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7201 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7202 MethodDecl->getOverloadedOperator() == OO_Equal) {
7203 if (!MethodDecl->isUsed())
7204 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7205 }
7206 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007207 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007208 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007209 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007210 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007211 bool AlreadyInstantiated = false;
7212 if (FunctionTemplateSpecializationInfo *SpecInfo
7213 = Function->getTemplateSpecializationInfo()) {
7214 if (SpecInfo->getPointOfInstantiation().isInvalid())
7215 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007216 else if (SpecInfo->getTemplateSpecializationKind()
7217 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007218 AlreadyInstantiated = true;
7219 } else if (MemberSpecializationInfo *MSInfo
7220 = Function->getMemberSpecializationInfo()) {
7221 if (MSInfo->getPointOfInstantiation().isInvalid())
7222 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007223 else if (MSInfo->getTemplateSpecializationKind()
7224 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007225 AlreadyInstantiated = true;
7226 }
7227
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007228 if (!AlreadyInstantiated) {
7229 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7230 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7231 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7232 Loc));
7233 else
7234 PendingImplicitInstantiations.push_back(std::make_pair(Function,
7235 Loc));
7236 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007237 }
7238
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007239 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007240 Function->setUsed(true);
7241 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007242 }
Mike Stump11289f42009-09-09 15:08:12 +00007243
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007244 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007245 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007246 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007247 Var->getInstantiatedFromStaticDataMember()) {
7248 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7249 assert(MSInfo && "Missing member specialization information?");
7250 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7251 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7252 MSInfo->setPointOfInstantiation(Loc);
7253 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7254 }
7255 }
Mike Stump11289f42009-09-09 15:08:12 +00007256
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007257 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007258
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007259 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007260 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007261 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007262}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007263
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007264/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7265/// of the program being compiled.
7266///
7267/// This routine emits the given diagnostic when the code currently being
7268/// type-checked is "potentially evaluated", meaning that there is a
7269/// possibility that the code will actually be executable. Code in sizeof()
7270/// expressions, code used only during overload resolution, etc., are not
7271/// potentially evaluated. This routine will suppress such diagnostics or,
7272/// in the absolutely nutty case of potentially potentially evaluated
7273/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7274/// later.
7275///
7276/// This routine should be used for all diagnostics that describe the run-time
7277/// behavior of a program, such as passing a non-POD value through an ellipsis.
7278/// Failure to do so will likely result in spurious diagnostics or failures
7279/// during overload resolution or within sizeof/alignof/typeof/typeid.
7280bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7281 const PartialDiagnostic &PD) {
7282 switch (ExprEvalContexts.back().Context ) {
7283 case Unevaluated:
7284 // The argument will never be evaluated, so don't complain.
7285 break;
7286
7287 case PotentiallyEvaluated:
7288 Diag(Loc, PD);
7289 return true;
7290
7291 case PotentiallyPotentiallyEvaluated:
7292 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7293 break;
7294 }
7295
7296 return false;
7297}
7298
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007299bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7300 CallExpr *CE, FunctionDecl *FD) {
7301 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7302 return false;
7303
7304 PartialDiagnostic Note =
7305 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7306 << FD->getDeclName() : PDiag();
7307 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7308
7309 if (RequireCompleteType(Loc, ReturnType,
7310 FD ?
7311 PDiag(diag::err_call_function_incomplete_return)
7312 << CE->getSourceRange() << FD->getDeclName() :
7313 PDiag(diag::err_call_incomplete_return)
7314 << CE->getSourceRange(),
7315 std::make_pair(NoteLoc, Note)))
7316 return true;
7317
7318 return false;
7319}
7320
John McCalld5707ab2009-10-12 21:59:07 +00007321// Diagnose the common s/=/==/ typo. Note that adding parentheses
7322// will prevent this condition from triggering, which is what we want.
7323void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7324 SourceLocation Loc;
7325
John McCall0506e4a2009-11-11 02:41:58 +00007326 unsigned diagnostic = diag::warn_condition_is_assignment;
7327
John McCalld5707ab2009-10-12 21:59:07 +00007328 if (isa<BinaryOperator>(E)) {
7329 BinaryOperator *Op = cast<BinaryOperator>(E);
7330 if (Op->getOpcode() != BinaryOperator::Assign)
7331 return;
7332
John McCallb0e419e2009-11-12 00:06:05 +00007333 // Greylist some idioms by putting them into a warning subcategory.
7334 if (ObjCMessageExpr *ME
7335 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7336 Selector Sel = ME->getSelector();
7337
John McCallb0e419e2009-11-12 00:06:05 +00007338 // self = [<foo> init...]
7339 if (isSelfExpr(Op->getLHS())
7340 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7341 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7342
7343 // <foo> = [<bar> nextObject]
7344 else if (Sel.isUnarySelector() &&
7345 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7346 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7347 }
John McCall0506e4a2009-11-11 02:41:58 +00007348
John McCalld5707ab2009-10-12 21:59:07 +00007349 Loc = Op->getOperatorLoc();
7350 } else if (isa<CXXOperatorCallExpr>(E)) {
7351 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7352 if (Op->getOperator() != OO_Equal)
7353 return;
7354
7355 Loc = Op->getOperatorLoc();
7356 } else {
7357 // Not an assignment.
7358 return;
7359 }
7360
John McCalld5707ab2009-10-12 21:59:07 +00007361 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007362 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007363
John McCall0506e4a2009-11-11 02:41:58 +00007364 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007365 << E->getSourceRange()
7366 << CodeModificationHint::CreateInsertion(Open, "(")
7367 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007368 Diag(Loc, diag::note_condition_assign_to_comparison)
7369 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00007370}
7371
7372bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7373 DiagnoseAssignmentAsCondition(E);
7374
7375 if (!E->isTypeDependent()) {
7376 DefaultFunctionArrayConversion(E);
7377
7378 QualType T = E->getType();
7379
7380 if (getLangOptions().CPlusPlus) {
7381 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7382 return true;
7383 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7384 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7385 << T << E->getSourceRange();
7386 return true;
7387 }
7388 }
7389
7390 return false;
7391}