blob: a7cae8a85ec69d596b7fa1e5952fcf8634e4b172 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
David Chisnall44663db2009-08-17 16:35:33 +000029
Douglas Gregoraa57e862009-02-18 21:56:37 +000030/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000042 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000043 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000044 // Implementing deprecated stuff requires referencing deprecated
45 // stuff. Don't warn if we are implementing a deprecated
46 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000047 bool isSilenced = false;
48
49 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50 // If this reference happens *in* a deprecated function or method, don't
51 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000052 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000053
54 // If this is an Objective-C method implementation, check to see if the
55 // method was deprecated on the declaration, not the definition.
56 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57 // The semantic decl context of a ObjCMethodDecl is the
58 // ObjCImplementationDecl.
59 if (ObjCImplementationDecl *Impl
60 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000062 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000064 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000065 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000083 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian180f3412009-05-13 18:09:35 +000091/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96 Expr **Args, unsigned NumArgs)
97{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000099 if (!attr)
100 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000103
Mike Stumpe127ae32009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000150 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000151 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000181}
182
Douglas Gregor3bb30002009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner299b8842008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner299b8842008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
198 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000199 else if (Ty->isArrayType()) {
200 // In C90 mode, arrays only promote to pointers if the array expression is
201 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202 // type 'array of type' is converted to an expression that has type 'pointer
203 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
204 // that has type 'array of type' ...". The relevant change is "an lvalue"
205 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000206 //
207 // C++ 4.2p1:
208 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209 // T" can be converted to an rvalue of type "pointer to T".
210 //
211 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000213 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000215 }
Chris Lattner299b8842008-07-25 21:10:04 +0000216}
217
Douglas Gregor70b307e2009-05-01 20:41:21 +0000218/// \brief Whether this is a promotable bitfield reference according
219/// to C99 6.3.1.1p2, bullet 2.
220///
221/// \returns the type this bit-field will promote to, or NULL if no
222/// promotion occurs.
223static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000224 FieldDecl *Field = E->getBitField();
225 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000226 return QualType();
227
228 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
229 if (!BT)
230 return QualType();
231
232 if (BT->getKind() != BuiltinType::Bool &&
233 BT->getKind() != BuiltinType::Int &&
234 BT->getKind() != BuiltinType::UInt)
235 return QualType();
236
237 llvm::APSInt BitWidthAP;
238 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
239 return QualType();
240
241 uint64_t BitWidth = BitWidthAP.getZExtValue();
242 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
243 if (BitWidth < IntSize ||
244 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
245 return Context.IntTy;
246
247 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
248 return Context.UnsignedIntTy;
249
250 return QualType();
251}
252
Chris Lattner299b8842008-07-25 21:10:04 +0000253/// UsualUnaryConversions - Performs various conversions that are common to most
254/// operators (C99 6.3). The conversions of array and function types are
255/// sometimes surpressed. For example, the array->pointer conversion doesn't
256/// apply if the array is an argument to the sizeof or address (&) operators.
257/// In these instances, this routine should *not* be called.
258Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
259 QualType Ty = Expr->getType();
260 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
261
Douglas Gregor70b307e2009-05-01 20:41:21 +0000262 // C99 6.3.1.1p2:
263 //
264 // The following may be used in an expression wherever an int or
265 // unsigned int may be used:
266 // - an object or expression with an integer type whose integer
267 // conversion rank is less than or equal to the rank of int
268 // and unsigned int.
269 // - A bit-field of type _Bool, int, signed int, or unsigned int.
270 //
271 // If an int can represent all values of the original type, the
272 // value is converted to an int; otherwise, it is converted to an
273 // unsigned int. These are called the integer promotions. All
274 // other types are unchanged by the integer promotions.
275 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000277 return Expr;
278 } else {
279 QualType T = isPromotableBitField(Expr, Context);
280 if (!T.isNull()) {
281 ImpCastExprToType(Expr, T);
282 return Expr;
283 }
284 }
285
286 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000287 return Expr;
288}
289
Chris Lattner9305c3d2008-07-25 22:25:12 +0000290/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
291/// do not have a prototype. Arguments that have type float are promoted to
292/// double. All other argument types are converted by UsualUnaryConversions().
293void Sema::DefaultArgumentPromotion(Expr *&Expr) {
294 QualType Ty = Expr->getType();
295 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
296
297 // If this is a 'float' (CVR qualified or typedef) promote to double.
298 if (const BuiltinType *BT = Ty->getAsBuiltinType())
299 if (BT->getKind() == BuiltinType::Float)
300 return ImpCastExprToType(Expr, Context.DoubleTy);
301
302 UsualUnaryConversions(Expr);
303}
304
Chris Lattner81f00ed2009-04-12 08:11:20 +0000305/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
306/// will warn if the resulting type is not a POD type, and rejects ObjC
307/// interfaces passed by value. This returns true if the argument type is
308/// completely illegal.
309bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000310 DefaultArgumentPromotion(Expr);
311
Chris Lattner81f00ed2009-04-12 08:11:20 +0000312 if (Expr->getType()->isObjCInterfaceType()) {
313 Diag(Expr->getLocStart(),
314 diag::err_cannot_pass_objc_interface_to_vararg)
315 << Expr->getType() << CT;
316 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000317 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000318
319 if (!Expr->getType()->isPODType())
320 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
321 << Expr->getType() << CT;
322
323 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000324}
325
326
Chris Lattner299b8842008-07-25 21:10:04 +0000327/// UsualArithmeticConversions - Performs various conversions that are common to
328/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
329/// routine returns the first non-arithmetic type found. The client is
330/// responsible for emitting appropriate error diagnostics.
331/// FIXME: verify the conversion rules for "complex int" are consistent with
332/// GCC.
333QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
334 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000335 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000336 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000337
338 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000339
Chris Lattner299b8842008-07-25 21:10:04 +0000340 // For conversion purposes, we ignore any qualifiers.
341 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000342 QualType lhs =
343 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
344 QualType rhs =
345 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000346
347 // If both types are identical, no conversion is needed.
348 if (lhs == rhs)
349 return lhs;
350
351 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
352 // The caller can deal with this (e.g. pointer + int).
353 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
354 return lhs;
355
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000356 // Perform bitfield promotions.
357 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
358 if (!LHSBitfieldPromoteTy.isNull())
359 lhs = LHSBitfieldPromoteTy;
360 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
361 if (!RHSBitfieldPromoteTy.isNull())
362 rhs = RHSBitfieldPromoteTy;
363
Douglas Gregor70d26122008-11-12 17:17:38 +0000364 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000365 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000366 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000367 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000368 return destType;
369}
370
371QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
372 // Perform the usual unary conversions. We do this early so that
373 // integral promotions to "int" can allow us to exit early, in the
374 // lhs == rhs check. Also, for conversion purposes, we ignore any
375 // qualifiers. For example, "const float" and "float" are
376 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000377 if (lhs->isPromotableIntegerType())
378 lhs = Context.IntTy;
379 else
380 lhs = lhs.getUnqualifiedType();
381 if (rhs->isPromotableIntegerType())
382 rhs = Context.IntTy;
383 else
384 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000385
Chris Lattner299b8842008-07-25 21:10:04 +0000386 // If both types are identical, no conversion is needed.
387 if (lhs == rhs)
388 return lhs;
389
390 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
391 // The caller can deal with this (e.g. pointer + int).
392 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
393 return lhs;
394
395 // At this point, we have two different arithmetic types.
396
397 // Handle complex types first (C99 6.3.1.8p1).
398 if (lhs->isComplexType() || rhs->isComplexType()) {
399 // if we have an integer operand, the result is the complex type.
400 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
401 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000402 return lhs;
403 }
404 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
405 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000406 return rhs;
407 }
408 // This handles complex/complex, complex/float, or float/complex.
409 // When both operands are complex, the shorter operand is converted to the
410 // type of the longer, and that is the type of the result. This corresponds
411 // to what is done when combining two real floating-point operands.
412 // The fun begins when size promotion occur across type domains.
413 // From H&S 6.3.4: When one operand is complex and the other is a real
414 // floating-point type, the less precise type is converted, within it's
415 // real or complex domain, to the precision of the other type. For example,
416 // when combining a "long double" with a "double _Complex", the
417 // "double _Complex" is promoted to "long double _Complex".
418 int result = Context.getFloatingTypeOrder(lhs, rhs);
419
420 if (result > 0) { // The left side is bigger, convert rhs.
421 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000422 } else if (result < 0) { // The right side is bigger, convert lhs.
423 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000424 }
425 // At this point, lhs and rhs have the same rank/size. Now, make sure the
426 // domains match. This is a requirement for our implementation, C99
427 // does not require this promotion.
428 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
429 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000430 return rhs;
431 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000432 return lhs;
433 }
434 }
435 return lhs; // The domain/size match exactly.
436 }
437 // Now handle "real" floating types (i.e. float, double, long double).
438 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
439 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000440 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000441 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000442 return lhs;
443 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000444 if (rhs->isComplexIntegerType()) {
445 // convert rhs to the complex floating point type.
446 return Context.getComplexType(lhs);
447 }
448 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000449 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000450 return rhs;
451 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000452 if (lhs->isComplexIntegerType()) {
453 // convert lhs to the complex floating point type.
454 return Context.getComplexType(rhs);
455 }
Chris Lattner299b8842008-07-25 21:10:04 +0000456 // We have two real floating types, float/complex combos were handled above.
457 // Convert the smaller operand to the bigger result.
458 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000459 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000460 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000461 assert(result < 0 && "illegal float comparison");
462 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000463 }
464 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
465 // Handle GCC complex int extension.
466 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
467 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
468
469 if (lhsComplexInt && rhsComplexInt) {
470 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000471 rhsComplexInt->getElementType()) >= 0)
472 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000473 return rhs;
474 } else if (lhsComplexInt && rhs->isIntegerType()) {
475 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000476 return lhs;
477 } else if (rhsComplexInt && lhs->isIntegerType()) {
478 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000479 return rhs;
480 }
481 }
482 // Finally, we have two differing integer types.
483 // The rules for this case are in C99 6.3.1.8
484 int compare = Context.getIntegerTypeOrder(lhs, rhs);
485 bool lhsSigned = lhs->isSignedIntegerType(),
486 rhsSigned = rhs->isSignedIntegerType();
487 QualType destType;
488 if (lhsSigned == rhsSigned) {
489 // Same signedness; use the higher-ranked type
490 destType = compare >= 0 ? lhs : rhs;
491 } else if (compare != (lhsSigned ? 1 : -1)) {
492 // The unsigned type has greater than or equal rank to the
493 // signed type, so use the unsigned type
494 destType = lhsSigned ? rhs : lhs;
495 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
496 // The two types are different widths; if we are here, that
497 // means the signed type is larger than the unsigned type, so
498 // use the signed type.
499 destType = lhsSigned ? lhs : rhs;
500 } else {
501 // The signed type is higher-ranked than the unsigned type,
502 // but isn't actually any bigger (like unsigned int and long
503 // on most 32-bit systems). Use the unsigned type corresponding
504 // to the signed type.
505 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
506 }
Chris Lattner299b8842008-07-25 21:10:04 +0000507 return destType;
508}
509
510//===----------------------------------------------------------------------===//
511// Semantic Analysis for various Expression Types
512//===----------------------------------------------------------------------===//
513
514
Steve Naroff87d58b42007-09-16 03:34:24 +0000515/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000516/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
517/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
518/// multiple tokens. However, the common case is that StringToks points to one
519/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520///
521Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000522Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000523 assert(NumStringToks && "Must have at least one string!");
524
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000525 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000526 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000527 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000528
529 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
530 for (unsigned i = 0; i != NumStringToks; ++i)
531 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000532
Chris Lattnera6dcce32008-02-11 00:02:17 +0000533 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000534 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000535 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000536
537 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
538 if (getLangOptions().CPlusPlus)
539 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000540
Chris Lattnera6dcce32008-02-11 00:02:17 +0000541 // Get an array type for the string, according to C99 6.4.5. This includes
542 // the nul terminator character as well as the string length for pascal
543 // strings.
544 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000545 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000546 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000549 return Owned(StringLiteral::Create(Context, Literal.GetString(),
550 Literal.GetStringLength(),
551 Literal.AnyWide, StrTy,
552 &StringTokLocs[0],
553 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000556/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
557/// CurBlock to VD should cause it to be snapshotted (as we do for auto
558/// variables defined outside the block) or false if this is not needed (e.g.
559/// for values inside the block or for globals).
560///
Chris Lattner0b464252009-04-21 22:26:47 +0000561/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
562/// up-to-date.
563///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000564static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
565 ValueDecl *VD) {
566 // If the value is defined inside the block, we couldn't snapshot it even if
567 // we wanted to.
568 if (CurBlock->TheDecl == VD->getDeclContext())
569 return false;
570
571 // If this is an enum constant or function, it is constant, don't snapshot.
572 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
573 return false;
574
575 // If this is a reference to an extern, static, or global variable, no need to
576 // snapshot it.
577 // FIXME: What about 'const' variables in C++?
578 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000579 if (!Var->hasLocalStorage())
580 return false;
581
582 // Blocks that have these can't be constant.
583 CurBlock->hasBlockDeclRefExprs = true;
584
585 // If we have nested blocks, the decl may be declared in an outer block (in
586 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
587 // be defined outside all of the current blocks (in which case the blocks do
588 // all get the bit). Walk the nesting chain.
589 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
590 NextBlock = NextBlock->PrevBlockInfo) {
591 // If we found the defining block for the variable, don't mark the block as
592 // having a reference outside it.
593 if (NextBlock->TheDecl == VD->getDeclContext())
594 break;
595
596 // Otherwise, the DeclRef from the inner block causes the outer one to need
597 // a snapshot as well.
598 NextBlock->hasBlockDeclRefExprs = true;
599 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000600
601 return true;
602}
603
604
605
Steve Naroff0acc9c92007-09-15 18:49:24 +0000606/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000607/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000608/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000610/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
612 IdentifierInfo &II,
613 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000614 const CXXScopeSpec *SS,
615 bool isAddressOfOperand) {
616 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000617 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618}
619
Douglas Gregor566782a2009-01-06 05:10:23 +0000620/// BuildDeclRefExpr - Build either a DeclRefExpr or a
621/// QualifiedDeclRefExpr based on whether or not SS is a
622/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000623Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000624Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
625 bool TypeDependent, bool ValueDependent,
626 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000627 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
628 Diag(Loc,
629 diag::err_auto_variable_cannot_appear_in_own_initializer)
630 << D->getDeclName();
631 return ExprError();
632 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000633
634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
635 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
636 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
637 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
638 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
639 << D->getIdentifier() << FD->getDeclName();
640 Diag(D->getLocation(), diag::note_local_variable_declared_here)
641 << D->getIdentifier();
642 return ExprError();
643 }
644 }
645 }
646 }
647
Douglas Gregor98189262009-06-19 23:52:42 +0000648 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000649
650 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000651 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000652 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
653 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000654 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000655 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000656 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
657
658 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000659}
660
Douglas Gregor723d3332009-01-07 00:43:41 +0000661/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
662/// variable corresponding to the anonymous union or struct whose type
663/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000664static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
665 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000666 assert(Record->isAnonymousStructOrUnion() &&
667 "Record must be an anonymous struct or union!");
668
Mike Stumpe127ae32009-05-16 07:39:55 +0000669 // FIXME: Once Decls are directly linked together, this will be an O(1)
670 // operation rather than a slow walk through DeclContext's vector (which
671 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000672 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000673 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
674 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000675 D != DEnd; ++D) {
676 if (*D == Record) {
677 // The object for the anonymous struct/union directly
678 // follows its type in the list of declarations.
679 ++D;
680 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000681 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000682 return *D;
683 }
684 }
685
686 assert(false && "Missing object for anonymous record");
687 return 0;
688}
689
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000690/// \brief Given a field that represents a member of an anonymous
691/// struct/union, build the path from that field's context to the
692/// actual member.
693///
694/// Construct the sequence of field member references we'll have to
695/// perform to get to the field in the anonymous union/struct. The
696/// list of members is built from the field outward, so traverse it
697/// backwards to go from an object in the current context to the field
698/// we found.
699///
700/// \returns The variable from which the field access should begin,
701/// for an anonymous struct/union that is not a member of another
702/// class. Otherwise, returns NULL.
703VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
704 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000705 assert(Field->getDeclContext()->isRecord() &&
706 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
707 && "Field must be stored inside an anonymous struct or union");
708
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000709 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000710 VarDecl *BaseObject = 0;
711 DeclContext *Ctx = Field->getDeclContext();
712 do {
713 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000714 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000715 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000716 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000717 else {
718 BaseObject = cast<VarDecl>(AnonObject);
719 break;
720 }
721 Ctx = Ctx->getParent();
722 } while (Ctx->isRecord() &&
723 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000724
725 return BaseObject;
726}
727
728Sema::OwningExprResult
729Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
730 FieldDecl *Field,
731 Expr *BaseObjectExpr,
732 SourceLocation OpLoc) {
733 llvm::SmallVector<FieldDecl *, 4> AnonFields;
734 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
735 AnonFields);
736
Douglas Gregor723d3332009-01-07 00:43:41 +0000737 // Build the expression that refers to the base object, from
738 // which we will build a sequence of member references to each
739 // of the anonymous union objects and, eventually, the field we
740 // found via name lookup.
741 bool BaseObjectIsPointer = false;
742 unsigned ExtraQuals = 0;
743 if (BaseObject) {
744 // BaseObject is an anonymous struct/union variable (and is,
745 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000746 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000747 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000748 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000749 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000750 ExtraQuals
751 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
752 } else if (BaseObjectExpr) {
753 // The caller provided the base object expression. Determine
754 // whether its a pointer and whether it adds any qualifiers to the
755 // anonymous struct/union fields we're looking into.
756 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000757 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000758 BaseObjectIsPointer = true;
759 ObjectType = ObjectPtr->getPointeeType();
760 }
761 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
762 } else {
763 // We've found a member of an anonymous struct/union that is
764 // inside a non-anonymous struct/union, so in a well-formed
765 // program our base object expression is "this".
766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
767 if (!MD->isStatic()) {
768 QualType AnonFieldType
769 = Context.getTagDeclType(
770 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
771 QualType ThisType = Context.getTagDeclType(MD->getParent());
772 if ((Context.getCanonicalType(AnonFieldType)
773 == Context.getCanonicalType(ThisType)) ||
774 IsDerivedFrom(ThisType, AnonFieldType)) {
775 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000776 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000777 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000778 BaseObjectIsPointer = true;
779 }
780 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000781 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
782 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000783 }
784 ExtraQuals = MD->getTypeQualifiers();
785 }
786
787 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000788 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
789 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000790 }
791
792 // Build the implicit member references to the field of the
793 // anonymous struct/union.
794 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000795 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000796 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
797 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
798 FI != FIEnd; ++FI) {
799 QualType MemberType = (*FI)->getType();
800 if (!(*FI)->isMutable()) {
801 unsigned combinedQualifiers
802 = MemberType.getCVRQualifiers() | ExtraQuals;
803 MemberType = MemberType.getQualifiedType(combinedQualifiers);
804 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000805 if (BaseAddrSpace != MemberType.getAddressSpace())
806 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000807 MarkDeclarationReferenced(Loc, *FI);
Steve Naroff774e4152009-01-21 00:14:39 +0000808 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
809 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000810 BaseObjectIsPointer = false;
811 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000812 }
813
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000815}
816
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000817/// ActOnDeclarationNameExpr - The parser has read some kind of name
818/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
819/// performs lookup on that name and returns an expression that refers
820/// to that name. This routine isn't directly called from the parser,
821/// because the parser doesn't know about DeclarationName. Rather,
822/// this routine is called by ActOnIdentifierExpr,
823/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
824/// which form the DeclarationName from the corresponding syntactic
825/// forms.
826///
827/// HasTrailingLParen indicates whether this identifier is used in a
828/// function call context. LookupCtx is only used for a C++
829/// qualified-id (foo::bar) to indicate the class or namespace that
830/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000831///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000832/// isAddressOfOperand means that this expression is the direct operand
833/// of an address-of operator. This matters because this is the only
834/// situation where a qualified name referencing a non-static member may
835/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000836Sema::OwningExprResult
837Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
838 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000839 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000840 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000841 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000842 if (SS && SS->isInvalid())
843 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000844
845 // C++ [temp.dep.expr]p3:
846 // An id-expression is type-dependent if it contains:
847 // -- a nested-name-specifier that contains a class-name that
848 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000849 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000850 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000851 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
852 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000853 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
854 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000855 }
856
Douglas Gregor411889e2009-02-13 23:20:09 +0000857 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
858 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000859
Sebastian Redlcd883f72009-01-18 18:53:16 +0000860 if (Lookup.isAmbiguous()) {
861 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
862 SS && SS->isSet() ? SS->getRange()
863 : SourceRange());
864 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000865 }
866
867 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000868
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000869 // If this reference is in an Objective-C method, then ivar lookup happens as
870 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000871 IdentifierInfo *II = Name.getAsIdentifierInfo();
872 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000873 // There are two cases to handle here. 1) scoped lookup could have failed,
874 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000875 // found a decl, but that decl is outside the current instance method (i.e.
876 // a global variable). In these two cases, we do a lookup for an ivar with
877 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000878 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000879 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000880 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000881 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000882 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000883 if (DiagnoseUseOfDecl(IV, Loc))
884 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000885
886 // If we're referencing an invalid decl, just return this as a silent
887 // error node. The error diagnostic was already emitted on the decl.
888 if (IV->isInvalidDecl())
889 return ExprError();
890
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000891 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
892 // If a class method attemps to use a free standing ivar, this is
893 // an error.
894 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
895 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
896 << IV->getDeclName());
897 // If a class method uses a global variable, even if an ivar with
898 // same name exists, use the global.
899 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000900 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
901 ClassDeclared != IFace)
902 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000903 // FIXME: This should use a new expr for a direct reference, don't
904 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000905 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000906 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
907 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000908 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000909 return Owned(new (Context)
910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000911 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000912 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000913 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000914 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000915 // We should warn if a local variable hides an ivar.
916 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000917 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000918 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000919 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
920 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000921 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000922 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000923 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000924 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000925 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000926 QualType T;
927
928 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000929 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
930 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000931 else
932 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000933 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000934 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000935 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000936
Douglas Gregoraa57e862009-02-18 21:56:37 +0000937 // Determine whether this name might be a candidate for
938 // argument-dependent lookup.
939 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
940 HasTrailingLParen;
941
942 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000943 // We've seen something of the form
944 //
945 // identifier(
946 //
947 // and we did not find any entity by the name
948 // "identifier". However, this identifier is still subject to
949 // argument-dependent lookup, so keep track of the name.
950 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
951 Context.OverloadTy,
952 Loc));
953 }
954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 if (D == 0) {
956 // Otherwise, this could be an implicitly declared function reference (legal
957 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000958 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000959 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000960 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000961 else {
962 // If this name wasn't predeclared and if this is not a function call,
963 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000964 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
966 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000967 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
968 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc, diag::err_undeclared_use)
970 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000971 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000972 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000973 }
974 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000975
976 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
977 // Warn about constructs like:
978 // if (void *X = foo()) { ... } else { X }.
979 // In the else block, the pointer is always false.
980
981 // FIXME: In a template instantiation, we don't have scope
982 // information to check this property.
983 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
984 Scope *CheckS = S;
985 while (CheckS) {
986 if (CheckS->isWithinElse() &&
987 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
988 if (Var->getType()->isBooleanType())
989 ExprError(Diag(Loc, diag::warn_value_always_false)
990 << Var->getDeclName());
991 else
992 ExprError(Diag(Loc, diag::warn_value_always_zero)
993 << Var->getDeclName());
994 break;
995 }
996
997 // Move up one more control parent to check again.
998 CheckS = CheckS->getControlParent();
999 if (CheckS)
1000 CheckS = CheckS->getParent();
1001 }
1002 }
1003 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1004 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1005 // C99 DR 316 says that, if a function type comes from a
1006 // function definition (without a prototype), that type is only
1007 // used for checking compatibility. Therefore, when referencing
1008 // the function, we pretend that we don't have the full function
1009 // type.
1010 if (DiagnoseUseOfDecl(Func, Loc))
1011 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +00001012
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001013 QualType T = Func->getType();
1014 QualType NoProtoType = T;
1015 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1016 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
1017 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
1018 }
1019 }
1020
1021 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
1022}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001023/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001024bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001025Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1026 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
1027 if (CXXRecordDecl *RD =
1028 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
1029 QualType DestType =
1030 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001031 if (DestType->isDependentType() || From->getType()->isDependentType())
1032 return false;
1033 QualType FromRecordType = From->getType();
1034 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001035 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001036 DestType = Context.getPointerType(DestType);
1037 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001038 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001039 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1040 CheckDerivedToBaseConversion(FromRecordType,
1041 DestRecordType,
1042 From->getSourceRange().getBegin(),
1043 From->getSourceRange()))
1044 return true;
Anders Carlsson85186942009-07-31 01:23:52 +00001045 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1046 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001047 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001048 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001049}
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001050
1051/// \brief Complete semantic analysis for a reference to the given declaration.
1052Sema::OwningExprResult
1053Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
1054 bool HasTrailingLParen,
1055 const CXXScopeSpec *SS,
1056 bool isAddressOfOperand) {
1057 assert(D && "Cannot refer to a NULL declaration");
1058 DeclarationName Name = D->getDeclName();
1059
Sebastian Redl0c9da212009-02-03 20:19:35 +00001060 // If this is an expression of the form &Class::member, don't build an
1061 // implicit member ref, because we want a pointer to the member in general,
1062 // not any specific instance's member.
1063 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001064 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +00001065 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +00001066 QualType DType;
1067 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1068 DType = FD->getType().getNonReferenceType();
1069 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1070 DType = Method->getType();
1071 } else if (isa<OverloadedFunctionDecl>(D)) {
1072 DType = Context.OverloadTy;
1073 }
1074 // Could be an inner type. That's diagnosed below, so ignore it here.
1075 if (!DType.isNull()) {
1076 // The pointer is type- and value-dependent if it points into something
1077 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +00001078 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +00001079 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +00001080 }
1081 }
1082 }
1083
Douglas Gregor723d3332009-01-07 00:43:41 +00001084 // We may have found a field within an anonymous union or struct
1085 // (C++ [class.union]).
1086 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
1087 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1088 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089
Douglas Gregor3257fb52008-12-22 05:46:06 +00001090 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1091 if (!MD->isStatic()) {
1092 // C++ [class.mfct.nonstatic]p2:
1093 // [...] if name lookup (3.4.1) resolves the name in the
1094 // id-expression to a nonstatic nontype member of class X or of
1095 // a base class of X, the id-expression is transformed into a
1096 // class member access expression (5.2.5) using (*this) (9.3.2)
1097 // as the postfix-expression to the left of the '.' operator.
1098 DeclContext *Ctx = 0;
1099 QualType MemberType;
1100 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1101 Ctx = FD->getDeclContext();
1102 MemberType = FD->getType();
1103
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001104 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +00001105 MemberType = RefType->getPointeeType();
1106 else if (!FD->isMutable()) {
1107 unsigned combinedQualifiers
1108 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
1109 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1110 }
1111 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1112 if (!Method->isStatic()) {
1113 Ctx = Method->getParent();
1114 MemberType = Method->getType();
1115 }
1116 } else if (OverloadedFunctionDecl *Ovl
1117 = dyn_cast<OverloadedFunctionDecl>(D)) {
1118 for (OverloadedFunctionDecl::function_iterator
1119 Func = Ovl->function_begin(),
1120 FuncEnd = Ovl->function_end();
1121 Func != FuncEnd; ++Func) {
1122 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1123 if (!DMethod->isStatic()) {
1124 Ctx = Ovl->getDeclContext();
1125 MemberType = Context.OverloadTy;
1126 break;
1127 }
1128 }
1129 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001130
1131 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001132 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1133 QualType ThisType = Context.getTagDeclType(MD->getParent());
1134 if ((Context.getCanonicalType(CtxType)
1135 == Context.getCanonicalType(ThisType)) ||
1136 IsDerivedFrom(ThisType, CtxType)) {
1137 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001138 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001139 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001140 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001141 if (PerformObjectMemberConversion(This, D))
1142 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001143 if (DiagnoseUseOfDecl(D, Loc))
1144 return ExprError();
Douglas Gregor09be81b2009-02-04 17:27:36 +00001145 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001146 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001147 }
1148 }
1149 }
1150 }
1151
Douglas Gregor8acb7272008-12-11 16:49:14 +00001152 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001153 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1154 if (MD->isStatic())
1155 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001156 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1157 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001158 }
1159
Douglas Gregor3257fb52008-12-22 05:46:06 +00001160 // Any other ways we could have found the field in a well-formed
1161 // program would have been turned into implicit member expressions
1162 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001163 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1164 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001165 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001168 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001169 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001170 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001171 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
Steve Naroffd6163f32008-09-05 22:11:13 +00001174 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001175 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001176 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1177 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001178 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001179 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1180 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001181 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001182
Douglas Gregoraa57e862009-02-18 21:56:37 +00001183 // Check whether this declaration can be used. Note that we suppress
1184 // this check when we're going to perform argument-dependent lookup
1185 // on this function name, because this might not be the function
1186 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001187 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1188 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001189 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1190 return ExprError();
1191
Steve Naroffd6163f32008-09-05 22:11:13 +00001192 // Only create DeclRefExpr's for valid Decl's.
1193 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001194 return ExprError();
1195
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001196 // If the identifier reference is inside a block, and it refers to a value
1197 // that is outside the block, create a BlockDeclRefExpr instead of a
1198 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1199 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001200 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001201 // We do not do this for things like enum constants, global variables, etc,
1202 // as they do not get snapshotted.
1203 //
1204 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001205 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001206 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001207 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001208 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001209 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001210 // This is to record that a 'const' was actually synthesize and added.
1211 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001212 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001213
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001214 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001215 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1216 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001217 }
1218 // If this reference is not in a block or if the referenced variable is
1219 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001220
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001221 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001222 bool ValueDependent = false;
1223 if (getLangOptions().CPlusPlus) {
1224 // C++ [temp.dep.expr]p3:
1225 // An id-expression is type-dependent if it contains:
1226 // - an identifier that was declared with a dependent type,
1227 if (VD->getType()->isDependentType())
1228 TypeDependent = true;
1229 // - FIXME: a template-id that is dependent,
1230 // - a conversion-function-id that specifies a dependent type,
1231 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1232 Name.getCXXNameType()->isDependentType())
1233 TypeDependent = true;
1234 // - a nested-name-specifier that contains a class-name that
1235 // names a dependent type.
1236 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001237 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001238 DC; DC = DC->getParent()) {
1239 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001240 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001241 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1242 if (Context.getTypeDeclType(Record)->isDependentType()) {
1243 TypeDependent = true;
1244 break;
1245 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001246 }
1247 }
1248 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001249
Douglas Gregora5d84612008-12-10 20:57:37 +00001250 // C++ [temp.dep.constexpr]p2:
1251 //
1252 // An identifier is value-dependent if it is:
1253 // - a name declared with a dependent type,
1254 if (TypeDependent)
1255 ValueDependent = true;
1256 // - the name of a non-type template parameter,
1257 else if (isa<NonTypeTemplateParmDecl>(VD))
1258 ValueDependent = true;
1259 // - a constant with integral or enumeration type and is
1260 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001261 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1262 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1263 Dcl->getInit()) {
1264 ValueDependent = Dcl->getInit()->isValueDependent();
1265 }
1266 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001267 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001268
Anders Carlsson4571d812009-06-24 00:10:43 +00001269 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1270 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Sebastian Redlcd883f72009-01-18 18:53:16 +00001273Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1274 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001275 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001276
Chris Lattner4b009652007-07-25 00:24:17 +00001277 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001278 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001279 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1280 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1281 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001282 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001283
Chris Lattner7e637512008-01-12 08:14:25 +00001284 // Pre-defined identifiers are of type char[x], where x is the length of the
1285 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001286 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001287 if (FunctionDecl *FD = getCurFunctionDecl())
1288 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001289 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1290 Length = MD->getSynthesizedMethodSize();
1291 else {
1292 Diag(Loc, diag::ext_predef_outside_function);
1293 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1294 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1295 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001296
1297
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001298 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001299 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001300 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001301 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001302}
1303
Sebastian Redlcd883f72009-01-18 18:53:16 +00001304Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001305 llvm::SmallString<16> CharBuffer;
1306 CharBuffer.resize(Tok.getLength());
1307 const char *ThisTokBegin = &CharBuffer[0];
1308 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001309
Chris Lattner4b009652007-07-25 00:24:17 +00001310 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1311 Tok.getLocation(), PP);
1312 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001313 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001314
1315 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1316
Sebastian Redl75324932009-01-20 22:23:13 +00001317 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1318 Literal.isWide(),
1319 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001320}
1321
Sebastian Redlcd883f72009-01-18 18:53:16 +00001322Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1323 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001324 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1325 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001326 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001327 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001328 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001329 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001330 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001331
Chris Lattner4b009652007-07-25 00:24:17 +00001332 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001333 // Add padding so that NumericLiteralParser can overread by one character.
1334 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001335 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001336
Chris Lattner4b009652007-07-25 00:24:17 +00001337 // Get the spelling of the token, which eliminates trigraphs, etc.
1338 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1341 Tok.getLocation(), PP);
1342 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001343 return ExprError();
1344
Chris Lattner1de66eb2007-08-26 03:42:43 +00001345 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001346
Chris Lattner1de66eb2007-08-26 03:42:43 +00001347 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001348 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001349 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001350 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001351 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001352 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001353 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001354 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001355
1356 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1357
Ted Kremenekddedbe22007-11-29 00:56:49 +00001358 // isExact will be set by GetFloatValue().
1359 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001360 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1361 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001362
Chris Lattner1de66eb2007-08-26 03:42:43 +00001363 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001364 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001365 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001366 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001367
Neil Booth7421e9c2007-08-29 22:00:19 +00001368 // long long is a C99 feature.
1369 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001370 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001371 Diag(Tok.getLocation(), diag::ext_longlong);
1372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001374 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001375
Chris Lattner4b009652007-07-25 00:24:17 +00001376 if (Literal.GetIntegerValue(ResultVal)) {
1377 // If this value didn't fit into uintmax_t, warn and force to ull.
1378 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001379 Ty = Context.UnsignedLongLongTy;
1380 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001381 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001382 } else {
1383 // If this value fits into a ULL, try to figure out what else it fits into
1384 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001385
Chris Lattner4b009652007-07-25 00:24:17 +00001386 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1387 // be an unsigned int.
1388 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1389
1390 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001391 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001392 if (!Literal.isLong && !Literal.isLongLong) {
1393 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001394 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001395
Chris Lattner4b009652007-07-25 00:24:17 +00001396 // Does it fit in a unsigned int?
1397 if (ResultVal.isIntN(IntSize)) {
1398 // Does it fit in a signed int?
1399 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001400 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001401 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001402 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001403 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001404 }
Chris Lattner4b009652007-07-25 00:24:17 +00001405 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001408 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001409 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001410
Chris Lattner4b009652007-07-25 00:24:17 +00001411 // Does it fit in a unsigned long?
1412 if (ResultVal.isIntN(LongSize)) {
1413 // Does it fit in a signed long?
1414 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001415 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001416 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001417 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001418 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001419 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001420 }
1421
Chris Lattner4b009652007-07-25 00:24:17 +00001422 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001423 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001424 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001425
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // Does it fit in a unsigned long long?
1427 if (ResultVal.isIntN(LongLongSize)) {
1428 // Does it fit in a signed long long?
1429 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001430 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001431 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001432 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001433 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
1435 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001436
Chris Lattner4b009652007-07-25 00:24:17 +00001437 // If we still couldn't decide a type, we probably have something that
1438 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001439 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001441 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001442 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001443 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001444
Chris Lattnere4068872008-05-09 05:59:00 +00001445 if (ResultVal.getBitWidth() != Width)
1446 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
Sebastian Redl75324932009-01-20 22:23:13 +00001448 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001449 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001450
Chris Lattner1de66eb2007-08-26 03:42:43 +00001451 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1452 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001453 Res = new (Context) ImaginaryLiteral(Res,
1454 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001455
1456 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001457}
1458
Sebastian Redlcd883f72009-01-18 18:53:16 +00001459Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1460 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001461 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001462 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001463 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001464}
1465
1466/// The UsualUnaryConversions() function is *not* called by this routine.
1467/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001468bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001469 SourceLocation OpLoc,
1470 const SourceRange &ExprRange,
1471 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001472 if (exprType->isDependentType())
1473 return false;
1474
Chris Lattner4b009652007-07-25 00:24:17 +00001475 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001476 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001477 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001478 if (isSizeof)
1479 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1480 return false;
1481 }
1482
Chris Lattner95933c12009-04-24 00:30:45 +00001483 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001484 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001485 Diag(OpLoc, diag::ext_sizeof_void_type)
1486 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001487 return false;
1488 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001489
Chris Lattner95933c12009-04-24 00:30:45 +00001490 if (RequireCompleteType(OpLoc, exprType,
1491 isSizeof ? diag::err_sizeof_incomplete_type :
1492 diag::err_alignof_incomplete_type,
1493 ExprRange))
1494 return true;
1495
1496 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001497 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001498 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001499 << exprType << isSizeof << ExprRange;
1500 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001501 }
1502
Chris Lattner95933c12009-04-24 00:30:45 +00001503 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001504}
1505
Chris Lattner8d9f7962009-01-24 20:17:12 +00001506bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1507 const SourceRange &ExprRange) {
1508 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001509
Chris Lattner8d9f7962009-01-24 20:17:12 +00001510 // alignof decl is always ok.
1511 if (isa<DeclRefExpr>(E))
1512 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001513
1514 // Cannot know anything else if the expression is dependent.
1515 if (E->isTypeDependent())
1516 return false;
1517
Douglas Gregor531434b2009-05-02 02:18:30 +00001518 if (E->getBitField()) {
1519 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1520 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001521 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001522
1523 // Alignment of a field access is always okay, so long as it isn't a
1524 // bit-field.
1525 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001526 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001527 return false;
1528
Chris Lattner8d9f7962009-01-24 20:17:12 +00001529 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1530}
1531
Douglas Gregor396f1142009-03-13 21:01:28 +00001532/// \brief Build a sizeof or alignof expression given a type operand.
1533Action::OwningExprResult
1534Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1535 bool isSizeOf, SourceRange R) {
1536 if (T.isNull())
1537 return ExprError();
1538
1539 if (!T->isDependentType() &&
1540 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1541 return ExprError();
1542
1543 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1544 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1545 Context.getSizeType(), OpLoc,
1546 R.getEnd()));
1547}
1548
1549/// \brief Build a sizeof or alignof expression given an expression
1550/// operand.
1551Action::OwningExprResult
1552Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1553 bool isSizeOf, SourceRange R) {
1554 // Verify that the operand is valid.
1555 bool isInvalid = false;
1556 if (E->isTypeDependent()) {
1557 // Delay type-checking for type-dependent expressions.
1558 } else if (!isSizeOf) {
1559 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001560 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001561 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1562 isInvalid = true;
1563 } else {
1564 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1565 }
1566
1567 if (isInvalid)
1568 return ExprError();
1569
1570 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1571 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1572 Context.getSizeType(), OpLoc,
1573 R.getEnd()));
1574}
1575
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001576/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1577/// the same for @c alignof and @c __alignof
1578/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001579Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001580Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1581 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001584
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001585 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001586 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1587 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1588 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001589
Douglas Gregor396f1142009-03-13 21:01:28 +00001590 // Get the end location.
1591 Expr *ArgEx = (Expr *)TyOrEx;
1592 Action::OwningExprResult Result
1593 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1594
1595 if (Result.isInvalid())
1596 DeleteExpr(ArgEx);
1597
1598 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001599}
1600
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001601QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001602 if (V->isTypeDependent())
1603 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001604
Chris Lattnera16e42d2007-08-26 05:39:26 +00001605 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001606 if (const ComplexType *CT = V->getType()->getAsComplexType())
1607 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001608
1609 // Otherwise they pass through real integer and floating point types here.
1610 if (V->getType()->isArithmeticType())
1611 return V->getType();
1612
1613 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001614 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1615 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001616 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001617}
1618
1619
Chris Lattner4b009652007-07-25 00:24:17 +00001620
Sebastian Redl8b769972009-01-19 00:08:26 +00001621Action::OwningExprResult
1622Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1623 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001624 // Since this might be a postfix expression, get rid of ParenListExprs.
1625 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001626 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001627
Chris Lattner4b009652007-07-25 00:24:17 +00001628 UnaryOperator::Opcode Opc;
1629 switch (Kind) {
1630 default: assert(0 && "Unknown unary op!");
1631 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1632 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1633 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001634
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001635 if (getLangOptions().CPlusPlus &&
1636 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1637 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001638 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001639 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1640
1641 // C++ [over.inc]p1:
1642 //
1643 // [...] If the function is a member function with one
1644 // parameter (which shall be of type int) or a non-member
1645 // function with two parameters (the second of which shall be
1646 // of type int), it defines the postfix increment operator ++
1647 // for objects of that type. When the postfix increment is
1648 // called as a result of using the ++ operator, the int
1649 // argument will have value zero.
1650 Expr *Args[2] = {
1651 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001652 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1653 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001654 };
1655
1656 // Build the candidate set for overloading
1657 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001658 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001659
1660 // Perform overload resolution.
1661 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001662 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001663 case OR_Success: {
1664 // We found a built-in operator or an overloaded operator.
1665 FunctionDecl *FnDecl = Best->Function;
1666
1667 if (FnDecl) {
1668 // We matched an overloaded operator. Build a call to that
1669 // operator.
1670
1671 // Convert the arguments.
1672 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1673 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001675 } else {
1676 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001677 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001678 FnDecl->getParamDecl(0)->getType(),
1679 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001680 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001681 }
1682
1683 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001685 = FnDecl->getType()->getAsFunctionType()->getResultType();
1686 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001687
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001688 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001689 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001690 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001691 UsualUnaryConversions(FnExpr);
1692
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001694 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001695 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1696 Args, 2, ResultTy,
1697 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001698 } else {
1699 // We matched a built-in operator. Convert the arguments, then
1700 // break out so that we will build the appropriate built-in
1701 // operator node.
1702 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1703 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001704 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001705
1706 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001707 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001708 }
1709
1710 case OR_No_Viable_Function:
1711 // No viable function; fall through to handling this as a
1712 // built-in operator, which will produce an error message for us.
1713 break;
1714
1715 case OR_Ambiguous:
1716 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1717 << UnaryOperator::getOpcodeStr(Opc)
1718 << Arg->getSourceRange();
1719 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001720 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001721
1722 case OR_Deleted:
1723 Diag(OpLoc, diag::err_ovl_deleted_oper)
1724 << Best->Function->isDeleted()
1725 << UnaryOperator::getOpcodeStr(Opc)
1726 << Arg->getSourceRange();
1727 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1728 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001729 }
1730
1731 // Either we found no viable overloaded operator or we matched a
1732 // built-in operator. In either case, fall through to trying to
1733 // build a built-in operation.
1734 }
1735
Eli Friedman94d30952009-07-22 23:24:42 +00001736 Input.release();
1737 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001738 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001739}
1740
Sebastian Redl8b769972009-01-19 00:08:26 +00001741Action::OwningExprResult
1742Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1743 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001744 // Since this might be a postfix expression, get rid of ParenListExprs.
1745 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1746
Sebastian Redl8b769972009-01-19 00:08:26 +00001747 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1748 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001749
Douglas Gregor80723c52008-11-19 17:17:41 +00001750 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001751 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1752 Base.release();
1753 Idx.release();
1754 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1755 Context.DependentTy, RLoc));
1756 }
1757
1758 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001759 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001760 LHSExp->getType()->isEnumeralType() ||
1761 RHSExp->getType()->isRecordType() ||
1762 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001763 // Add the appropriate overloaded operators (C++ [over.match.oper])
1764 // to the candidate set.
1765 OverloadCandidateSet CandidateSet;
1766 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001767 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1768 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001769
Douglas Gregor80723c52008-11-19 17:17:41 +00001770 // Perform overload resolution.
1771 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001772 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001773 case OR_Success: {
1774 // We found a built-in operator or an overloaded operator.
1775 FunctionDecl *FnDecl = Best->Function;
1776
1777 if (FnDecl) {
1778 // We matched an overloaded operator. Build a call to that
1779 // operator.
1780
1781 // Convert the arguments.
1782 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1783 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1784 PerformCopyInitialization(RHSExp,
1785 FnDecl->getParamDecl(0)->getType(),
1786 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001787 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001788 } else {
1789 // Convert the arguments.
1790 if (PerformCopyInitialization(LHSExp,
1791 FnDecl->getParamDecl(0)->getType(),
1792 "passing") ||
1793 PerformCopyInitialization(RHSExp,
1794 FnDecl->getParamDecl(1)->getType(),
1795 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001796 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001797 }
1798
1799 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001800 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001801 = FnDecl->getType()->getAsFunctionType()->getResultType();
1802 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001803
Douglas Gregor80723c52008-11-19 17:17:41 +00001804 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001805 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1806 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001807 UsualUnaryConversions(FnExpr);
1808
Sebastian Redl8b769972009-01-19 00:08:26 +00001809 Base.release();
1810 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001811 Args[0] = LHSExp;
1812 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001813 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1814 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001815 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001816 } else {
1817 // We matched a built-in operator. Convert the arguments, then
1818 // break out so that we will build the appropriate built-in
1819 // operator node.
1820 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1821 "passing") ||
1822 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1823 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001824 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001825
1826 break;
1827 }
1828 }
1829
1830 case OR_No_Viable_Function:
1831 // No viable function; fall through to handling this as a
1832 // built-in operator, which will produce an error message for us.
1833 break;
1834
1835 case OR_Ambiguous:
1836 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1837 << "[]"
1838 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1839 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001840 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001841
1842 case OR_Deleted:
1843 Diag(LLoc, diag::err_ovl_deleted_oper)
1844 << Best->Function->isDeleted()
1845 << "[]"
1846 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1847 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1848 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001849 }
1850
1851 // Either we found no viable overloaded operator or we matched a
1852 // built-in operator. In either case, fall through to trying to
1853 // build a built-in operation.
1854 }
1855
Chris Lattner4b009652007-07-25 00:24:17 +00001856 // Perform default conversions.
1857 DefaultFunctionArrayConversion(LHSExp);
1858 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001859
Chris Lattner4b009652007-07-25 00:24:17 +00001860 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1861
1862 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001863 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001864 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001865 // and index from the expression types.
1866 Expr *BaseExpr, *IndexExpr;
1867 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001868 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1869 BaseExpr = LHSExp;
1870 IndexExpr = RHSExp;
1871 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001872 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001873 BaseExpr = LHSExp;
1874 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001875 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001876 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001877 // Handle the uncommon case of "123[Ptr]".
1878 BaseExpr = RHSExp;
1879 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001880 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001881 } else if (const ObjCObjectPointerType *PTy =
1882 LHSTy->getAsObjCObjectPointerType()) {
1883 BaseExpr = LHSExp;
1884 IndexExpr = RHSExp;
1885 ResultType = PTy->getPointeeType();
1886 } else if (const ObjCObjectPointerType *PTy =
1887 RHSTy->getAsObjCObjectPointerType()) {
1888 // Handle the uncommon case of "123[Ptr]".
1889 BaseExpr = RHSExp;
1890 IndexExpr = LHSExp;
1891 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001892 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1893 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001894 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001895
Chris Lattner4b009652007-07-25 00:24:17 +00001896 // FIXME: need to deal with const...
1897 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001898 } else if (LHSTy->isArrayType()) {
1899 // If we see an array that wasn't promoted by
1900 // DefaultFunctionArrayConversion, it must be an array that
1901 // wasn't promoted because of the C90 rule that doesn't
1902 // allow promoting non-lvalue arrays. Warn, then
1903 // force the promotion here.
1904 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1905 LHSExp->getSourceRange();
1906 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1907 LHSTy = LHSExp->getType();
1908
1909 BaseExpr = LHSExp;
1910 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001911 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001912 } else if (RHSTy->isArrayType()) {
1913 // Same as previous, except for 123[f().a] case
1914 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1915 RHSExp->getSourceRange();
1916 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1917 RHSTy = RHSExp->getType();
1918
1919 BaseExpr = RHSExp;
1920 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001921 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001922 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001923 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1924 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001925 }
Chris Lattner4b009652007-07-25 00:24:17 +00001926 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001927 if (!(IndexExpr->getType()->isIntegerType() &&
1928 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001929 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1930 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001931
Douglas Gregor05e28f62009-03-24 19:52:54 +00001932 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1933 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1934 // type. Note that Functions are not objects, and that (in C99 parlance)
1935 // incomplete types are not object types.
1936 if (ResultType->isFunctionType()) {
1937 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1938 << ResultType << BaseExpr->getSourceRange();
1939 return ExprError();
1940 }
Chris Lattner95933c12009-04-24 00:30:45 +00001941
Douglas Gregor05e28f62009-03-24 19:52:54 +00001942 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001943 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001944 BaseExpr->getSourceRange()))
1945 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001946
1947 // Diagnose bad cases where we step over interface counts.
1948 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1949 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1950 << ResultType << BaseExpr->getSourceRange();
1951 return ExprError();
1952 }
1953
Sebastian Redl8b769972009-01-19 00:08:26 +00001954 Base.release();
1955 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001956 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001957 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001958}
1959
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001960QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001961CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001962 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001963 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001964
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001965 // The vector accessor can't exceed the number of elements.
1966 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001967
Mike Stump9afab102009-02-19 03:04:26 +00001968 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001969 // special names that indicate a subset of exactly half the elements are
1970 // to be selected.
1971 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001972
Nate Begeman1486b502009-01-18 01:47:54 +00001973 // This flag determines whether or not CompName has an 's' char prefix,
1974 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001975 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001976
1977 // Check that we've found one of the special components, or that the component
1978 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001979 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001980 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1981 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001982 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001983 do
1984 compStr++;
1985 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001986 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001987 do
1988 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001989 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001990 }
Nate Begeman1486b502009-01-18 01:47:54 +00001991
Mike Stump9afab102009-02-19 03:04:26 +00001992 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001993 // We didn't get to the end of the string. This means the component names
1994 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001995 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1996 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001997 return QualType();
1998 }
Mike Stump9afab102009-02-19 03:04:26 +00001999
Nate Begeman1486b502009-01-18 01:47:54 +00002000 // Ensure no component accessor exceeds the width of the vector type it
2001 // operates on.
2002 if (!HalvingSwizzle) {
2003 compStr = CompName.getName();
2004
2005 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002006 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00002007
2008 while (*compStr) {
2009 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2010 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2011 << baseType << SourceRange(CompLoc);
2012 return QualType();
2013 }
2014 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002015 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00002016
Nate Begeman1486b502009-01-18 01:47:54 +00002017 // If this is a halving swizzle, verify that the base type has an even
2018 // number of elements.
2019 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002020 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002021 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00002022 return QualType();
2023 }
Mike Stump9afab102009-02-19 03:04:26 +00002024
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002025 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00002026 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002027 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00002028 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00002029 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00002030 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
2031 : CompName.getLength();
2032 if (HexSwizzle)
2033 CompSize--;
2034
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002035 if (CompSize == 1)
2036 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002037
Nate Begemanaf6ed502008-04-18 23:10:10 +00002038 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00002039 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002040 // diagostics look bad. We want extended vector types to appear built-in.
2041 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2042 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2043 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00002044 }
2045 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002046}
2047
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002048static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2049 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002050 const Selector &Sel,
2051 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002052
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002053 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002054 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002055 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002056 return OMD;
2057
2058 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2059 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002060 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2061 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002062 return D;
2063 }
2064 return 0;
2065}
2066
Steve Naroffc75c1a82009-06-17 22:40:22 +00002067static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002068 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002069 const Selector &Sel,
2070 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002071 // Check protocols on qualified interfaces.
2072 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00002073 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002074 E = QIdTy->qual_end(); I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002075 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002076 GDecl = PD;
2077 break;
2078 }
2079 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002080 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002081 GDecl = OMD;
2082 break;
2083 }
2084 }
2085 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00002086 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002087 E = QIdTy->qual_end(); I != E; ++I) {
2088 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002089 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002090 if (GDecl)
2091 return GDecl;
2092 }
2093 }
2094 return GDecl;
2095}
Chris Lattner2cb744b2009-02-15 22:43:40 +00002096
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002097/// FindMethodInNestedImplementations - Look up a method in current and
2098/// all base class implementations.
2099///
2100ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2101 const ObjCInterfaceDecl *IFace,
2102 const Selector &Sel) {
2103 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00002104 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002105 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002106
2107 if (!Method && IFace->getSuperClass())
2108 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2109 return Method;
2110}
2111
Sebastian Redl8b769972009-01-19 00:08:26 +00002112Action::OwningExprResult
2113Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2114 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002115 IdentifierInfo &Member,
Douglas Gregorda61ad22009-08-06 03:17:00 +00002116 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2117 // FIXME: handle the CXXScopeSpec for proper lookup of qualified-ids
2118 if (SS && SS->isInvalid())
2119 return ExprError();
2120
Nate Begemane85f43d2009-08-10 23:49:36 +00002121 // Since this might be a postfix expression, get rid of ParenListExprs.
2122 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2123
Anders Carlssonc154a722009-05-01 19:30:39 +00002124 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002125 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002126
Steve Naroff137e11d2007-12-16 21:42:28 +00002127 // Perform default conversions.
2128 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002129
Steve Naroff2cb66382007-07-26 03:11:44 +00002130 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002131 // If this is an Objective-C pseudo-builtin and a definition is provided then
2132 // use that.
2133 if (BaseType->isObjCIdType()) {
2134 // We have an 'id' type. Rather than fall through, we check if this
2135 // is a reference to 'isa'.
2136 if (BaseType != Context.ObjCIdRedefinitionType) {
2137 BaseType = Context.ObjCIdRedefinitionType;
2138 ImpCastExprToType(BaseExpr, BaseType);
2139 }
2140 } else if (BaseType->isObjCClassType() &&
2141 BaseType != Context.ObjCClassRedefinitionType) {
2142 BaseType = Context.ObjCClassRedefinitionType;
2143 ImpCastExprToType(BaseExpr, BaseType);
2144 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002145 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002146
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002147 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2148 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002149 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002150 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002151 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2152 BaseExpr, true,
2153 OpLoc,
2154 DeclarationName(&Member),
2155 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002156 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002157 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002158 else if (BaseType->isObjCObjectPointerType())
2159 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002160 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002161 return ExprError(Diag(MemberLoc,
2162 diag::err_typecheck_member_reference_arrow)
2163 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002164 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002165 if (BaseType->isDependentType()) {
2166 // Require that the base type isn't a pointer type
2167 // (so we'll report an error for)
2168 // T* t;
2169 // t.f;
2170 //
2171 // In Obj-C++, however, the above expression is valid, since it could be
2172 // accessing the 'f' property if T is an Obj-C interface. The extra check
2173 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002174 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002175
2176 if (!PT || (getLangOptions().ObjC1 &&
2177 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002178 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2179 BaseExpr, false,
2180 OpLoc,
2181 DeclarationName(&Member),
2182 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002183 }
Chris Lattner4b009652007-07-25 00:24:17 +00002184 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002185
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002186 // Handle field access to simple records. This also handles access to fields
2187 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002188 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002189 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002190 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002191 diag::err_typecheck_incomplete_tag,
2192 BaseExpr->getSourceRange()))
2193 return ExprError();
2194
Douglas Gregorda61ad22009-08-06 03:17:00 +00002195 DeclContext *DC = RDecl;
2196 if (SS && SS->isSet()) {
2197 // If the member name was a qualified-id, look into the
2198 // nested-name-specifier.
2199 DC = computeDeclContext(*SS, false);
2200
2201 // FIXME: If DC is not computable, we should build a
2202 // CXXUnresolvedMemberExpr.
2203 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2204 }
2205
Steve Naroff2cb66382007-07-26 03:11:44 +00002206 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002207 LookupResult Result
Douglas Gregorda61ad22009-08-06 03:17:00 +00002208 = LookupQualifiedName(DC, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002209 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002210
Douglas Gregor12431cb2009-08-06 05:28:30 +00002211 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002212 QualType BaseTypeCanon
2213 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2214 QualType MemberTypeCanon
2215 = Context.getCanonicalType(
2216 Context.getTypeDeclType(
2217 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2218
2219 if (BaseTypeCanon != MemberTypeCanon &&
2220 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2221 return ExprError(Diag(SS->getBeginLoc(),
2222 diag::err_not_direct_base_or_virtual)
2223 << MemberTypeCanon << BaseTypeCanon);
2224 }
2225
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002226 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002227 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2228 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002229 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002230 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2231 MemberLoc, BaseExpr->getSourceRange());
2232 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002233 }
2234
2235 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002236
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002237 // If the decl being referenced had an error, return an error for this
2238 // sub-expr without emitting another error, in order to avoid cascading
2239 // error cases.
2240 if (MemberDecl->isInvalidDecl())
2241 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002242
Douglas Gregoraa57e862009-02-18 21:56:37 +00002243 // Check the use of this field
2244 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2245 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002246
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002247 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002248 // We may have found a field within an anonymous union or struct
2249 // (C++ [class.union]).
2250 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002251 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002252 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002253
Douglas Gregor82d44772008-12-20 23:49:58 +00002254 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002255 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002256 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002257 MemberType = Ref->getPointeeType();
2258 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002259 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002260 unsigned combinedQualifiers =
2261 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002262 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002263 combinedQualifiers &= ~QualType::Const;
2264 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002265 if (BaseAddrSpace != MemberType.getAddressSpace())
2266 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002267 }
Eli Friedman76b49832008-02-06 22:48:16 +00002268
Douglas Gregorcad27f62009-06-22 23:06:13 +00002269 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002270 if (PerformObjectMemberConversion(BaseExpr, FD))
2271 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002272 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2273 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002274 }
2275
Douglas Gregorcad27f62009-06-22 23:06:13 +00002276 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2277 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Steve Naroff774e4152009-01-21 00:14:39 +00002278 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002279 Var, MemberLoc,
2280 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002281 }
2282 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2283 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002284 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002285 MemberFn, MemberLoc,
2286 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002287 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002288 if (OverloadedFunctionDecl *Ovl
2289 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002290 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002291 MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002292 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2293 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002294 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2295 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002296 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002297 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002298 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2299 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002300
Douglas Gregor82d44772008-12-20 23:49:58 +00002301 // We found a declaration kind that we didn't expect. This is a
2302 // generic error message that tells the user that she can't refer
2303 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002304 return ExprError(Diag(MemberLoc,
2305 diag::err_typecheck_member_reference_unknown)
2306 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002307 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002308
Steve Naroff329ec222009-07-10 23:34:53 +00002309 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002310 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002311 // Also must look for a getter name which uses property syntax.
2312 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2313 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2314 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2315 ObjCMethodDecl *Getter;
2316 // FIXME: need to also look locally in the implementation.
2317 if ((Getter = IFace->lookupClassMethod(Sel))) {
2318 // Check the use of this method.
2319 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2320 return ExprError();
2321 }
2322 // If we found a getter then this may be a valid dot-reference, we
2323 // will look for the matching setter, in case it is needed.
2324 Selector SetterSel =
2325 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2326 PP.getSelectorTable(), &Member);
2327 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2328 if (!Setter) {
2329 // If this reference is in an @implementation, also check for 'private'
2330 // methods.
2331 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2332 }
2333 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002334 if (!Setter)
2335 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002336
2337 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2338 return ExprError();
2339
2340 if (Getter || Setter) {
2341 QualType PType;
2342
2343 if (Getter)
2344 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002345 else
2346 // Get the expression type from Setter's incoming parameter.
2347 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002348 // FIXME: we must check that the setter has property type.
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002349 return Owned(new (Context) ObjCImplctSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002350 Setter, MemberLoc, BaseExpr));
2351 }
2352 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2353 << &Member << BaseType);
2354 }
2355 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002356 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2357 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002358 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2359 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2360 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2361 const ObjCInterfaceType *IFaceT =
2362 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002363 if (IFaceT) {
2364 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2365 ObjCInterfaceDecl *ClassDeclared;
2366 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(&Member, ClassDeclared);
2367
2368 if (IV) {
2369 // If the decl being referenced had an error, return an error for this
2370 // sub-expr without emitting another error, in order to avoid cascading
2371 // error cases.
2372 if (IV->isInvalidDecl())
2373 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002374
Steve Naroff4e743962009-07-16 00:25:06 +00002375 // Check whether we can reference this field.
2376 if (DiagnoseUseOfDecl(IV, MemberLoc))
2377 return ExprError();
2378 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2379 IV->getAccessControl() != ObjCIvarDecl::Package) {
2380 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2381 if (ObjCMethodDecl *MD = getCurMethodDecl())
2382 ClassOfMethodDecl = MD->getClassInterface();
2383 else if (ObjCImpDecl && getCurFunctionDecl()) {
2384 // Case of a c-function declared inside an objc implementation.
2385 // FIXME: For a c-style function nested inside an objc implementation
2386 // class, there is no implementation context available, so we pass
2387 // down the context as argument to this routine. Ideally, this context
2388 // need be passed down in the AST node and somehow calculated from the
2389 // AST for a function decl.
2390 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2391 if (ObjCImplementationDecl *IMPD =
2392 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2393 ClassOfMethodDecl = IMPD->getClassInterface();
2394 else if (ObjCCategoryImplDecl* CatImplClass =
2395 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2396 ClassOfMethodDecl = CatImplClass->getClassInterface();
2397 }
2398
2399 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2400 if (ClassDeclared != IDecl ||
2401 ClassOfMethodDecl != ClassDeclared)
2402 Diag(MemberLoc, diag::error_private_ivar_access)
2403 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002404 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2405 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002406 Diag(MemberLoc, diag::error_protected_ivar_access)
2407 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002408 }
Steve Naroff4e743962009-07-16 00:25:06 +00002409
2410 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2411 MemberLoc, BaseExpr,
2412 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002413 }
Steve Naroff4e743962009-07-16 00:25:06 +00002414 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2415 << IDecl->getDeclName() << &Member
2416 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002417 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002418 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002419 // Handle properties on 'id' and qualified "id".
2420 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2421 BaseType->isObjCQualifiedIdType())) {
2422 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2423
Steve Naroff329ec222009-07-10 23:34:53 +00002424 // Check protocols on qualified interfaces.
2425 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2426 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2427 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2428 // Check the use of this declaration
2429 if (DiagnoseUseOfDecl(PD, MemberLoc))
2430 return ExprError();
2431
2432 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2433 MemberLoc, BaseExpr));
2434 }
2435 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2436 // Check the use of this method.
2437 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2438 return ExprError();
2439
2440 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2441 OMD->getResultType(),
2442 OMD, OpLoc, MemberLoc,
2443 NULL, 0));
2444 }
2445 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002446
Steve Naroff329ec222009-07-10 23:34:53 +00002447 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2448 << &Member << BaseType);
2449 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002450 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2451 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002452 const ObjCObjectPointerType *OPT;
2453 if (OpKind == tok::period &&
2454 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2455 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2456 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2457
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002458 // Search for a declared property first.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002459 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002460 // Check whether we can reference this property.
2461 if (DiagnoseUseOfDecl(PD, MemberLoc))
2462 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002463 QualType ResTy = PD->getType();
2464 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002465 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002466 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2467 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002468 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002469 MemberLoc, BaseExpr));
2470 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002471 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002472 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2473 E = OPT->qual_end(); I != E; ++I)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002474 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002475 // Check whether we can reference this property.
2476 if (DiagnoseUseOfDecl(PD, MemberLoc))
2477 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002478
Steve Naroff774e4152009-01-21 00:14:39 +00002479 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002480 MemberLoc, BaseExpr));
2481 }
Steve Naroff329ec222009-07-10 23:34:53 +00002482 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2483 E = OPT->qual_end(); I != E; ++I)
2484 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2485 // Check whether we can reference this property.
2486 if (DiagnoseUseOfDecl(PD, MemberLoc))
2487 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002488
Steve Naroff329ec222009-07-10 23:34:53 +00002489 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2490 MemberLoc, BaseExpr));
2491 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002492 // If that failed, look for an "implicit" property by seeing if the nullary
2493 // selector is implemented.
2494
2495 // FIXME: The logic for looking up nullary and unary selectors should be
2496 // shared with the code in ActOnInstanceMessage.
2497
2498 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002499 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002500
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002501 // If this reference is in an @implementation, check for 'private' methods.
2502 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002503 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002504
Steve Naroff04151f32008-10-22 19:16:27 +00002505 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002506 if (!Getter)
2507 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002508 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002509 // Check if we can reference this property.
2510 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2511 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002512 }
2513 // If we found a getter then this may be a valid dot-reference, we
2514 // will look for the matching setter, in case it is needed.
2515 Selector SetterSel =
2516 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2517 PP.getSelectorTable(), &Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002518 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002519 if (!Setter) {
2520 // If this reference is in an @implementation, also check for 'private'
2521 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002522 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002523 }
2524 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002525 if (!Setter)
2526 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002527
Steve Naroffdede0c92009-03-11 13:48:17 +00002528 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2529 return ExprError();
2530
2531 if (Getter || Setter) {
2532 QualType PType;
2533
2534 if (Getter)
2535 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002536 else
2537 // Get the expression type from Setter's incoming parameter.
2538 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002539 // FIXME: we must check that the setter has property type.
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002540 return Owned(new (Context) ObjCImplctSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002541 Setter, MemberLoc, BaseExpr));
2542 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002543 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2544 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002545 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002546
Steve Naroff29d293b2009-07-24 17:54:45 +00002547 // Handle the following exceptional case (*Obj).isa.
2548 if (OpKind == tok::period &&
2549 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Steve Naroffbbe4f962009-07-29 14:06:03 +00002550 Member.isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002551 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2552 Context.getObjCIdType()));
2553
Chris Lattnera57cf472008-07-21 04:28:12 +00002554 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002555 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002556 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2557 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002558 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002559 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002560 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002561 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002562
Douglas Gregor762da552009-03-27 06:00:30 +00002563 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2564 << BaseType << BaseExpr->getSourceRange();
2565
2566 // If the user is trying to apply -> or . to a function or function
2567 // pointer, it's probably because they forgot parentheses to call
2568 // the function. Suggest the addition of those parentheses.
2569 if (BaseType == Context.OverloadTy ||
2570 BaseType->isFunctionType() ||
2571 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002572 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002573 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2574 Diag(Loc, diag::note_member_reference_needs_call)
2575 << CodeModificationHint::CreateInsertion(Loc, "()");
2576 }
2577
2578 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002579}
2580
Douglas Gregor3257fb52008-12-22 05:46:06 +00002581/// ConvertArgumentsForCall - Converts the arguments specified in
2582/// Args/NumArgs to the parameter types of the function FDecl with
2583/// function prototype Proto. Call is the call expression itself, and
2584/// Fn is the function expression. For a C++ member function, this
2585/// routine does not attempt to convert the object argument. Returns
2586/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002587bool
2588Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002589 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002590 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002591 Expr **Args, unsigned NumArgs,
2592 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002593 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002594 // assignment, to the types of the corresponding parameter, ...
2595 unsigned NumArgsInProto = Proto->getNumArgs();
2596 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002597 bool Invalid = false;
2598
Douglas Gregor3257fb52008-12-22 05:46:06 +00002599 // If too few arguments are available (and we don't have default
2600 // arguments for the remaining parameters), don't make the call.
2601 if (NumArgs < NumArgsInProto) {
2602 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2603 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2604 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2605 // Use default arguments for missing arguments
2606 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002607 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002608 }
2609
2610 // If too many are passed and not variadic, error on the extras and drop
2611 // them.
2612 if (NumArgs > NumArgsInProto) {
2613 if (!Proto->isVariadic()) {
2614 Diag(Args[NumArgsInProto]->getLocStart(),
2615 diag::err_typecheck_call_too_many_args)
2616 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2617 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2618 Args[NumArgs-1]->getLocEnd());
2619 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002620 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002621 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002622 }
2623 NumArgsToCheck = NumArgsInProto;
2624 }
Mike Stump9afab102009-02-19 03:04:26 +00002625
Douglas Gregor3257fb52008-12-22 05:46:06 +00002626 // Continue to check argument types (even if we have too few/many args).
2627 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2628 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002629
Douglas Gregor3257fb52008-12-22 05:46:06 +00002630 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002631 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002632 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002633
Eli Friedman83dec9e2009-03-22 22:00:50 +00002634 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2635 ProtoArgType,
2636 diag::err_call_incomplete_argument,
2637 Arg->getSourceRange()))
2638 return true;
2639
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002640 // Pass the argument.
2641 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2642 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002643 } else {
2644 if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2645 Diag (Call->getSourceRange().getBegin(),
2646 diag::err_use_of_default_argument_to_function_declared_later) <<
2647 FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2648 Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2649 diag::note_default_argument_declared_here);
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002650 } else {
2651 Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2652
2653 // If the default expression creates temporaries, we need to
2654 // push them to the current stack of expression temporaries so they'll
2655 // be properly destroyed.
2656 if (CXXExprWithTemporaries *E
2657 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2658 assert(!E->shouldDestroyTemporaries() &&
2659 "Can't destroy temporaries in a default argument expr!");
2660 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2661 ExprTemporaries.push_back(E->getTemporary(I));
2662 }
Anders Carlssona116e6e2009-06-12 16:51:40 +00002663 }
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002664
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002665 // We already type-checked the argument, so we know it works.
Anders Carlsson3d752db2009-08-14 18:30:22 +00002666 Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(i));
Anders Carlssona116e6e2009-06-12 16:51:40 +00002667 }
2668
Douglas Gregor3257fb52008-12-22 05:46:06 +00002669 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002670
Douglas Gregor3257fb52008-12-22 05:46:06 +00002671 Call->setArg(i, Arg);
2672 }
Mike Stump9afab102009-02-19 03:04:26 +00002673
Douglas Gregor3257fb52008-12-22 05:46:06 +00002674 // If this is a variadic call, handle args passed through "...".
2675 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002676 VariadicCallType CallType = VariadicFunction;
2677 if (Fn->getType()->isBlockPointerType())
2678 CallType = VariadicBlock; // Block
2679 else if (isa<MemberExpr>(Fn))
2680 CallType = VariadicMethod;
2681
Douglas Gregor3257fb52008-12-22 05:46:06 +00002682 // Promote the arguments (C99 6.5.2.2p7).
2683 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2684 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002685 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002686 Call->setArg(i, Arg);
2687 }
2688 }
2689
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002690 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002691}
2692
Steve Naroff87d58b42007-09-16 03:34:24 +00002693/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002694/// This provides the location of the left/right parens and a list of comma
2695/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002696Action::OwningExprResult
2697Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2698 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002699 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002700 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002701
2702 // Since this might be a postfix expression, get rid of ParenListExprs.
2703 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2704
Anders Carlssonc154a722009-05-01 19:30:39 +00002705 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002706 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002707 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002708 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002709 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002710 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002711
Douglas Gregor3257fb52008-12-22 05:46:06 +00002712 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002713 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002714 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002715 // FIXME: Will need to cache the results of name lookup (including ADL) in
2716 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002717 bool Dependent = false;
2718 if (Fn->isTypeDependent())
2719 Dependent = true;
2720 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2721 Dependent = true;
2722
2723 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002724 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002725 Context.DependentTy, RParenLoc));
2726
2727 // Determine whether this is a call to an object (C++ [over.call.object]).
2728 if (Fn->getType()->isRecordType())
2729 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2730 CommaLocs, RParenLoc));
2731
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002732 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002733 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2734 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2735 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2736 isa<CXXMethodDecl>(MemDecl) ||
2737 (isa<FunctionTemplateDecl>(MemDecl) &&
2738 isa<CXXMethodDecl>(
2739 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002740 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2741 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002742 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002743 }
2744
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002745 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002746 // Also, in C++, keep track of whether we should perform argument-dependent
2747 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002748 Expr *FnExpr = Fn;
2749 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002750 bool HasExplicitTemplateArgs = 0;
2751 const TemplateArgument *ExplicitTemplateArgs = 0;
2752 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002753 while (true) {
2754 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2755 FnExpr = IcExpr->getSubExpr();
2756 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002757 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002758 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002759 ADL = false;
2760 FnExpr = PExpr->getSubExpr();
2761 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002762 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002763 == UnaryOperator::AddrOf) {
2764 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002765 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002766 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2767 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002768 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002769 break;
Mike Stump9afab102009-02-19 03:04:26 +00002770 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002771 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2772 UnqualifiedName = DepName->getName();
2773 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002774 } else if (TemplateIdRefExpr *TemplateIdRef
2775 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2776 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002777 if (!NDecl)
2778 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002779 HasExplicitTemplateArgs = true;
2780 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2781 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2782
2783 // C++ [temp.arg.explicit]p6:
2784 // [Note: For simple function names, argument dependent lookup (3.4.2)
2785 // applies even when the function name is not visible within the
2786 // scope of the call. This is because the call still has the syntactic
2787 // form of a function call (3.4.1). But when a function template with
2788 // explicit template arguments is used, the call does not have the
2789 // correct syntactic form unless there is a function template with
2790 // that name visible at the point of the call. If no such name is
2791 // visible, the call is not syntactically well-formed and
2792 // argument-dependent lookup does not apply. If some such name is
2793 // visible, argument dependent lookup applies and additional function
2794 // templates may be found in other namespaces.
2795 //
2796 // The summary of this paragraph is that, if we get to this point and the
2797 // template-id was not a qualified name, then argument-dependent lookup
2798 // is still possible.
2799 if (TemplateIdRef->getQualifier())
2800 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002801 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002802 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002803 // Any kind of name that does not refer to a declaration (or
2804 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2805 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002806 break;
2807 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002808 }
Mike Stump9afab102009-02-19 03:04:26 +00002809
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002810 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002811 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002812 if (NDecl) {
2813 FDecl = dyn_cast<FunctionDecl>(NDecl);
2814 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002815 FDecl = FunctionTemplate->getTemplatedDecl();
2816 else
Douglas Gregor28857752009-06-30 22:34:41 +00002817 FDecl = dyn_cast<FunctionDecl>(NDecl);
2818 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002819 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002820
Douglas Gregorb60eb752009-06-25 22:08:12 +00002821 if (Ovl || FunctionTemplate ||
2822 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002823 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002824 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002825 ADL = false;
2826
Douglas Gregorfcb19192009-02-11 23:02:49 +00002827 // We don't perform ADL in C.
2828 if (!getLangOptions().CPlusPlus)
2829 ADL = false;
2830
Douglas Gregorb60eb752009-06-25 22:08:12 +00002831 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002832 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2833 HasExplicitTemplateArgs,
2834 ExplicitTemplateArgs,
2835 NumExplicitTemplateArgs,
2836 LParenLoc, Args, NumArgs, CommaLocs,
2837 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002838 if (!FDecl)
2839 return ExprError();
2840
2841 // Update Fn to refer to the actual function selected.
2842 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002843 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002844 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002845 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2846 QDRExpr->getLocation(),
2847 false, false,
2848 QDRExpr->getQualifierRange(),
2849 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002850 else
Mike Stump9afab102009-02-19 03:04:26 +00002851 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002852 Fn->getSourceRange().getBegin());
2853 Fn->Destroy(Context);
2854 Fn = NewFn;
2855 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002856 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002857
2858 // Promote the function operand.
2859 UsualUnaryConversions(Fn);
2860
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002861 // Make the call expr early, before semantic checks. This guarantees cleanup
2862 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002863 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2864 Args, NumArgs,
2865 Context.BoolTy,
2866 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002867
Steve Naroffd6163f32008-09-05 22:11:13 +00002868 const FunctionType *FuncT;
2869 if (!Fn->getType()->isBlockPointerType()) {
2870 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2871 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002872 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002873 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002874 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2875 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002876 FuncT = PT->getPointeeType()->getAsFunctionType();
2877 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002878 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002879 getAsFunctionType();
2880 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002881 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002882 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2883 << Fn->getType() << Fn->getSourceRange());
2884
Eli Friedman83dec9e2009-03-22 22:00:50 +00002885 // Check for a valid return type
2886 if (!FuncT->getResultType()->isVoidType() &&
2887 RequireCompleteType(Fn->getSourceRange().getBegin(),
2888 FuncT->getResultType(),
2889 diag::err_call_incomplete_return,
2890 TheCall->getSourceRange()))
2891 return ExprError();
2892
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002893 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002894 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002895
Douglas Gregor4fa58902009-02-26 23:50:07 +00002896 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002897 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002898 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002899 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002900 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002901 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002902
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002903 if (FDecl) {
2904 // Check if we have too few/too many template arguments, based
2905 // on our knowledge of the function definition.
2906 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002907 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002908 const FunctionProtoType *Proto =
2909 Def->getType()->getAsFunctionProtoType();
2910 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2911 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2912 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2913 }
2914 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002915 }
2916
Steve Naroffdb65e052007-08-28 23:30:39 +00002917 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002918 for (unsigned i = 0; i != NumArgs; i++) {
2919 Expr *Arg = Args[i];
2920 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002921 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2922 Arg->getType(),
2923 diag::err_call_incomplete_argument,
2924 Arg->getSourceRange()))
2925 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002926 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002927 }
Chris Lattner4b009652007-07-25 00:24:17 +00002928 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002929
Douglas Gregor3257fb52008-12-22 05:46:06 +00002930 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2931 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002932 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2933 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002934
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002935 // Check for sentinels
2936 if (NDecl)
2937 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002938
Chris Lattner2e64c072007-08-10 20:18:51 +00002939 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002940 if (FDecl) {
2941 if (CheckFunctionCall(FDecl, TheCall.get()))
2942 return ExprError();
2943
2944 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2945 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2946 } else if (NDecl) {
2947 if (CheckBlockCall(NDecl, TheCall.get()))
2948 return ExprError();
2949 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002950
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002951 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002952}
2953
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002954Action::OwningExprResult
2955Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2956 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002957 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002958 QualType literalType = QualType::getFromOpaquePtr(Ty);
2959 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002960 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002961 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002962
Eli Friedman8c2173d2008-05-20 05:22:08 +00002963 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002964 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002965 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2966 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002967 } else if (!literalType->isDependentType() &&
2968 RequireCompleteType(LParenLoc, literalType,
2969 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002970 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002971 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002972
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002973 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002974 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002975 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002976
Chris Lattnere5cb5862008-12-04 23:50:19 +00002977 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002978 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002979 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002980 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002981 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002982 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002983 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002984 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002985}
2986
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002987Action::OwningExprResult
2988Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002989 SourceLocation RBraceLoc) {
2990 unsigned NumInit = initlist.size();
2991 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002992
Steve Naroff0acc9c92007-09-15 18:49:24 +00002993 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002994 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002995
Mike Stump9afab102009-02-19 03:04:26 +00002996 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002997 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002998 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002999 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00003000}
3001
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003002/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00003003bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Anders Carlsson9583fa72009-08-07 22:21:05 +00003004 CastExpr::CastKind& Kind, bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00003005 if (getLangOptions().CPlusPlus)
Anders Carlsson9583fa72009-08-07 22:21:05 +00003006 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
Sebastian Redl0e35d042009-07-25 15:41:38 +00003007
Eli Friedman01e0f652009-08-15 19:02:19 +00003008 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003009
3010 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3011 // type needs to be scalar.
3012 if (castType->isVoidType()) {
3013 // Cast to void allows any expr type.
3014 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003015 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3016 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3017 (castType->isStructureType() || castType->isUnionType())) {
3018 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00003019 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003020 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3021 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003022 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003023 } else if (castType->isUnionType()) {
3024 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003025 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003026 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003027 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003028 Field != FieldEnd; ++Field) {
3029 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3030 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3031 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3032 << castExpr->getSourceRange();
3033 break;
3034 }
3035 }
3036 if (Field == FieldEnd)
3037 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3038 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003039 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003040 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003041 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003042 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003043 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003044 }
Mike Stump9afab102009-02-19 03:04:26 +00003045 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003046 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003047 return Diag(castExpr->getLocStart(),
3048 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003049 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003050 } else if (castType->isExtVectorType()) {
3051 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003052 return true;
3053 } else if (castType->isVectorType()) {
3054 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3055 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003056 } else if (castExpr->getType()->isVectorType()) {
3057 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3058 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003059 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003060 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003061 } else if (!castType->isArithmeticType()) {
3062 QualType castExprType = castExpr->getType();
3063 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3064 return Diag(castExpr->getLocStart(),
3065 diag::err_cast_pointer_from_non_pointer_int)
3066 << castExprType << castExpr->getSourceRange();
3067 } else if (!castExpr->getType()->isArithmeticType()) {
3068 if (!castType->isIntegralType() && castType->isArithmeticType())
3069 return Diag(castExpr->getLocStart(),
3070 diag::err_cast_pointer_to_non_pointer_int)
3071 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003072 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003073 if (isa<ObjCSelectorExpr>(castExpr))
3074 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003075 return false;
3076}
3077
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003078bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003079 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003080
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003081 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003082 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003083 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003084 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003085 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003086 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003087 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003088 } else
3089 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003090 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003091 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003092
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003093 return false;
3094}
3095
Nate Begemanbd42e022009-06-26 00:50:28 +00003096bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3097 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3098
Nate Begeman9e063702009-06-27 22:05:55 +00003099 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3100 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003101 if (SrcTy->isVectorType()) {
3102 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3103 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3104 << DestTy << SrcTy << R;
3105 return false;
3106 }
3107
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003108 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003109 // conversion will take place first from scalar to elt type, and then
3110 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003111 if (SrcTy->isPointerType())
3112 return Diag(R.getBegin(),
3113 diag::err_invalid_conversion_between_vector_and_scalar)
3114 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003115 return false;
3116}
3117
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003118Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003119Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003120 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003121 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3122
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003123 assert((Ty != 0) && (Op.get() != 0) &&
3124 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003125
Nate Begemane85f43d2009-08-10 23:49:36 +00003126 Expr *castExpr = (Expr *)Op.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003127 QualType castType = QualType::getFromOpaquePtr(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003128
3129 // If the Expr being casted is a ParenListExpr, handle it specially.
3130 if (isa<ParenListExpr>(castExpr))
3131 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Chris Lattner4b009652007-07-25 00:24:17 +00003132
Anders Carlsson9583fa72009-08-07 22:21:05 +00003133 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3134 Kind))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003135 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003136
3137 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003138 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003139 Kind, castExpr, castType,
3140 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003141}
3142
Nate Begemane85f43d2009-08-10 23:49:36 +00003143/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3144/// of comma binary operators.
3145Action::OwningExprResult
3146Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3147 Expr *expr = EA.takeAs<Expr>();
3148 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3149 if (!E)
3150 return Owned(expr);
3151
3152 OwningExprResult Result(*this, E->getExpr(0));
3153
3154 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3155 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3156 Owned(E->getExpr(i)));
3157
3158 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3159}
3160
3161Action::OwningExprResult
3162Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3163 SourceLocation RParenLoc, ExprArg Op,
3164 QualType Ty) {
3165 ParenListExpr *PE = (ParenListExpr *)Op.get();
3166
3167 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3168 // then handle it as such.
3169 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3170 if (PE->getNumExprs() == 0) {
3171 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3172 return ExprError();
3173 }
3174
3175 llvm::SmallVector<Expr *, 8> initExprs;
3176 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3177 initExprs.push_back(PE->getExpr(i));
3178
3179 // FIXME: This means that pretty-printing the final AST will produce curly
3180 // braces instead of the original commas.
3181 Op.release();
3182 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3183 initExprs.size(), RParenLoc);
3184 E->setType(Ty);
3185 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3186 Owned(E));
3187 } else {
3188 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3189 // sequence of BinOp comma operators.
3190 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3191 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3192 }
3193}
3194
3195Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3196 SourceLocation R,
3197 MultiExprArg Val) {
3198 unsigned nexprs = Val.size();
3199 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3200 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3201 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3202 return Owned(expr);
3203}
3204
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003205/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3206/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003207/// C99 6.5.15
3208QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3209 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003210 // C++ is sufficiently different to merit its own checker.
3211 if (getLangOptions().CPlusPlus)
3212 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3213
Chris Lattnere2897262009-02-18 04:28:32 +00003214 UsualUnaryConversions(Cond);
3215 UsualUnaryConversions(LHS);
3216 UsualUnaryConversions(RHS);
3217 QualType CondTy = Cond->getType();
3218 QualType LHSTy = LHS->getType();
3219 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003220
3221 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003222 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3223 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3224 << CondTy;
3225 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003226 }
Mike Stump9afab102009-02-19 03:04:26 +00003227
Chris Lattner992ae932008-01-06 22:42:25 +00003228 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003229 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3230 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003231
Chris Lattner992ae932008-01-06 22:42:25 +00003232 // If both operands have arithmetic type, do the usual arithmetic conversions
3233 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003234 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3235 UsualArithmeticConversions(LHS, RHS);
3236 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003237 }
Mike Stump9afab102009-02-19 03:04:26 +00003238
Chris Lattner992ae932008-01-06 22:42:25 +00003239 // If both operands are the same structure or union type, the result is that
3240 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003241 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3242 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003243 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003244 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003245 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003246 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003247 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003248 }
Mike Stump9afab102009-02-19 03:04:26 +00003249
Chris Lattner992ae932008-01-06 22:42:25 +00003250 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003251 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003252 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3253 if (!LHSTy->isVoidType())
3254 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3255 << RHS->getSourceRange();
3256 if (!RHSTy->isVoidType())
3257 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3258 << LHS->getSourceRange();
3259 ImpCastExprToType(LHS, Context.VoidTy);
3260 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003261 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003262 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003263 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3264 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003265 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003266 RHS->isNullPointerConstant(Context)) {
3267 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3268 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003269 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003270 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003271 LHS->isNullPointerConstant(Context)) {
3272 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3273 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003274 }
David Chisnall44663db2009-08-17 16:35:33 +00003275 // Handle things like Class and struct objc_class*. Here we case the result
3276 // to the pseudo-builtin, because that will be implicitly cast back to the
3277 // redefinition type if an attempt is made to access its fields.
3278 if (LHSTy->isObjCClassType() &&
3279 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3280 ImpCastExprToType(RHS, LHSTy);
3281 return LHSTy;
3282 }
3283 if (RHSTy->isObjCClassType() &&
3284 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3285 ImpCastExprToType(LHS, RHSTy);
3286 return RHSTy;
3287 }
3288 // And the same for struct objc_object* / id
3289 if (LHSTy->isObjCIdType() &&
3290 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3291 ImpCastExprToType(RHS, LHSTy);
3292 return LHSTy;
3293 }
3294 if (RHSTy->isObjCIdType() &&
3295 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3296 ImpCastExprToType(LHS, RHSTy);
3297 return RHSTy;
3298 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003299 // Handle block pointer types.
3300 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3301 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3302 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3303 QualType destType = Context.getPointerType(Context.VoidTy);
3304 ImpCastExprToType(LHS, destType);
3305 ImpCastExprToType(RHS, destType);
3306 return destType;
3307 }
3308 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3309 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3310 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003311 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003312 // We have 2 block pointer types.
3313 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3314 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003315 return LHSTy;
3316 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003317 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003318 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3319 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003320
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003321 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3322 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003323 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3324 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3325 // In this situation, we assume void* type. No especially good
3326 // reason, but this is what gcc does, and we do have to pick
3327 // to get a consistent AST.
3328 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3329 ImpCastExprToType(LHS, incompatTy);
3330 ImpCastExprToType(RHS, incompatTy);
3331 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003332 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003333 // The block pointer types are compatible.
3334 ImpCastExprToType(LHS, LHSTy);
3335 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003336 return LHSTy;
3337 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003338 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003339 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003340
3341 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3342 // Two identical object pointer types are always compatible.
3343 return LHSTy;
3344 }
Steve Naroff329ec222009-07-10 23:34:53 +00003345 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3346 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003347 QualType compositeType = LHSTy;
3348
3349 // If both operands are interfaces and either operand can be
3350 // assigned to the other, use that type as the composite
3351 // type. This allows
3352 // xxx ? (A*) a : (B*) b
3353 // where B is a subclass of A.
3354 //
3355 // Additionally, as for assignment, if either type is 'id'
3356 // allow silent coercion. Finally, if the types are
3357 // incompatible then make sure to use 'id' as the composite
3358 // type so the result is acceptable for sending messages to.
3359
3360 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3361 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003362 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003363 compositeType = LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003364 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003365 compositeType = RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003366 } else if ((LHSTy->isObjCQualifiedIdType() ||
3367 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003368 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003369 // Need to handle "id<xx>" explicitly.
3370 // GCC allows qualified id and any Objective-C type to devolve to
3371 // id. Currently localizing to here until clear this should be
3372 // part of ObjCQualifiedIdTypesAreCompatible.
3373 compositeType = Context.getObjCIdType();
3374 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003375 compositeType = Context.getObjCIdType();
3376 } else {
3377 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3378 << LHSTy << RHSTy
3379 << LHS->getSourceRange() << RHS->getSourceRange();
3380 QualType incompatTy = Context.getObjCIdType();
3381 ImpCastExprToType(LHS, incompatTy);
3382 ImpCastExprToType(RHS, incompatTy);
3383 return incompatTy;
3384 }
3385 // The object pointer types are compatible.
3386 ImpCastExprToType(LHS, compositeType);
3387 ImpCastExprToType(RHS, compositeType);
3388 return compositeType;
3389 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003390 // Check Objective-C object pointer types and 'void *'
3391 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003392 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003393 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3394 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3395 QualType destType = Context.getPointerType(destPointee);
3396 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3397 ImpCastExprToType(RHS, destType); // promote to void*
3398 return destType;
3399 }
3400 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3401 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003402 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003403 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3404 QualType destType = Context.getPointerType(destPointee);
3405 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3406 ImpCastExprToType(LHS, destType); // promote to void*
3407 return destType;
3408 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003409 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3410 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3411 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003412 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3413 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003414
3415 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3416 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3417 // Figure out necessary qualifiers (C99 6.5.15p6)
3418 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3419 QualType destType = Context.getPointerType(destPointee);
3420 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3421 ImpCastExprToType(RHS, destType); // promote to void*
3422 return destType;
3423 }
3424 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3425 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3426 QualType destType = Context.getPointerType(destPointee);
3427 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3428 ImpCastExprToType(RHS, destType); // promote to void*
3429 return destType;
3430 }
3431
3432 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3433 // Two identical pointer types are always compatible.
3434 return LHSTy;
3435 }
3436 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3437 rhptee.getUnqualifiedType())) {
3438 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3439 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3440 // In this situation, we assume void* type. No especially good
3441 // reason, but this is what gcc does, and we do have to pick
3442 // to get a consistent AST.
3443 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3444 ImpCastExprToType(LHS, incompatTy);
3445 ImpCastExprToType(RHS, incompatTy);
3446 return incompatTy;
3447 }
3448 // The pointer types are compatible.
3449 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3450 // differently qualified versions of compatible types, the result type is
3451 // a pointer to an appropriately qualified version of the *composite*
3452 // type.
3453 // FIXME: Need to calculate the composite type.
3454 // FIXME: Need to add qualifiers
3455 ImpCastExprToType(LHS, LHSTy);
3456 ImpCastExprToType(RHS, LHSTy);
3457 return LHSTy;
3458 }
3459
3460 // GCC compatibility: soften pointer/integer mismatch.
3461 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3462 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3463 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3464 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3465 return RHSTy;
3466 }
3467 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3468 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3469 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3470 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3471 return LHSTy;
3472 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003473
Chris Lattner992ae932008-01-06 22:42:25 +00003474 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003475 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3476 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003477 return QualType();
3478}
3479
Steve Naroff87d58b42007-09-16 03:34:24 +00003480/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003481/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003482Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3483 SourceLocation ColonLoc,
3484 ExprArg Cond, ExprArg LHS,
3485 ExprArg RHS) {
3486 Expr *CondExpr = (Expr *) Cond.get();
3487 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003488
3489 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3490 // was the condition.
3491 bool isLHSNull = LHSExpr == 0;
3492 if (isLHSNull)
3493 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003494
3495 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003496 RHSExpr, QuestionLoc);
3497 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003498 return ExprError();
3499
3500 Cond.release();
3501 LHS.release();
3502 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003503 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003504 isLHSNull ? 0 : LHSExpr,
3505 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003506}
3507
Chris Lattner4b009652007-07-25 00:24:17 +00003508// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003509// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003510// routine is it effectively iqnores the qualifiers on the top level pointee.
3511// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3512// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003513Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003514Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3515 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003516
David Chisnall44663db2009-08-17 16:35:33 +00003517 if ((lhsType->isObjCClassType() &&
3518 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3519 (rhsType->isObjCClassType() &&
3520 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3521 return Compatible;
3522 }
3523
Chris Lattner4b009652007-07-25 00:24:17 +00003524 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003525 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3526 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003527
Chris Lattner4b009652007-07-25 00:24:17 +00003528 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003529 lhptee = Context.getCanonicalType(lhptee);
3530 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003531
Chris Lattner005ed752008-01-04 18:04:52 +00003532 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003533
3534 // C99 6.5.16.1p1: This following citation is common to constraints
3535 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3536 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003537 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003538 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003539 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003540
Mike Stump9afab102009-02-19 03:04:26 +00003541 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3542 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003543 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003544 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003545 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003546 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003547
Chris Lattner4ca3d772008-01-03 22:56:36 +00003548 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003549 assert(rhptee->isFunctionType());
3550 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003551 }
Mike Stump9afab102009-02-19 03:04:26 +00003552
Chris Lattner4ca3d772008-01-03 22:56:36 +00003553 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003554 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003555 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003556
3557 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003558 assert(lhptee->isFunctionType());
3559 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003560 }
Mike Stump9afab102009-02-19 03:04:26 +00003561 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003562 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003563 lhptee = lhptee.getUnqualifiedType();
3564 rhptee = rhptee.getUnqualifiedType();
3565 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3566 // Check if the pointee types are compatible ignoring the sign.
3567 // We explicitly check for char so that we catch "char" vs
3568 // "unsigned char" on systems where "char" is unsigned.
3569 if (lhptee->isCharType()) {
3570 lhptee = Context.UnsignedCharTy;
3571 } else if (lhptee->isSignedIntegerType()) {
3572 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3573 }
3574 if (rhptee->isCharType()) {
3575 rhptee = Context.UnsignedCharTy;
3576 } else if (rhptee->isSignedIntegerType()) {
3577 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3578 }
3579 if (lhptee == rhptee) {
3580 // Types are compatible ignoring the sign. Qualifier incompatibility
3581 // takes priority over sign incompatibility because the sign
3582 // warning can be disabled.
3583 if (ConvTy != Compatible)
3584 return ConvTy;
3585 return IncompatiblePointerSign;
3586 }
3587 // General pointer incompatibility takes priority over qualifiers.
3588 return IncompatiblePointer;
3589 }
Chris Lattner005ed752008-01-04 18:04:52 +00003590 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003591}
3592
Steve Naroff3454b6c2008-09-04 15:10:53 +00003593/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3594/// block pointer types are compatible or whether a block and normal pointer
3595/// are compatible. It is more restrict than comparing two function pointer
3596// types.
Mike Stump9afab102009-02-19 03:04:26 +00003597Sema::AssignConvertType
3598Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003599 QualType rhsType) {
3600 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003601
Steve Naroff3454b6c2008-09-04 15:10:53 +00003602 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003603 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3604 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003605
Steve Naroff3454b6c2008-09-04 15:10:53 +00003606 // make sure we operate on the canonical type
3607 lhptee = Context.getCanonicalType(lhptee);
3608 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003609
Steve Naroff3454b6c2008-09-04 15:10:53 +00003610 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003611
Steve Naroff3454b6c2008-09-04 15:10:53 +00003612 // For blocks we enforce that qualifiers are identical.
3613 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3614 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003615
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003616 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003617 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003618 return ConvTy;
3619}
3620
Mike Stump9afab102009-02-19 03:04:26 +00003621/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3622/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003623/// pointers. Here are some objectionable examples that GCC considers warnings:
3624///
3625/// int a, *pint;
3626/// short *pshort;
3627/// struct foo *pfoo;
3628///
3629/// pint = pshort; // warning: assignment from incompatible pointer type
3630/// a = pint; // warning: assignment makes integer from pointer without a cast
3631/// pint = a; // warning: assignment makes pointer from integer without a cast
3632/// pint = pfoo; // warning: assignment from incompatible pointer type
3633///
3634/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003635/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003636///
Chris Lattner005ed752008-01-04 18:04:52 +00003637Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003638Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003639 // Get canonical types. We're not formatting these types, just comparing
3640 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003641 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3642 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003643
3644 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003645 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003646
David Chisnall44663db2009-08-17 16:35:33 +00003647 if ((lhsType->isObjCClassType() &&
3648 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3649 (rhsType->isObjCClassType() &&
3650 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3651 return Compatible;
3652 }
3653
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003654 // If the left-hand side is a reference type, then we are in a
3655 // (rare!) case where we've allowed the use of references in C,
3656 // e.g., as a parameter type in a built-in function. In this case,
3657 // just make sure that the type referenced is compatible with the
3658 // right-hand side type. The caller is responsible for adjusting
3659 // lhsType so that the resulting expression does not have reference
3660 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003661 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003662 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003663 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003664 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003665 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003666 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3667 // to the same ExtVector type.
3668 if (lhsType->isExtVectorType()) {
3669 if (rhsType->isExtVectorType())
3670 return lhsType == rhsType ? Compatible : Incompatible;
3671 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3672 return Compatible;
3673 }
3674
Nate Begemanc5f0f652008-07-14 18:02:46 +00003675 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003676 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003677 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003678 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003679 if (getLangOptions().LaxVectorConversions &&
3680 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003681 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003682 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003683 }
3684 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003685 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003686
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003687 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003688 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003689
Chris Lattner390564e2008-04-07 06:49:41 +00003690 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003691 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003692 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003693
Chris Lattner390564e2008-04-07 06:49:41 +00003694 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003695 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003696
Steve Naroff8194a542009-07-20 17:56:53 +00003697 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003698 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003699 if (lhsType->isVoidPointerType()) // an exception to the rule.
3700 return Compatible;
3701 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003702 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003703 if (rhsType->getAs<BlockPointerType>()) {
3704 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003705 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003706
3707 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003708 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003709 return Compatible;
3710 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003711 return Incompatible;
3712 }
3713
3714 if (isa<BlockPointerType>(lhsType)) {
3715 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003716 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003717
Steve Naroffa982c712008-09-29 18:10:17 +00003718 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003719 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003720 return Compatible;
3721
Steve Naroff3454b6c2008-09-04 15:10:53 +00003722 if (rhsType->isBlockPointerType())
3723 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003724
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003725 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003726 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003727 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003728 }
Chris Lattner1853da22008-01-04 23:18:45 +00003729 return Incompatible;
3730 }
3731
Steve Naroff329ec222009-07-10 23:34:53 +00003732 if (isa<ObjCObjectPointerType>(lhsType)) {
3733 if (rhsType->isIntegerType())
3734 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003735
3736 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003737 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003738 if (rhsType->isVoidPointerType()) // an exception to the rule.
3739 return Compatible;
3740 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003741 }
3742 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003743 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3744 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003745 if (Context.typesAreCompatible(lhsType, rhsType))
3746 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003747 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3748 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003749 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003750 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003751 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003752 if (RHSPT->getPointeeType()->isVoidType())
3753 return Compatible;
3754 }
3755 // Treat block pointers as objects.
3756 if (rhsType->isBlockPointerType())
3757 return Compatible;
3758 return Incompatible;
3759 }
Chris Lattner390564e2008-04-07 06:49:41 +00003760 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003761 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003762 if (lhsType == Context.BoolTy)
3763 return Compatible;
3764
3765 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003766 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003767
Mike Stump9afab102009-02-19 03:04:26 +00003768 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003769 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003770
3771 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003772 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003773 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003774 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003775 }
Steve Naroff329ec222009-07-10 23:34:53 +00003776 if (isa<ObjCObjectPointerType>(rhsType)) {
3777 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3778 if (lhsType == Context.BoolTy)
3779 return Compatible;
3780
3781 if (lhsType->isIntegerType())
3782 return PointerToInt;
3783
Steve Naroff8194a542009-07-20 17:56:53 +00003784 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003785 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003786 if (lhsType->isVoidPointerType()) // an exception to the rule.
3787 return Compatible;
3788 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003789 }
3790 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003791 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003792 return Compatible;
3793 return Incompatible;
3794 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003795
Chris Lattner1853da22008-01-04 23:18:45 +00003796 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003797 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003798 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003799 }
3800 return Incompatible;
3801}
3802
Douglas Gregor144b06c2009-04-29 22:16:16 +00003803/// \brief Constructs a transparent union from an expression that is
3804/// used to initialize the transparent union.
3805static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3806 QualType UnionType, FieldDecl *Field) {
3807 // Build an initializer list that designates the appropriate member
3808 // of the transparent union.
3809 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3810 &E, 1,
3811 SourceLocation());
3812 Initializer->setType(UnionType);
3813 Initializer->setInitializedFieldInUnion(Field);
3814
3815 // Build a compound literal constructing a value of the transparent
3816 // union type from this initializer list.
3817 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3818 false);
3819}
3820
3821Sema::AssignConvertType
3822Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3823 QualType FromType = rExpr->getType();
3824
3825 // If the ArgType is a Union type, we want to handle a potential
3826 // transparent_union GCC extension.
3827 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003828 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003829 return Incompatible;
3830
3831 // The field to initialize within the transparent union.
3832 RecordDecl *UD = UT->getDecl();
3833 FieldDecl *InitField = 0;
3834 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003835 for (RecordDecl::field_iterator it = UD->field_begin(),
3836 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003837 it != itend; ++it) {
3838 if (it->getType()->isPointerType()) {
3839 // If the transparent union contains a pointer type, we allow:
3840 // 1) void pointer
3841 // 2) null pointer constant
3842 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003843 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003844 ImpCastExprToType(rExpr, it->getType());
3845 InitField = *it;
3846 break;
3847 }
3848
3849 if (rExpr->isNullPointerConstant(Context)) {
3850 ImpCastExprToType(rExpr, it->getType());
3851 InitField = *it;
3852 break;
3853 }
3854 }
3855
3856 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3857 == Compatible) {
3858 InitField = *it;
3859 break;
3860 }
3861 }
3862
3863 if (!InitField)
3864 return Incompatible;
3865
3866 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3867 return Compatible;
3868}
3869
Chris Lattner005ed752008-01-04 18:04:52 +00003870Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003871Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003872 if (getLangOptions().CPlusPlus) {
3873 if (!lhsType->isRecordType()) {
3874 // C++ 5.17p3: If the left operand is not of class type, the
3875 // expression is implicitly converted (C++ 4) to the
3876 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003877 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3878 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003879 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003880 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003881 }
3882
3883 // FIXME: Currently, we fall through and treat C++ classes like C
3884 // structures.
3885 }
3886
Steve Naroffcdee22d2007-11-27 17:58:44 +00003887 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3888 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003889 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003890 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003891 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003892 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003893 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003894 return Compatible;
3895 }
Mike Stump9afab102009-02-19 03:04:26 +00003896
Chris Lattner5f505bf2007-10-16 02:55:40 +00003897 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003898 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003899 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003900 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003901 //
Mike Stump9afab102009-02-19 03:04:26 +00003902 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003903 if (!lhsType->isReferenceType())
3904 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003905
Chris Lattner005ed752008-01-04 18:04:52 +00003906 Sema::AssignConvertType result =
3907 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003908
Steve Naroff0f32f432007-08-24 22:33:52 +00003909 // C99 6.5.16.1p2: The value of the right operand is converted to the
3910 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003911 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3912 // so that we can use references in built-in functions even in C.
3913 // The getNonReferenceType() call makes sure that the resulting expression
3914 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003915 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003916 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003917 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003918}
3919
Chris Lattner1eafdea2008-11-18 01:30:42 +00003920QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003921 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003922 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003923 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003924 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003925}
3926
Mike Stump9afab102009-02-19 03:04:26 +00003927inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003928 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003929 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003930 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003931 QualType lhsType =
3932 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3933 QualType rhsType =
3934 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003935
Nate Begemanc5f0f652008-07-14 18:02:46 +00003936 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003937 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003938 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003939
Nate Begemanc5f0f652008-07-14 18:02:46 +00003940 // Handle the case of a vector & extvector type of the same size and element
3941 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003942 if (getLangOptions().LaxVectorConversions) {
3943 // FIXME: Should we warn here?
3944 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003945 if (const VectorType *RV = rhsType->getAsVectorType())
3946 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003947 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003948 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003949 }
3950 }
3951 }
Mike Stump9afab102009-02-19 03:04:26 +00003952
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003953 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3954 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3955 bool swapped = false;
3956 if (rhsType->isExtVectorType()) {
3957 swapped = true;
3958 std::swap(rex, lex);
3959 std::swap(rhsType, lhsType);
3960 }
3961
Nate Begemanf1695892009-06-28 19:12:57 +00003962 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003963 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3964 QualType EltTy = LV->getElementType();
3965 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3966 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003967 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003968 if (swapped) std::swap(rex, lex);
3969 return lhsType;
3970 }
3971 }
3972 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3973 rhsType->isRealFloatingType()) {
3974 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003975 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003976 if (swapped) std::swap(rex, lex);
3977 return lhsType;
3978 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003979 }
3980 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003981
Nate Begemanf1695892009-06-28 19:12:57 +00003982 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003983 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003984 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003985 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003986 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003987}
3988
Chris Lattner4b009652007-07-25 00:24:17 +00003989inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003990 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003991{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003992 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003993 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003994
Steve Naroff8f708362007-08-24 19:07:16 +00003995 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003996
Chris Lattner4b009652007-07-25 00:24:17 +00003997 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003998 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003999 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004000}
4001
4002inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004003 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004004{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00004005 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4006 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4007 return CheckVectorOperands(Loc, lex, rex);
4008 return InvalidOperands(Loc, lex, rex);
4009 }
Chris Lattner4b009652007-07-25 00:24:17 +00004010
Steve Naroff8f708362007-08-24 19:07:16 +00004011 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004012
Chris Lattner4b009652007-07-25 00:24:17 +00004013 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004014 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004015 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004016}
4017
4018inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004019 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004020{
Eli Friedman3cd92882009-03-28 01:22:36 +00004021 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4022 QualType compType = CheckVectorOperands(Loc, lex, rex);
4023 if (CompLHSTy) *CompLHSTy = compType;
4024 return compType;
4025 }
Chris Lattner4b009652007-07-25 00:24:17 +00004026
Eli Friedman3cd92882009-03-28 01:22:36 +00004027 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004028
Chris Lattner4b009652007-07-25 00:24:17 +00004029 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004030 if (lex->getType()->isArithmeticType() &&
4031 rex->getType()->isArithmeticType()) {
4032 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004033 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004034 }
Chris Lattner4b009652007-07-25 00:24:17 +00004035
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004036 // Put any potential pointer into PExp
4037 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004038 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004039 std::swap(PExp, IExp);
4040
Steve Naroff79ae19a2009-07-14 18:25:06 +00004041 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004042
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004043 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004044 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004045
Chris Lattner184f92d2009-04-24 23:50:08 +00004046 // Check for arithmetic on pointers to incomplete types.
4047 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004048 if (getLangOptions().CPlusPlus) {
4049 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004050 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004051 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004052 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004053
4054 // GNU extension: arithmetic on pointer to void
4055 Diag(Loc, diag::ext_gnu_void_ptr)
4056 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004057 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004058 if (getLangOptions().CPlusPlus) {
4059 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4060 << lex->getType() << lex->getSourceRange();
4061 return QualType();
4062 }
4063
4064 // GNU extension: arithmetic on pointer to function
4065 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4066 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004067 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004068 // Check if we require a complete type.
4069 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004070 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004071 PExp->getType()->isObjCObjectPointerType()) &&
4072 RequireCompleteType(Loc, PointeeTy,
4073 diag::err_typecheck_arithmetic_incomplete_type,
4074 PExp->getSourceRange(), SourceRange(),
4075 PExp->getType()))
4076 return QualType();
4077 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004078 // Diagnose bad cases where we step over interface counts.
4079 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4080 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4081 << PointeeTy << PExp->getSourceRange();
4082 return QualType();
4083 }
4084
Eli Friedman3cd92882009-03-28 01:22:36 +00004085 if (CompLHSTy) {
4086 QualType LHSTy = lex->getType();
4087 if (LHSTy->isPromotableIntegerType())
4088 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004089 else {
4090 QualType T = isPromotableBitField(lex, Context);
4091 if (!T.isNull())
4092 LHSTy = T;
4093 }
4094
Eli Friedman3cd92882009-03-28 01:22:36 +00004095 *CompLHSTy = LHSTy;
4096 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004097 return PExp->getType();
4098 }
4099 }
4100
Chris Lattner1eafdea2008-11-18 01:30:42 +00004101 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004102}
4103
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004104// C99 6.5.6
4105QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004106 SourceLocation Loc, QualType* CompLHSTy) {
4107 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4108 QualType compType = CheckVectorOperands(Loc, lex, rex);
4109 if (CompLHSTy) *CompLHSTy = compType;
4110 return compType;
4111 }
Mike Stump9afab102009-02-19 03:04:26 +00004112
Eli Friedman3cd92882009-03-28 01:22:36 +00004113 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004114
Chris Lattnerf6da2912007-12-09 21:53:25 +00004115 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004116
Chris Lattnerf6da2912007-12-09 21:53:25 +00004117 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004118 if (lex->getType()->isArithmeticType()
4119 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004120 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004121 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004122 }
Steve Naroff329ec222009-07-10 23:34:53 +00004123
Chris Lattnerf6da2912007-12-09 21:53:25 +00004124 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004125 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004126 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004127
Douglas Gregor05e28f62009-03-24 19:52:54 +00004128 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004129
Douglas Gregor05e28f62009-03-24 19:52:54 +00004130 bool ComplainAboutVoid = false;
4131 Expr *ComplainAboutFunc = 0;
4132 if (lpointee->isVoidType()) {
4133 if (getLangOptions().CPlusPlus) {
4134 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4135 << lex->getSourceRange() << rex->getSourceRange();
4136 return QualType();
4137 }
4138
4139 // GNU C extension: arithmetic on pointer to void
4140 ComplainAboutVoid = true;
4141 } else if (lpointee->isFunctionType()) {
4142 if (getLangOptions().CPlusPlus) {
4143 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004144 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004145 return QualType();
4146 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004147
4148 // GNU C extension: arithmetic on pointer to function
4149 ComplainAboutFunc = lex;
4150 } else if (!lpointee->isDependentType() &&
4151 RequireCompleteType(Loc, lpointee,
4152 diag::err_typecheck_sub_ptr_object,
4153 lex->getSourceRange(),
4154 SourceRange(),
4155 lex->getType()))
4156 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004157
Chris Lattner184f92d2009-04-24 23:50:08 +00004158 // Diagnose bad cases where we step over interface counts.
4159 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4160 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4161 << lpointee << lex->getSourceRange();
4162 return QualType();
4163 }
4164
Chris Lattnerf6da2912007-12-09 21:53:25 +00004165 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004166 if (rex->getType()->isIntegerType()) {
4167 if (ComplainAboutVoid)
4168 Diag(Loc, diag::ext_gnu_void_ptr)
4169 << lex->getSourceRange() << rex->getSourceRange();
4170 if (ComplainAboutFunc)
4171 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4172 << ComplainAboutFunc->getType()
4173 << ComplainAboutFunc->getSourceRange();
4174
Eli Friedman3cd92882009-03-28 01:22:36 +00004175 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004176 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004177 }
Mike Stump9afab102009-02-19 03:04:26 +00004178
Chris Lattnerf6da2912007-12-09 21:53:25 +00004179 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004180 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004181 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004182
Douglas Gregor05e28f62009-03-24 19:52:54 +00004183 // RHS must be a completely-type object type.
4184 // Handle the GNU void* extension.
4185 if (rpointee->isVoidType()) {
4186 if (getLangOptions().CPlusPlus) {
4187 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4188 << lex->getSourceRange() << rex->getSourceRange();
4189 return QualType();
4190 }
Mike Stump9afab102009-02-19 03:04:26 +00004191
Douglas Gregor05e28f62009-03-24 19:52:54 +00004192 ComplainAboutVoid = true;
4193 } else if (rpointee->isFunctionType()) {
4194 if (getLangOptions().CPlusPlus) {
4195 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004196 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004197 return QualType();
4198 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004199
4200 // GNU extension: arithmetic on pointer to function
4201 if (!ComplainAboutFunc)
4202 ComplainAboutFunc = rex;
4203 } else if (!rpointee->isDependentType() &&
4204 RequireCompleteType(Loc, rpointee,
4205 diag::err_typecheck_sub_ptr_object,
4206 rex->getSourceRange(),
4207 SourceRange(),
4208 rex->getType()))
4209 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004210
Eli Friedman143ddc92009-05-16 13:54:38 +00004211 if (getLangOptions().CPlusPlus) {
4212 // Pointee types must be the same: C++ [expr.add]
4213 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4214 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4215 << lex->getType() << rex->getType()
4216 << lex->getSourceRange() << rex->getSourceRange();
4217 return QualType();
4218 }
4219 } else {
4220 // Pointee types must be compatible C99 6.5.6p3
4221 if (!Context.typesAreCompatible(
4222 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4223 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4224 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4225 << lex->getType() << rex->getType()
4226 << lex->getSourceRange() << rex->getSourceRange();
4227 return QualType();
4228 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004229 }
Mike Stump9afab102009-02-19 03:04:26 +00004230
Douglas Gregor05e28f62009-03-24 19:52:54 +00004231 if (ComplainAboutVoid)
4232 Diag(Loc, diag::ext_gnu_void_ptr)
4233 << lex->getSourceRange() << rex->getSourceRange();
4234 if (ComplainAboutFunc)
4235 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4236 << ComplainAboutFunc->getType()
4237 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004238
4239 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004240 return Context.getPointerDiffType();
4241 }
4242 }
Mike Stump9afab102009-02-19 03:04:26 +00004243
Chris Lattner1eafdea2008-11-18 01:30:42 +00004244 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004245}
4246
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004247// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004248QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004249 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004250 // C99 6.5.7p2: Each of the operands shall have integer type.
4251 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004252 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004253
Chris Lattner2c8bff72007-12-12 05:47:28 +00004254 // Shifts don't perform usual arithmetic conversions, they just do integer
4255 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00004256 QualType LHSTy;
4257 if (lex->getType()->isPromotableIntegerType())
4258 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004259 else {
4260 LHSTy = isPromotableBitField(lex, Context);
4261 if (LHSTy.isNull())
4262 LHSTy = lex->getType();
4263 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004264 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004265 ImpCastExprToType(lex, LHSTy);
4266
Chris Lattner2c8bff72007-12-12 05:47:28 +00004267 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004268
Ryan Flynnf109fff2009-08-07 16:20:20 +00004269 // Sanity-check shift operands
4270 llvm::APSInt Right;
4271 // Check right/shifter operand
4272 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004273 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004274 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4275 else {
4276 llvm::APInt LeftBits(Right.getBitWidth(),
4277 Context.getTypeSize(lex->getType()));
4278 if (Right.uge(LeftBits))
4279 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4280 }
4281 }
4282
Chris Lattner2c8bff72007-12-12 05:47:28 +00004283 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004284 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004285}
4286
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004287// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004288QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004289 unsigned OpaqueOpc, bool isRelational) {
4290 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4291
Nate Begemanc5f0f652008-07-14 18:02:46 +00004292 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004293 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004294
Chris Lattner254f3bc2007-08-26 01:18:55 +00004295 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004296 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4297 UsualArithmeticConversions(lex, rex);
4298 else {
4299 UsualUnaryConversions(lex);
4300 UsualUnaryConversions(rex);
4301 }
Chris Lattner4b009652007-07-25 00:24:17 +00004302 QualType lType = lex->getType();
4303 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004304
Mike Stumpea3d74e2009-05-07 18:43:07 +00004305 if (!lType->isFloatingType()
4306 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004307 // For non-floating point types, check for self-comparisons of the form
4308 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4309 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004310 // NOTE: Don't warn about comparisons of enum constants. These can arise
4311 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004312 Expr *LHSStripped = lex->IgnoreParens();
4313 Expr *RHSStripped = rex->IgnoreParens();
4314 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4315 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004316 if (DRL->getDecl() == DRR->getDecl() &&
4317 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004318 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004319
4320 if (isa<CastExpr>(LHSStripped))
4321 LHSStripped = LHSStripped->IgnoreParenCasts();
4322 if (isa<CastExpr>(RHSStripped))
4323 RHSStripped = RHSStripped->IgnoreParenCasts();
4324
4325 // Warn about comparisons against a string constant (unless the other
4326 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004327 Expr *literalString = 0;
4328 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004329 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004330 !RHSStripped->isNullPointerConstant(Context)) {
4331 literalString = lex;
4332 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004333 } else if ((isa<StringLiteral>(RHSStripped) ||
4334 isa<ObjCEncodeExpr>(RHSStripped)) &&
4335 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004336 literalString = rex;
4337 literalStringStripped = RHSStripped;
4338 }
4339
4340 if (literalString) {
4341 std::string resultComparison;
4342 switch (Opc) {
4343 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4344 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4345 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4346 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4347 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4348 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4349 default: assert(false && "Invalid comparison operator");
4350 }
4351 Diag(Loc, diag::warn_stringcompare)
4352 << isa<ObjCEncodeExpr>(literalStringStripped)
4353 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004354 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4355 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4356 "strcmp(")
4357 << CodeModificationHint::CreateInsertion(
4358 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004359 resultComparison);
4360 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004361 }
Mike Stump9afab102009-02-19 03:04:26 +00004362
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004363 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004364 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004365
Chris Lattner254f3bc2007-08-26 01:18:55 +00004366 if (isRelational) {
4367 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004368 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004369 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004370 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004371 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004372 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004373 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004374 }
Mike Stump9afab102009-02-19 03:04:26 +00004375
Chris Lattner254f3bc2007-08-26 01:18:55 +00004376 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004377 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004378 }
Mike Stump9afab102009-02-19 03:04:26 +00004379
Chris Lattner22be8422007-08-26 01:10:14 +00004380 bool LHSIsNull = lex->isNullPointerConstant(Context);
4381 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004382
Chris Lattner254f3bc2007-08-26 01:18:55 +00004383 // All of the following pointer related warnings are GCC extensions, except
4384 // when handling null pointer constants. One day, we can consider making them
4385 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004386 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004387 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004388 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004389 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004390 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004391
Douglas Gregor4da47382009-07-06 20:14:23 +00004392 if (isRelational) {
4393 if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004394 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4395 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4396 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004397 if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) {
4398 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4399 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4400 }
4401 } else {
4402 if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) {
4403 if (!LHSIsNull && !RHSIsNull)
4404 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4405 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4406 }
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004407 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004408
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004409 // Simple check: if the pointee types are identical, we're done.
4410 if (LCanPointeeTy == RCanPointeeTy)
4411 return ResultTy;
4412
4413 if (getLangOptions().CPlusPlus) {
4414 // C++ [expr.rel]p2:
4415 // [...] Pointer conversions (4.10) and qualification
4416 // conversions (4.4) are performed on pointer operands (or on
4417 // a pointer operand and a null pointer constant) to bring
4418 // them to their composite pointer type. [...]
4419 //
4420 // C++ [expr.eq]p2 uses the same notion for (in)equality
4421 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004422 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004423 if (T.isNull()) {
4424 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4425 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4426 return QualType();
4427 }
4428
4429 ImpCastExprToType(lex, T);
4430 ImpCastExprToType(rex, T);
4431 return ResultTy;
4432 }
4433
Steve Naroff3b435622007-11-13 14:57:38 +00004434 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004435 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4436 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Steve Naroff329ec222009-07-10 23:34:53 +00004437 RCanPointeeTy.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004438 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004439 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004440 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004441 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004442 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004443 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004444 // C++ allows comparison of pointers with null pointer constants.
4445 if (getLangOptions().CPlusPlus) {
4446 if (lType->isPointerType() && RHSIsNull) {
4447 ImpCastExprToType(rex, lType);
4448 return ResultTy;
4449 }
4450 if (rType->isPointerType() && LHSIsNull) {
4451 ImpCastExprToType(lex, rType);
4452 return ResultTy;
4453 }
4454 // And comparison of nullptr_t with itself.
4455 if (lType->isNullPtrType() && rType->isNullPtrType())
4456 return ResultTy;
4457 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004458 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004459 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004460 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4461 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004462
Steve Naroff3454b6c2008-09-04 15:10:53 +00004463 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004464 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004465 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004466 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004467 }
4468 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004469 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004470 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004471 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004472 if (!isRelational
4473 && ((lType->isBlockPointerType() && rType->isPointerType())
4474 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004475 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004476 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004477 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004478 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004479 ->getPointeeType()->isVoidType())))
4480 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4481 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004482 }
4483 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004484 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004485 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004486
Steve Naroff329ec222009-07-10 23:34:53 +00004487 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004488 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004489 const PointerType *LPT = lType->getAs<PointerType>();
4490 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004491 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004492 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004493 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004494 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004495
Steve Naroff030fcda2008-11-17 19:49:16 +00004496 if (!LPtrToVoid && !RPtrToVoid &&
4497 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004498 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004499 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004500 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004501 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004502 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004503 }
Steve Naroff329ec222009-07-10 23:34:53 +00004504 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4505 if (!Context.areComparableObjCPointerTypes(lType, rType)) {
4506 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4507 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4508 }
Steve Naroff936c4362008-06-03 14:04:54 +00004509 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004510 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004511 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004512 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004513 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004514 if (isRelational)
4515 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4516 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4517 else if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004518 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004520 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004521 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004522 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004523 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004524 if (isRelational)
4525 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4526 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4527 else if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004528 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004529 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004530 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004531 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004532 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004533 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004534 if (!isRelational && RHSIsNull
4535 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004536 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004537 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004538 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004539 if (!isRelational && LHSIsNull
4540 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004541 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004542 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004543 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004544 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004545}
4546
Nate Begemanc5f0f652008-07-14 18:02:46 +00004547/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004548/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004549/// like a scalar comparison, a vector comparison produces a vector of integer
4550/// types.
4551QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004552 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004553 bool isRelational) {
4554 // Check to make sure we're operating on vectors of the same type and width,
4555 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004556 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004557 if (vType.isNull())
4558 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004559
Nate Begemanc5f0f652008-07-14 18:02:46 +00004560 QualType lType = lex->getType();
4561 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004562
Nate Begemanc5f0f652008-07-14 18:02:46 +00004563 // For non-floating point types, check for self-comparisons of the form
4564 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4565 // often indicate logic errors in the program.
4566 if (!lType->isFloatingType()) {
4567 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4568 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4569 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004570 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004571 }
Mike Stump9afab102009-02-19 03:04:26 +00004572
Nate Begemanc5f0f652008-07-14 18:02:46 +00004573 // Check for comparisons of floating point operands using != and ==.
4574 if (!isRelational && lType->isFloatingType()) {
4575 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004576 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004577 }
Mike Stump9afab102009-02-19 03:04:26 +00004578
Nate Begemanc5f0f652008-07-14 18:02:46 +00004579 // Return the type for the comparison, which is the same as vector type for
4580 // integer vectors, or an integer type of identical size and number of
4581 // elements for floating point vectors.
4582 if (lType->isIntegerType())
4583 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004584
Nate Begemanc5f0f652008-07-14 18:02:46 +00004585 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004586 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004587 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004588 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004589 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004590 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4591
Mike Stump9afab102009-02-19 03:04:26 +00004592 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004593 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004594 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4595}
4596
Chris Lattner4b009652007-07-25 00:24:17 +00004597inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004598 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004599{
4600 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004601 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004602
Steve Naroff8f708362007-08-24 19:07:16 +00004603 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004604
Chris Lattner4b009652007-07-25 00:24:17 +00004605 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004606 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004607 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004608}
4609
4610inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004611 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004612{
4613 UsualUnaryConversions(lex);
4614 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004615
Eli Friedmanbea3f842008-05-13 20:16:47 +00004616 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004617 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004618 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004619}
4620
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004621/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4622/// is a read-only property; return true if so. A readonly property expression
4623/// depends on various declarations and thus must be treated specially.
4624///
Mike Stump9afab102009-02-19 03:04:26 +00004625static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004626{
4627 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4628 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4629 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4630 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004631 if (const ObjCObjectPointerType *OPT =
4632 BaseType->getAsObjCInterfacePointerType())
4633 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4634 if (S.isPropertyReadonly(PDecl, IFace))
4635 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004636 }
4637 }
4638 return false;
4639}
4640
Chris Lattner4c2642c2008-11-18 01:22:49 +00004641/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4642/// emit an error and return true. If so, return false.
4643static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004644 SourceLocation OrigLoc = Loc;
4645 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4646 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004647 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4648 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004649 if (IsLV == Expr::MLV_Valid)
4650 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004651
Chris Lattner4c2642c2008-11-18 01:22:49 +00004652 unsigned Diag = 0;
4653 bool NeedType = false;
4654 switch (IsLV) { // C99 6.5.16p2
4655 default: assert(0 && "Unknown result from isModifiableLvalue!");
4656 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004657 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004658 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4659 NeedType = true;
4660 break;
Mike Stump9afab102009-02-19 03:04:26 +00004661 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004662 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4663 NeedType = true;
4664 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004665 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004666 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4667 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004668 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004669 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4670 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004671 case Expr::MLV_IncompleteType:
4672 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004673 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004674 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4675 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004676 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004677 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4678 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004679 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004680 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4681 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004682 case Expr::MLV_ReadonlyProperty:
4683 Diag = diag::error_readonly_property_assignment;
4684 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004685 case Expr::MLV_NoSetterProperty:
4686 Diag = diag::error_nosetter_property_assignment;
4687 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004688 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004689
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004690 SourceRange Assign;
4691 if (Loc != OrigLoc)
4692 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004693 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004694 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004695 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004696 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004697 return true;
4698}
4699
4700
4701
4702// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004703QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4704 SourceLocation Loc,
4705 QualType CompoundType) {
4706 // Verify that LHS is a modifiable lvalue, and emit error if not.
4707 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004708 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004709
4710 QualType LHSType = LHS->getType();
4711 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004712
Chris Lattner005ed752008-01-04 18:04:52 +00004713 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004714 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004715 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004716 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004717 // Special case of NSObject attributes on c-style pointer types.
4718 if (ConvTy == IncompatiblePointer &&
4719 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004720 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004721 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004722 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004723 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004724
Chris Lattner34c85082008-08-21 18:04:13 +00004725 // If the RHS is a unary plus or minus, check to see if they = and + are
4726 // right next to each other. If so, the user may have typo'd "x =+ 4"
4727 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004728 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004729 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4730 RHSCheck = ICE->getSubExpr();
4731 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4732 if ((UO->getOpcode() == UnaryOperator::Plus ||
4733 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004734 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004735 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004736 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4737 // And there is a space or other character before the subexpr of the
4738 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004739 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4740 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004741 Diag(Loc, diag::warn_not_compound_assign)
4742 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4743 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004744 }
Chris Lattner34c85082008-08-21 18:04:13 +00004745 }
4746 } else {
4747 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004748 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004749 }
Chris Lattner005ed752008-01-04 18:04:52 +00004750
Chris Lattner1eafdea2008-11-18 01:30:42 +00004751 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4752 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004753 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004754
Chris Lattner4b009652007-07-25 00:24:17 +00004755 // C99 6.5.16p3: The type of an assignment expression is the type of the
4756 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004757 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004758 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4759 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004760 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004761 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004762 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004763}
4764
Chris Lattner1eafdea2008-11-18 01:30:42 +00004765// C99 6.5.17
4766QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004767 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004768 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004769
4770 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4771 // incomplete in C++).
4772
Chris Lattner1eafdea2008-11-18 01:30:42 +00004773 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004774}
4775
4776/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4777/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004778QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4779 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004780 if (Op->isTypeDependent())
4781 return Context.DependentTy;
4782
Chris Lattnere65182c2008-11-21 07:05:48 +00004783 QualType ResType = Op->getType();
4784 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004785
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004786 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4787 // Decrement of bool is not allowed.
4788 if (!isInc) {
4789 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4790 return QualType();
4791 }
4792 // Increment of bool sets it to true, but is deprecated.
4793 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4794 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004795 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004796 } else if (ResType->isAnyPointerType()) {
4797 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004798
Chris Lattnere65182c2008-11-21 07:05:48 +00004799 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004800 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004801 if (getLangOptions().CPlusPlus) {
4802 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4803 << Op->getSourceRange();
4804 return QualType();
4805 }
4806
4807 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004808 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004809 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004810 if (getLangOptions().CPlusPlus) {
4811 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4812 << Op->getType() << Op->getSourceRange();
4813 return QualType();
4814 }
4815
4816 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004817 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004818 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004819 diag::err_typecheck_arithmetic_incomplete_type,
4820 Op->getSourceRange(), SourceRange(),
4821 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004822 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004823 // Diagnose bad cases where we step over interface counts.
4824 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4825 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4826 << PointeeTy << Op->getSourceRange();
4827 return QualType();
4828 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004829 } else if (ResType->isComplexType()) {
4830 // C99 does not support ++/-- on complex types, we allow as an extension.
4831 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004832 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004833 } else {
4834 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004835 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004836 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004837 }
Mike Stump9afab102009-02-19 03:04:26 +00004838 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004839 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004840 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004841 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004842 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004843}
4844
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004845/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004846/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004847/// where the declaration is needed for type checking. We only need to
4848/// handle cases when the expression references a function designator
4849/// or is an lvalue. Here are some examples:
4850/// - &(x) => x
4851/// - &*****f => f for f a function designator.
4852/// - &s.xx => s
4853/// - &s.zz[1].yy -> s, if zz is an array
4854/// - *(x + 1) -> x, if x is an array
4855/// - &"123"[2] -> 0
4856/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004857static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004858 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004859 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004860 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004861 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004862 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004863 // If this is an arrow operator, the address is an offset from
4864 // the base's value, so the object the base refers to is
4865 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004866 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004867 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004868 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004869 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004870 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004871 // FIXME: This code shouldn't be necessary! We should catch the implicit
4872 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004873 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4874 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4875 if (ICE->getSubExpr()->getType()->isArrayType())
4876 return getPrimaryDecl(ICE->getSubExpr());
4877 }
4878 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004879 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004880 case Stmt::UnaryOperatorClass: {
4881 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004882
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004883 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004884 case UnaryOperator::Real:
4885 case UnaryOperator::Imag:
4886 case UnaryOperator::Extension:
4887 return getPrimaryDecl(UO->getSubExpr());
4888 default:
4889 return 0;
4890 }
4891 }
Chris Lattner4b009652007-07-25 00:24:17 +00004892 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004893 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004894 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004895 // If the result of an implicit cast is an l-value, we care about
4896 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004897 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004898 default:
4899 return 0;
4900 }
4901}
4902
4903/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004904/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004905/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004906/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004907/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004908/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004909/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004910QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004911 // Make sure to ignore parentheses in subsequent checks
4912 op = op->IgnoreParens();
4913
Douglas Gregore6be68a2008-12-17 22:52:20 +00004914 if (op->isTypeDependent())
4915 return Context.DependentTy;
4916
Steve Naroff9c6c3592008-01-13 17:10:08 +00004917 if (getLangOptions().C99) {
4918 // Implement C99-only parts of addressof rules.
4919 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4920 if (uOp->getOpcode() == UnaryOperator::Deref)
4921 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4922 // (assuming the deref expression is valid).
4923 return uOp->getSubExpr()->getType();
4924 }
4925 // Technically, there should be a check for array subscript
4926 // expressions here, but the result of one is always an lvalue anyway.
4927 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004928 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004929 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004930
Eli Friedman14ab4c42009-05-16 23:27:50 +00004931 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4932 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004933 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004934 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004935 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004936 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4937 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004938 return QualType();
4939 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004940 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004941 // The operand cannot be a bit-field
4942 Diag(OpLoc, diag::err_typecheck_address_of)
4943 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004944 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004945 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4946 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004947 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004948 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004949 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004950 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004951 } else if (isa<ObjCPropertyRefExpr>(op)) {
4952 // cannot take address of a property expression.
4953 Diag(OpLoc, diag::err_typecheck_address_of)
4954 << "property expression" << op->getSourceRange();
4955 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004956 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004957 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004958 // with the register storage-class specifier.
4959 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4960 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004961 Diag(OpLoc, diag::err_typecheck_address_of)
4962 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004963 return QualType();
4964 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004965 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4966 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004967 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004968 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004969 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004970 // Could be a pointer to member, though, if there is an explicit
4971 // scope qualifier for the class.
4972 if (isa<QualifiedDeclRefExpr>(op)) {
4973 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004974 if (Ctx && Ctx->isRecord()) {
4975 if (FD->getType()->isReferenceType()) {
4976 Diag(OpLoc,
4977 diag::err_cannot_form_pointer_to_member_of_reference_type)
4978 << FD->getDeclName() << FD->getType();
4979 return QualType();
4980 }
4981
Sebastian Redl0c9da212009-02-03 20:19:35 +00004982 return Context.getMemberPointerType(op->getType(),
4983 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004984 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004985 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004986 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004987 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004988 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004989 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4990 return Context.getMemberPointerType(op->getType(),
4991 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4992 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004993 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004994 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004995
Eli Friedman14ab4c42009-05-16 23:27:50 +00004996 if (lval == Expr::LV_IncompleteVoidType) {
4997 // Taking the address of a void variable is technically illegal, but we
4998 // allow it in cases which are otherwise valid.
4999 // Example: "extern void x; void* y = &x;".
5000 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5001 }
5002
Chris Lattner4b009652007-07-25 00:24:17 +00005003 // If the operand has type "type", the result has type "pointer to type".
5004 return Context.getPointerType(op->getType());
5005}
5006
Chris Lattnerda5c0872008-11-23 09:13:29 +00005007QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005008 if (Op->isTypeDependent())
5009 return Context.DependentTy;
5010
Chris Lattnerda5c0872008-11-23 09:13:29 +00005011 UsualUnaryConversions(Op);
5012 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005013
Chris Lattnerda5c0872008-11-23 09:13:29 +00005014 // Note that per both C89 and C99, this is always legal, even if ptype is an
5015 // incomplete type or void. It would be possible to warn about dereferencing
5016 // a void pointer, but it's completely well-defined, and such a warning is
5017 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005018 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005019 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005020
Steve Naroff329ec222009-07-10 23:34:53 +00005021 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5022 return OPT->getPointeeType();
5023
Chris Lattner77d52da2008-11-20 06:06:08 +00005024 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005025 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005026 return QualType();
5027}
5028
5029static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5030 tok::TokenKind Kind) {
5031 BinaryOperator::Opcode Opc;
5032 switch (Kind) {
5033 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005034 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5035 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005036 case tok::star: Opc = BinaryOperator::Mul; break;
5037 case tok::slash: Opc = BinaryOperator::Div; break;
5038 case tok::percent: Opc = BinaryOperator::Rem; break;
5039 case tok::plus: Opc = BinaryOperator::Add; break;
5040 case tok::minus: Opc = BinaryOperator::Sub; break;
5041 case tok::lessless: Opc = BinaryOperator::Shl; break;
5042 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5043 case tok::lessequal: Opc = BinaryOperator::LE; break;
5044 case tok::less: Opc = BinaryOperator::LT; break;
5045 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5046 case tok::greater: Opc = BinaryOperator::GT; break;
5047 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5048 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5049 case tok::amp: Opc = BinaryOperator::And; break;
5050 case tok::caret: Opc = BinaryOperator::Xor; break;
5051 case tok::pipe: Opc = BinaryOperator::Or; break;
5052 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5053 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5054 case tok::equal: Opc = BinaryOperator::Assign; break;
5055 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5056 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5057 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5058 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5059 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5060 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5061 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5062 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5063 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5064 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5065 case tok::comma: Opc = BinaryOperator::Comma; break;
5066 }
5067 return Opc;
5068}
5069
5070static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5071 tok::TokenKind Kind) {
5072 UnaryOperator::Opcode Opc;
5073 switch (Kind) {
5074 default: assert(0 && "Unknown unary op!");
5075 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5076 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5077 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5078 case tok::star: Opc = UnaryOperator::Deref; break;
5079 case tok::plus: Opc = UnaryOperator::Plus; break;
5080 case tok::minus: Opc = UnaryOperator::Minus; break;
5081 case tok::tilde: Opc = UnaryOperator::Not; break;
5082 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005083 case tok::kw___real: Opc = UnaryOperator::Real; break;
5084 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5085 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5086 }
5087 return Opc;
5088}
5089
Douglas Gregord7f915e2008-11-06 23:29:22 +00005090/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5091/// operator @p Opc at location @c TokLoc. This routine only supports
5092/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005093Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5094 unsigned Op,
5095 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005096 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005097 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005098 // The following two variables are used for compound assignment operators
5099 QualType CompLHSTy; // Type of LHS after promotions for computation
5100 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005101
5102 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005103 case BinaryOperator::Assign:
5104 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5105 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005106 case BinaryOperator::PtrMemD:
5107 case BinaryOperator::PtrMemI:
5108 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5109 Opc == BinaryOperator::PtrMemI);
5110 break;
5111 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005112 case BinaryOperator::Div:
5113 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5114 break;
5115 case BinaryOperator::Rem:
5116 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5117 break;
5118 case BinaryOperator::Add:
5119 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5120 break;
5121 case BinaryOperator::Sub:
5122 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5123 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005124 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005125 case BinaryOperator::Shr:
5126 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5127 break;
5128 case BinaryOperator::LE:
5129 case BinaryOperator::LT:
5130 case BinaryOperator::GE:
5131 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005132 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005133 break;
5134 case BinaryOperator::EQ:
5135 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005136 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005137 break;
5138 case BinaryOperator::And:
5139 case BinaryOperator::Xor:
5140 case BinaryOperator::Or:
5141 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5142 break;
5143 case BinaryOperator::LAnd:
5144 case BinaryOperator::LOr:
5145 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5146 break;
5147 case BinaryOperator::MulAssign:
5148 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005149 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5150 CompLHSTy = CompResultTy;
5151 if (!CompResultTy.isNull())
5152 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005153 break;
5154 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005155 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5156 CompLHSTy = CompResultTy;
5157 if (!CompResultTy.isNull())
5158 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005159 break;
5160 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005161 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5162 if (!CompResultTy.isNull())
5163 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005164 break;
5165 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005166 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5167 if (!CompResultTy.isNull())
5168 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005169 break;
5170 case BinaryOperator::ShlAssign:
5171 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005172 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5173 CompLHSTy = CompResultTy;
5174 if (!CompResultTy.isNull())
5175 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005176 break;
5177 case BinaryOperator::AndAssign:
5178 case BinaryOperator::XorAssign:
5179 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005180 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5181 CompLHSTy = CompResultTy;
5182 if (!CompResultTy.isNull())
5183 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005184 break;
5185 case BinaryOperator::Comma:
5186 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5187 break;
5188 }
5189 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005190 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005191 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005192 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5193 else
5194 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005195 CompLHSTy, CompResultTy,
5196 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005197}
5198
Chris Lattner4b009652007-07-25 00:24:17 +00005199// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005200Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5201 tok::TokenKind Kind,
5202 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005203 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005204 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005205
Steve Naroff87d58b42007-09-16 03:34:24 +00005206 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5207 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005208
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005209 if (getLangOptions().CPlusPlus &&
5210 (lhs->getType()->isOverloadableType() ||
5211 rhs->getType()->isOverloadableType())) {
5212 // Find all of the overloaded operators visible from this
5213 // point. We perform both an operator-name lookup from the local
5214 // scope and an argument-dependent lookup based on the types of
5215 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005216 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005217 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5218 if (OverOp != OO_None) {
5219 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5220 Functions);
5221 Expr *Args[2] = { lhs, rhs };
5222 DeclarationName OpName
5223 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5224 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005225 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005226
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005227 // Build the (potentially-overloaded, potentially-dependent)
5228 // binary operation.
5229 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005230 }
5231
Douglas Gregord7f915e2008-11-06 23:29:22 +00005232 // Build a built-in binary operation.
5233 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005234}
5235
Douglas Gregorc78182d2009-03-13 23:49:33 +00005236Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5237 unsigned OpcIn,
5238 ExprArg InputArg) {
5239 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005240
Mike Stumpe127ae32009-05-16 07:39:55 +00005241 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005242 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005243 QualType resultType;
5244 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005245 case UnaryOperator::OffsetOf:
5246 assert(false && "Invalid unary operator");
5247 break;
5248
Chris Lattner4b009652007-07-25 00:24:17 +00005249 case UnaryOperator::PreInc:
5250 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005251 case UnaryOperator::PostInc:
5252 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005253 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005254 Opc == UnaryOperator::PreInc ||
5255 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005256 break;
Mike Stump9afab102009-02-19 03:04:26 +00005257 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005258 resultType = CheckAddressOfOperand(Input, OpLoc);
5259 break;
Mike Stump9afab102009-02-19 03:04:26 +00005260 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005261 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005262 resultType = CheckIndirectionOperand(Input, OpLoc);
5263 break;
5264 case UnaryOperator::Plus:
5265 case UnaryOperator::Minus:
5266 UsualUnaryConversions(Input);
5267 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005268 if (resultType->isDependentType())
5269 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005270 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5271 break;
5272 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5273 resultType->isEnumeralType())
5274 break;
5275 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5276 Opc == UnaryOperator::Plus &&
5277 resultType->isPointerType())
5278 break;
5279
Sebastian Redl8b769972009-01-19 00:08:26 +00005280 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5281 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005282 case UnaryOperator::Not: // bitwise complement
5283 UsualUnaryConversions(Input);
5284 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005285 if (resultType->isDependentType())
5286 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005287 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5288 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5289 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005290 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005291 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005292 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005293 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5294 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005295 break;
5296 case UnaryOperator::LNot: // logical negation
5297 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5298 DefaultFunctionArrayConversion(Input);
5299 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005300 if (resultType->isDependentType())
5301 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005302 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005303 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5304 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005305 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005306 // In C++, it's bool. C++ 5.3.1p8
5307 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005308 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005309 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005310 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005311 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005312 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005313 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005314 resultType = Input->getType();
5315 break;
5316 }
5317 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005318 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005319
5320 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005321 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005322}
5323
Douglas Gregorc78182d2009-03-13 23:49:33 +00005324// Unary Operators. 'Tok' is the token for the operator.
5325Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5326 tok::TokenKind Op, ExprArg input) {
5327 Expr *Input = (Expr*)input.get();
5328 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5329
5330 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5331 // Find all of the overloaded operators visible from this
5332 // point. We perform both an operator-name lookup from the local
5333 // scope and an argument-dependent lookup based on the types of
5334 // the arguments.
5335 FunctionSet Functions;
5336 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5337 if (OverOp != OO_None) {
5338 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5339 Functions);
5340 DeclarationName OpName
5341 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5342 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5343 }
5344
5345 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5346 }
5347
5348 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5349}
5350
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005351/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005352Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5353 SourceLocation LabLoc,
5354 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005355 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005356 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005357
Daniel Dunbar879788d2008-08-04 16:51:22 +00005358 // If we haven't seen this label yet, create a forward reference. It
5359 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005360 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005361 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005362
Chris Lattner4b009652007-07-25 00:24:17 +00005363 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005364 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5365 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005366}
5367
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005368Sema::OwningExprResult
5369Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5370 SourceLocation RPLoc) { // "({..})"
5371 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005372 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5373 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5374
Eli Friedmanbc941e12009-01-24 23:09:00 +00005375 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005376 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005377 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005378
Chris Lattner4b009652007-07-25 00:24:17 +00005379 // FIXME: there are a variety of strange constraints to enforce here, for
5380 // example, it is not possible to goto into a stmt expression apparently.
5381 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005382
Chris Lattner4b009652007-07-25 00:24:17 +00005383 // If there are sub stmts in the compound stmt, take the type of the last one
5384 // as the type of the stmtexpr.
5385 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005386
Chris Lattner200964f2008-07-26 19:51:01 +00005387 if (!Compound->body_empty()) {
5388 Stmt *LastStmt = Compound->body_back();
5389 // If LastStmt is a label, skip down through into the body.
5390 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5391 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005392
Chris Lattner200964f2008-07-26 19:51:01 +00005393 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005394 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005395 }
Mike Stump9afab102009-02-19 03:04:26 +00005396
Eli Friedman2b128322009-03-23 00:24:07 +00005397 // FIXME: Check that expression type is complete/non-abstract; statement
5398 // expressions are not lvalues.
5399
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005400 substmt.release();
5401 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005402}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005403
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005404Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5405 SourceLocation BuiltinLoc,
5406 SourceLocation TypeLoc,
5407 TypeTy *argty,
5408 OffsetOfComponent *CompPtr,
5409 unsigned NumComponents,
5410 SourceLocation RPLoc) {
5411 // FIXME: This function leaks all expressions in the offset components on
5412 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005413 QualType ArgTy = QualType::getFromOpaquePtr(argty);
5414 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005415
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005416 bool Dependent = ArgTy->isDependentType();
5417
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005418 // We must have at least one component that refers to the type, and the first
5419 // one is known to be a field designator. Verify that the ArgTy represents
5420 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005421 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005422 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005423
Eli Friedman2b128322009-03-23 00:24:07 +00005424 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5425 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005426
Eli Friedman342d9432009-02-27 06:44:11 +00005427 // Otherwise, create a null pointer as the base, and iteratively process
5428 // the offsetof designators.
5429 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5430 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005431 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005432 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005433
Chris Lattnerb37522e2007-08-31 21:49:13 +00005434 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5435 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005436 // FIXME: This diagnostic isn't actually visible because the location is in
5437 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005438 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005439 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5440 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005441
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005442 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005443 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005444
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005445 // FIXME: Dependent case loses a lot of information here. And probably
5446 // leaks like a sieve.
5447 for (unsigned i = 0; i != NumComponents; ++i) {
5448 const OffsetOfComponent &OC = CompPtr[i];
5449 if (OC.isBrackets) {
5450 // Offset of an array sub-field. TODO: Should we allow vector elements?
5451 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5452 if (!AT) {
5453 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005454 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5455 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005456 }
5457
5458 // FIXME: C++: Verify that operator[] isn't overloaded.
5459
Eli Friedman342d9432009-02-27 06:44:11 +00005460 // Promote the array so it looks more like a normal array subscript
5461 // expression.
5462 DefaultFunctionArrayConversion(Res);
5463
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005464 // C99 6.5.2.1p1
5465 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005466 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005467 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005468 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005469 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005470 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005471
5472 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5473 OC.LocEnd);
5474 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005475 }
Mike Stump9afab102009-02-19 03:04:26 +00005476
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005477 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005478 if (!RC) {
5479 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005480 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5481 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005482 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005483
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005484 // Get the decl corresponding to this.
5485 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005486 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005487 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005488 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5489 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5490 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005491 DidWarnAboutNonPOD = true;
5492 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005493 }
5494
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005495 FieldDecl *MemberDecl
5496 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5497 LookupMemberName)
5498 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005499 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005500 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005501 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5502 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005503
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005504 // FIXME: C++: Verify that MemberDecl isn't a static field.
5505 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005506 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005507 Res = BuildAnonymousStructUnionMemberReference(
5508 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005509 } else {
5510 // MemberDecl->getType() doesn't get the right qualifiers, but it
5511 // doesn't matter here.
5512 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5513 MemberDecl->getType().getNonReferenceType());
5514 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005515 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005516 }
Mike Stump9afab102009-02-19 03:04:26 +00005517
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005518 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5519 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005520}
5521
5522
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005523Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5524 TypeTy *arg1,TypeTy *arg2,
5525 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00005526 QualType argT1 = QualType::getFromOpaquePtr(arg1);
5527 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005528
Steve Naroff63bad2d2007-08-01 22:05:33 +00005529 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005530
Douglas Gregore6211502009-05-19 22:28:02 +00005531 if (getLangOptions().CPlusPlus) {
5532 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5533 << SourceRange(BuiltinLoc, RPLoc);
5534 return ExprError();
5535 }
5536
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005537 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5538 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005539}
5540
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005541Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5542 ExprArg cond,
5543 ExprArg expr1, ExprArg expr2,
5544 SourceLocation RPLoc) {
5545 Expr *CondExpr = static_cast<Expr*>(cond.get());
5546 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5547 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005548
Steve Naroff93c53012007-08-03 21:21:27 +00005549 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5550
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005551 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005552 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005553 resType = Context.DependentTy;
5554 } else {
5555 // The conditional expression is required to be a constant expression.
5556 llvm::APSInt condEval(32);
5557 SourceLocation ExpLoc;
5558 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005559 return ExprError(Diag(ExpLoc,
5560 diag::err_typecheck_choose_expr_requires_constant)
5561 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005562
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005563 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5564 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5565 }
5566
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005567 cond.release(); expr1.release(); expr2.release();
5568 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5569 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005570}
5571
Steve Naroff52a81c02008-09-03 18:15:37 +00005572//===----------------------------------------------------------------------===//
5573// Clang Extensions.
5574//===----------------------------------------------------------------------===//
5575
5576/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005577void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005578 // Analyze block parameters.
5579 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005580
Steve Naroff52a81c02008-09-03 18:15:37 +00005581 // Add BSI to CurBlock.
5582 BSI->PrevBlockInfo = CurBlock;
5583 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005584
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005585 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005586 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005587 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005588 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005589 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5590 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005591
Steve Naroff52059382008-10-10 01:28:17 +00005592 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005593 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005594}
5595
Mike Stumpc1fddff2009-02-04 22:31:32 +00005596void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005597 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005598
5599 if (ParamInfo.getNumTypeObjects() == 0
5600 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005601 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005602 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5603
Mike Stump458287d2009-04-28 01:10:27 +00005604 if (T->isArrayType()) {
5605 Diag(ParamInfo.getSourceRange().getBegin(),
5606 diag::err_block_returns_array);
5607 return;
5608 }
5609
Mike Stumpc1fddff2009-02-04 22:31:32 +00005610 // The parameter list is optional, if there was none, assume ().
5611 if (!T->isFunctionType())
5612 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5613
5614 CurBlock->hasPrototype = true;
5615 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005616 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005617 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005618 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005619 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005620 // FIXME: remove the attribute.
5621 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005622 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5623
5624 // Do not allow returning a objc interface by-value.
5625 if (RetTy->isObjCInterfaceType()) {
5626 Diag(ParamInfo.getSourceRange().getBegin(),
5627 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5628 return;
5629 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005630 return;
5631 }
5632
Steve Naroff52a81c02008-09-03 18:15:37 +00005633 // Analyze arguments to block.
5634 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5635 "Not a function declarator!");
5636 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005637
Steve Naroff52059382008-10-10 01:28:17 +00005638 CurBlock->hasPrototype = FTI.hasPrototype;
5639 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005640
Steve Naroff52a81c02008-09-03 18:15:37 +00005641 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5642 // no arguments, not a function that takes a single void argument.
5643 if (FTI.hasPrototype &&
5644 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005645 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5646 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005647 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005648 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005649 } else if (FTI.hasPrototype) {
5650 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005651 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005652 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005653 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005654 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005655 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005656 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005657 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005658 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5659 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5660 // If this has an identifier, add it to the scope stack.
5661 if ((*AI)->getIdentifier())
5662 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005663
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005664 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005665 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005666 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005667 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005668 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005669 // FIXME: remove the attribute.
5670 }
5671
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005672 // Analyze the return type.
5673 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5674 QualType RetTy = T->getAsFunctionType()->getResultType();
5675
5676 // Do not allow returning a objc interface by-value.
5677 if (RetTy->isObjCInterfaceType()) {
5678 Diag(ParamInfo.getSourceRange().getBegin(),
5679 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5680 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005681 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005682}
5683
5684/// ActOnBlockError - If there is an error parsing a block, this callback
5685/// is invoked to pop the information about the block from the action impl.
5686void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5687 // Ensure that CurBlock is deleted.
5688 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005689
Chris Lattnere7765e12009-04-19 05:28:12 +00005690 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5691
Steve Naroff52a81c02008-09-03 18:15:37 +00005692 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005693 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005694 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005695 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005696}
5697
5698/// ActOnBlockStmtExpr - This is called when the body of a block statement
5699/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005700Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5701 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005702 // If blocks are disabled, emit an error.
5703 if (!LangOpts.Blocks)
5704 Diag(CaretLoc, diag::err_blocks_disable);
5705
Steve Naroff52a81c02008-09-03 18:15:37 +00005706 // Ensure that CurBlock is deleted.
5707 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005708
Steve Naroff52059382008-10-10 01:28:17 +00005709 PopDeclContext();
5710
Steve Naroff52a81c02008-09-03 18:15:37 +00005711 // Pop off CurBlock, handle nested blocks.
5712 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005713
Steve Naroff52a81c02008-09-03 18:15:37 +00005714 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005715 if (!BSI->ReturnType.isNull())
5716 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005717
Steve Naroff52a81c02008-09-03 18:15:37 +00005718 llvm::SmallVector<QualType, 8> ArgTypes;
5719 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5720 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005721
Mike Stump8e288f42009-07-28 22:04:01 +00005722 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005723 QualType BlockTy;
5724 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005725 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5726 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005727 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005728 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005729 BSI->isVariadic, 0, false, false, 0, 0,
5730 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005731
Eli Friedman2b128322009-03-23 00:24:07 +00005732 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005733 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005734 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005735
Chris Lattnere7765e12009-04-19 05:28:12 +00005736 // If needed, diagnose invalid gotos and switches in the block.
5737 if (CurFunctionNeedsScopeChecking)
5738 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5739 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5740
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005741 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005742 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005743 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5744 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005745}
5746
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005747Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5748 ExprArg expr, TypeTy *type,
5749 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005750 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005751 Expr *E = static_cast<Expr*>(expr.get());
5752 Expr *OrigExpr = E;
5753
Anders Carlsson36760332007-10-15 20:28:48 +00005754 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005755
5756 // Get the va_list type
5757 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005758 if (VaListType->isArrayType()) {
5759 // Deal with implicit array decay; for example, on x86-64,
5760 // va_list is an array, but it's supposed to decay to
5761 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005762 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005763 // Make sure the input expression also decays appropriately.
5764 UsualUnaryConversions(E);
5765 } else {
5766 // Otherwise, the va_list argument must be an l-value because
5767 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005768 if (!E->isTypeDependent() &&
5769 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005770 return ExprError();
5771 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005772
Douglas Gregor25990972009-05-19 23:10:31 +00005773 if (!E->isTypeDependent() &&
5774 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005775 return ExprError(Diag(E->getLocStart(),
5776 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005777 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005778 }
Mike Stump9afab102009-02-19 03:04:26 +00005779
Eli Friedman2b128322009-03-23 00:24:07 +00005780 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005781 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005782
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005783 expr.release();
5784 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5785 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005786}
5787
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005788Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005789 // The type of __null will be int or long, depending on the size of
5790 // pointers on the target.
5791 QualType Ty;
5792 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5793 Ty = Context.IntTy;
5794 else
5795 Ty = Context.LongTy;
5796
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005797 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005798}
5799
Chris Lattner005ed752008-01-04 18:04:52 +00005800bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5801 SourceLocation Loc,
5802 QualType DstType, QualType SrcType,
5803 Expr *SrcExpr, const char *Flavor) {
5804 // Decode the result (notice that AST's are still created for extensions).
5805 bool isInvalid = false;
5806 unsigned DiagKind;
5807 switch (ConvTy) {
5808 default: assert(0 && "Unknown conversion type");
5809 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005810 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005811 DiagKind = diag::ext_typecheck_convert_pointer_int;
5812 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005813 case IntToPointer:
5814 DiagKind = diag::ext_typecheck_convert_int_pointer;
5815 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005816 case IncompatiblePointer:
5817 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5818 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005819 case IncompatiblePointerSign:
5820 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5821 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005822 case FunctionVoidPointer:
5823 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5824 break;
5825 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005826 // If the qualifiers lost were because we were applying the
5827 // (deprecated) C++ conversion from a string literal to a char*
5828 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5829 // Ideally, this check would be performed in
5830 // CheckPointerTypesForAssignment. However, that would require a
5831 // bit of refactoring (so that the second argument is an
5832 // expression, rather than a type), which should be done as part
5833 // of a larger effort to fix CheckPointerTypesForAssignment for
5834 // C++ semantics.
5835 if (getLangOptions().CPlusPlus &&
5836 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5837 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005838 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5839 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005840 case IntToBlockPointer:
5841 DiagKind = diag::err_int_to_block_pointer;
5842 break;
5843 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005844 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005845 break;
Steve Naroff19608432008-10-14 22:18:38 +00005846 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005847 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005848 // it can give a more specific diagnostic.
5849 DiagKind = diag::warn_incompatible_qualified_id;
5850 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005851 case IncompatibleVectors:
5852 DiagKind = diag::warn_incompatible_vectors;
5853 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005854 case Incompatible:
5855 DiagKind = diag::err_typecheck_convert_incompatible;
5856 isInvalid = true;
5857 break;
5858 }
Mike Stump9afab102009-02-19 03:04:26 +00005859
Chris Lattner271d4c22008-11-24 05:29:24 +00005860 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5861 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005862 return isInvalid;
5863}
Anders Carlssond5201b92008-11-30 19:50:32 +00005864
Chris Lattnereec8ae22009-04-25 21:59:05 +00005865bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005866 llvm::APSInt ICEResult;
5867 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5868 if (Result)
5869 *Result = ICEResult;
5870 return false;
5871 }
5872
Anders Carlssond5201b92008-11-30 19:50:32 +00005873 Expr::EvalResult EvalResult;
5874
Mike Stump9afab102009-02-19 03:04:26 +00005875 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005876 EvalResult.HasSideEffects) {
5877 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5878
5879 if (EvalResult.Diag) {
5880 // We only show the note if it's not the usual "invalid subexpression"
5881 // or if it's actually in a subexpression.
5882 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5883 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5884 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5885 }
Mike Stump9afab102009-02-19 03:04:26 +00005886
Anders Carlssond5201b92008-11-30 19:50:32 +00005887 return true;
5888 }
5889
Eli Friedmance329412009-04-25 22:26:58 +00005890 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5891 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005892
Eli Friedmance329412009-04-25 22:26:58 +00005893 if (EvalResult.Diag &&
5894 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5895 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005896
Anders Carlssond5201b92008-11-30 19:50:32 +00005897 if (Result)
5898 *Result = EvalResult.Val.getInt();
5899 return false;
5900}
Douglas Gregor98189262009-06-19 23:52:42 +00005901
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005902Sema::ExpressionEvaluationContext
5903Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5904 // Introduce a new set of potentially referenced declarations to the stack.
5905 if (NewContext == PotentiallyPotentiallyEvaluated)
5906 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5907
5908 std::swap(ExprEvalContext, NewContext);
5909 return NewContext;
5910}
5911
5912void
5913Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5914 ExpressionEvaluationContext NewContext) {
5915 ExprEvalContext = NewContext;
5916
5917 if (OldContext == PotentiallyPotentiallyEvaluated) {
5918 // Mark any remaining declarations in the current position of the stack
5919 // as "referenced". If they were not meant to be referenced, semantic
5920 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5921 PotentiallyReferencedDecls RemainingDecls;
5922 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5923 PotentiallyReferencedDeclStack.pop_back();
5924
5925 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5926 IEnd = RemainingDecls.end();
5927 I != IEnd; ++I)
5928 MarkDeclarationReferenced(I->first, I->second);
5929 }
5930}
Douglas Gregor98189262009-06-19 23:52:42 +00005931
5932/// \brief Note that the given declaration was referenced in the source code.
5933///
5934/// This routine should be invoke whenever a given declaration is referenced
5935/// in the source code, and where that reference occurred. If this declaration
5936/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5937/// C99 6.9p3), then the declaration will be marked as used.
5938///
5939/// \param Loc the location where the declaration was referenced.
5940///
5941/// \param D the declaration that has been referenced by the source code.
5942void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5943 assert(D && "No declaration?");
5944
Douglas Gregorcad27f62009-06-22 23:06:13 +00005945 if (D->isUsed())
5946 return;
5947
Douglas Gregor98189262009-06-19 23:52:42 +00005948 // Mark a parameter declaration "used", regardless of whether we're in a
5949 // template or not.
5950 if (isa<ParmVarDecl>(D))
5951 D->setUsed(true);
5952
5953 // Do not mark anything as "used" within a dependent context; wait for
5954 // an instantiation.
5955 if (CurContext->isDependentContext())
5956 return;
5957
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005958 switch (ExprEvalContext) {
5959 case Unevaluated:
5960 // We are in an expression that is not potentially evaluated; do nothing.
5961 return;
5962
5963 case PotentiallyEvaluated:
5964 // We are in a potentially-evaluated expression, so this declaration is
5965 // "used"; handle this below.
5966 break;
5967
5968 case PotentiallyPotentiallyEvaluated:
5969 // We are in an expression that may be potentially evaluated; queue this
5970 // declaration reference until we know whether the expression is
5971 // potentially evaluated.
5972 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5973 return;
5974 }
5975
Douglas Gregor98189262009-06-19 23:52:42 +00005976 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005977 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005978 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005979 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5980 if (!Constructor->isUsed())
5981 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005982 } else if (Constructor->isImplicit() &&
5983 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005984 if (!Constructor->isUsed())
5985 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5986 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005987 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5988 if (Destructor->isImplicit() && !Destructor->isUsed())
5989 DefineImplicitDestructor(Loc, Destructor);
5990
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005991 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5992 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5993 MethodDecl->getOverloadedOperator() == OO_Equal) {
5994 if (!MethodDecl->isUsed())
5995 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5996 }
5997 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005998 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005999 // Implicit instantiation of function templates and member functions of
6000 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006001 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006002 // FIXME: distinguish between implicit instantiations of function
6003 // templates and explicit specializations (the latter don't get
6004 // instantiated, naturally).
6005 if (Function->getInstantiatedFromMemberFunction() ||
6006 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006007 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006008 }
6009
6010
Douglas Gregor98189262009-06-19 23:52:42 +00006011 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006012 Function->setUsed(true);
6013 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006014 }
Douglas Gregor98189262009-06-19 23:52:42 +00006015
6016 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006017 // Implicit instantiation of static data members of class templates.
6018 // FIXME: distinguish between implicit instantiations (which we need to
6019 // actually instantiate) and explicit specializations.
6020 if (Var->isStaticDataMember() &&
6021 Var->getInstantiatedFromStaticDataMember())
6022 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6023
Douglas Gregor98189262009-06-19 23:52:42 +00006024 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006025
Douglas Gregor98189262009-06-19 23:52:42 +00006026 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006027 return;
6028}
Douglas Gregor98189262009-06-19 23:52:42 +00006029}
6030