blob: 6a7bca0165a65c2d736b5ae74688bae1f6401b25 [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
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
Douglas Gregorc55b0b02009-04-09 21:40:53 +000061 MD = Impl->getClassInterface()->getMethod(Context,
62 MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
64 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
65 }
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
83 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{
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
99 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
104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the
105 // same common base class. Then we won't be needing two versions of
106 // the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000107 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000108 bool warnNotEnoughArgs = false;
109 int isMethod = 0;
110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = MD->param_end();
113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
120 isMethod = 1;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000121 }
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000122 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
123 // skip over named parameters.
124 ObjCMethodDecl::param_iterator P, E = FD->param_end();
125 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
126 if (nullPos)
127 --nullPos;
128 else
129 ++i;
130 }
131 warnNotEnoughArgs = (P != E || i >= NumArgs);
132 }
133 else
134 return;
135
136 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000137 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000138 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000139 return;
140 }
141 int sentinel = i;
142 while (sentinelPos > 0 && i < NumArgs-1) {
143 --sentinelPos;
144 ++i;
145 }
146 if (sentinelPos > 0) {
147 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000148 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000149 return;
150 }
151 while (i < NumArgs-1) {
152 ++i;
153 ++sentinel;
154 }
155 Expr *sentinelExpr = Args[sentinel];
156 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000158 Diag(Loc, diag::warn_missing_sentinel) << isMethod << isMethod;
159 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000160 }
161 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000162}
163
Douglas Gregor3bb30002009-02-26 21:00:50 +0000164SourceRange Sema::getExprRange(ExprTy *E) const {
165 Expr *Ex = (Expr *)E;
166 return Ex? Ex->getSourceRange() : SourceRange();
167}
168
Chris Lattner299b8842008-07-25 21:10:04 +0000169//===----------------------------------------------------------------------===//
170// Standard Promotions and Conversions
171//===----------------------------------------------------------------------===//
172
Chris Lattner299b8842008-07-25 21:10:04 +0000173/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
174void Sema::DefaultFunctionArrayConversion(Expr *&E) {
175 QualType Ty = E->getType();
176 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
177
Chris Lattner299b8842008-07-25 21:10:04 +0000178 if (Ty->isFunctionType())
179 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000180 else if (Ty->isArrayType()) {
181 // In C90 mode, arrays only promote to pointers if the array expression is
182 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
183 // type 'array of type' is converted to an expression that has type 'pointer
184 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
185 // that has type 'array of type' ...". The relevant change is "an lvalue"
186 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000187 //
188 // C++ 4.2p1:
189 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
190 // T" can be converted to an rvalue of type "pointer to T".
191 //
192 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
193 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000194 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
195 }
Chris Lattner299b8842008-07-25 21:10:04 +0000196}
197
Douglas Gregor70b307e2009-05-01 20:41:21 +0000198/// \brief Whether this is a promotable bitfield reference according
199/// to C99 6.3.1.1p2, bullet 2.
200///
201/// \returns the type this bit-field will promote to, or NULL if no
202/// promotion occurs.
203static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000204 FieldDecl *Field = E->getBitField();
205 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000206 return QualType();
207
208 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
209 if (!BT)
210 return QualType();
211
212 if (BT->getKind() != BuiltinType::Bool &&
213 BT->getKind() != BuiltinType::Int &&
214 BT->getKind() != BuiltinType::UInt)
215 return QualType();
216
217 llvm::APSInt BitWidthAP;
218 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
219 return QualType();
220
221 uint64_t BitWidth = BitWidthAP.getZExtValue();
222 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
223 if (BitWidth < IntSize ||
224 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
225 return Context.IntTy;
226
227 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
228 return Context.UnsignedIntTy;
229
230 return QualType();
231}
232
Chris Lattner299b8842008-07-25 21:10:04 +0000233/// UsualUnaryConversions - Performs various conversions that are common to most
234/// operators (C99 6.3). The conversions of array and function types are
235/// sometimes surpressed. For example, the array->pointer conversion doesn't
236/// apply if the array is an argument to the sizeof or address (&) operators.
237/// In these instances, this routine should *not* be called.
238Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
239 QualType Ty = Expr->getType();
240 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
241
Douglas Gregor70b307e2009-05-01 20:41:21 +0000242 // C99 6.3.1.1p2:
243 //
244 // The following may be used in an expression wherever an int or
245 // unsigned int may be used:
246 // - an object or expression with an integer type whose integer
247 // conversion rank is less than or equal to the rank of int
248 // and unsigned int.
249 // - A bit-field of type _Bool, int, signed int, or unsigned int.
250 //
251 // If an int can represent all values of the original type, the
252 // value is converted to an int; otherwise, it is converted to an
253 // unsigned int. These are called the integer promotions. All
254 // other types are unchanged by the integer promotions.
255 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000256 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000257 return Expr;
258 } else {
259 QualType T = isPromotableBitField(Expr, Context);
260 if (!T.isNull()) {
261 ImpCastExprToType(Expr, T);
262 return Expr;
263 }
264 }
265
266 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return Expr;
268}
269
Chris Lattner9305c3d2008-07-25 22:25:12 +0000270/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
271/// do not have a prototype. Arguments that have type float are promoted to
272/// double. All other argument types are converted by UsualUnaryConversions().
273void Sema::DefaultArgumentPromotion(Expr *&Expr) {
274 QualType Ty = Expr->getType();
275 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
276
277 // If this is a 'float' (CVR qualified or typedef) promote to double.
278 if (const BuiltinType *BT = Ty->getAsBuiltinType())
279 if (BT->getKind() == BuiltinType::Float)
280 return ImpCastExprToType(Expr, Context.DoubleTy);
281
282 UsualUnaryConversions(Expr);
283}
284
Chris Lattner81f00ed2009-04-12 08:11:20 +0000285/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
286/// will warn if the resulting type is not a POD type, and rejects ObjC
287/// interfaces passed by value. This returns true if the argument type is
288/// completely illegal.
289bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000290 DefaultArgumentPromotion(Expr);
291
Chris Lattner81f00ed2009-04-12 08:11:20 +0000292 if (Expr->getType()->isObjCInterfaceType()) {
293 Diag(Expr->getLocStart(),
294 diag::err_cannot_pass_objc_interface_to_vararg)
295 << Expr->getType() << CT;
296 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000297 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000298
299 if (!Expr->getType()->isPODType())
300 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
301 << Expr->getType() << CT;
302
303 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000304}
305
306
Chris Lattner299b8842008-07-25 21:10:04 +0000307/// UsualArithmeticConversions - Performs various conversions that are common to
308/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
309/// routine returns the first non-arithmetic type found. The client is
310/// responsible for emitting appropriate error diagnostics.
311/// FIXME: verify the conversion rules for "complex int" are consistent with
312/// GCC.
313QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
314 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000315 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000316 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000317
318 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000319
Chris Lattner299b8842008-07-25 21:10:04 +0000320 // For conversion purposes, we ignore any qualifiers.
321 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000322 QualType lhs =
323 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
324 QualType rhs =
325 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000326
327 // If both types are identical, no conversion is needed.
328 if (lhs == rhs)
329 return lhs;
330
331 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
332 // The caller can deal with this (e.g. pointer + int).
333 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
334 return lhs;
335
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000336 // Perform bitfield promotions.
337 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
338 if (!LHSBitfieldPromoteTy.isNull())
339 lhs = LHSBitfieldPromoteTy;
340 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
341 if (!RHSBitfieldPromoteTy.isNull())
342 rhs = RHSBitfieldPromoteTy;
343
Douglas Gregor70d26122008-11-12 17:17:38 +0000344 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000345 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000346 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000347 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000348 return destType;
349}
350
351QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
352 // Perform the usual unary conversions. We do this early so that
353 // integral promotions to "int" can allow us to exit early, in the
354 // lhs == rhs check. Also, for conversion purposes, we ignore any
355 // qualifiers. For example, "const float" and "float" are
356 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000357 if (lhs->isPromotableIntegerType())
358 lhs = Context.IntTy;
359 else
360 lhs = lhs.getUnqualifiedType();
361 if (rhs->isPromotableIntegerType())
362 rhs = Context.IntTy;
363 else
364 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000365
Chris Lattner299b8842008-07-25 21:10:04 +0000366 // If both types are identical, no conversion is needed.
367 if (lhs == rhs)
368 return lhs;
369
370 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
371 // The caller can deal with this (e.g. pointer + int).
372 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
373 return lhs;
374
375 // At this point, we have two different arithmetic types.
376
377 // Handle complex types first (C99 6.3.1.8p1).
378 if (lhs->isComplexType() || rhs->isComplexType()) {
379 // if we have an integer operand, the result is the complex type.
380 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
381 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000382 return lhs;
383 }
384 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
385 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000386 return rhs;
387 }
388 // This handles complex/complex, complex/float, or float/complex.
389 // When both operands are complex, the shorter operand is converted to the
390 // type of the longer, and that is the type of the result. This corresponds
391 // to what is done when combining two real floating-point operands.
392 // The fun begins when size promotion occur across type domains.
393 // From H&S 6.3.4: When one operand is complex and the other is a real
394 // floating-point type, the less precise type is converted, within it's
395 // real or complex domain, to the precision of the other type. For example,
396 // when combining a "long double" with a "double _Complex", the
397 // "double _Complex" is promoted to "long double _Complex".
398 int result = Context.getFloatingTypeOrder(lhs, rhs);
399
400 if (result > 0) { // The left side is bigger, convert rhs.
401 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000402 } else if (result < 0) { // The right side is bigger, convert lhs.
403 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000404 }
405 // At this point, lhs and rhs have the same rank/size. Now, make sure the
406 // domains match. This is a requirement for our implementation, C99
407 // does not require this promotion.
408 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
409 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000410 return rhs;
411 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000412 return lhs;
413 }
414 }
415 return lhs; // The domain/size match exactly.
416 }
417 // Now handle "real" floating types (i.e. float, double, long double).
418 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
419 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000420 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000421 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000422 return lhs;
423 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000424 if (rhs->isComplexIntegerType()) {
425 // convert rhs to the complex floating point type.
426 return Context.getComplexType(lhs);
427 }
428 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000429 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000430 return rhs;
431 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000432 if (lhs->isComplexIntegerType()) {
433 // convert lhs to the complex floating point type.
434 return Context.getComplexType(rhs);
435 }
Chris Lattner299b8842008-07-25 21:10:04 +0000436 // We have two real floating types, float/complex combos were handled above.
437 // Convert the smaller operand to the bigger result.
438 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000439 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000440 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000441 assert(result < 0 && "illegal float comparison");
442 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000443 }
444 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
445 // Handle GCC complex int extension.
446 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
447 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
448
449 if (lhsComplexInt && rhsComplexInt) {
450 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000451 rhsComplexInt->getElementType()) >= 0)
452 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000453 return rhs;
454 } else if (lhsComplexInt && rhs->isIntegerType()) {
455 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000456 return lhs;
457 } else if (rhsComplexInt && lhs->isIntegerType()) {
458 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000459 return rhs;
460 }
461 }
462 // Finally, we have two differing integer types.
463 // The rules for this case are in C99 6.3.1.8
464 int compare = Context.getIntegerTypeOrder(lhs, rhs);
465 bool lhsSigned = lhs->isSignedIntegerType(),
466 rhsSigned = rhs->isSignedIntegerType();
467 QualType destType;
468 if (lhsSigned == rhsSigned) {
469 // Same signedness; use the higher-ranked type
470 destType = compare >= 0 ? lhs : rhs;
471 } else if (compare != (lhsSigned ? 1 : -1)) {
472 // The unsigned type has greater than or equal rank to the
473 // signed type, so use the unsigned type
474 destType = lhsSigned ? rhs : lhs;
475 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
476 // The two types are different widths; if we are here, that
477 // means the signed type is larger than the unsigned type, so
478 // use the signed type.
479 destType = lhsSigned ? lhs : rhs;
480 } else {
481 // The signed type is higher-ranked than the unsigned type,
482 // but isn't actually any bigger (like unsigned int and long
483 // on most 32-bit systems). Use the unsigned type corresponding
484 // to the signed type.
485 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
486 }
Chris Lattner299b8842008-07-25 21:10:04 +0000487 return destType;
488}
489
490//===----------------------------------------------------------------------===//
491// Semantic Analysis for various Expression Types
492//===----------------------------------------------------------------------===//
493
494
Steve Naroff87d58b42007-09-16 03:34:24 +0000495/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000496/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
497/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
498/// multiple tokens. However, the common case is that StringToks points to one
499/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000500///
501Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000502Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000503 assert(NumStringToks && "Must have at least one string!");
504
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000505 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000506 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000507 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000508
509 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
510 for (unsigned i = 0; i != NumStringToks; ++i)
511 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000512
Chris Lattnera6dcce32008-02-11 00:02:17 +0000513 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000514 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000515 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000516
517 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
518 if (getLangOptions().CPlusPlus)
519 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520
Chris Lattnera6dcce32008-02-11 00:02:17 +0000521 // Get an array type for the string, according to C99 6.4.5. This includes
522 // the nul terminator character as well as the string length for pascal
523 // strings.
524 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000525 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000526 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000527
Chris Lattner4b009652007-07-25 00:24:17 +0000528 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000529 return Owned(StringLiteral::Create(Context, Literal.GetString(),
530 Literal.GetStringLength(),
531 Literal.AnyWide, StrTy,
532 &StringTokLocs[0],
533 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000534}
535
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000536/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
537/// CurBlock to VD should cause it to be snapshotted (as we do for auto
538/// variables defined outside the block) or false if this is not needed (e.g.
539/// for values inside the block or for globals).
540///
Chris Lattner0b464252009-04-21 22:26:47 +0000541/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
542/// up-to-date.
543///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000544static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
545 ValueDecl *VD) {
546 // If the value is defined inside the block, we couldn't snapshot it even if
547 // we wanted to.
548 if (CurBlock->TheDecl == VD->getDeclContext())
549 return false;
550
551 // If this is an enum constant or function, it is constant, don't snapshot.
552 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
553 return false;
554
555 // If this is a reference to an extern, static, or global variable, no need to
556 // snapshot it.
557 // FIXME: What about 'const' variables in C++?
558 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000559 if (!Var->hasLocalStorage())
560 return false;
561
562 // Blocks that have these can't be constant.
563 CurBlock->hasBlockDeclRefExprs = true;
564
565 // If we have nested blocks, the decl may be declared in an outer block (in
566 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
567 // be defined outside all of the current blocks (in which case the blocks do
568 // all get the bit). Walk the nesting chain.
569 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
570 NextBlock = NextBlock->PrevBlockInfo) {
571 // If we found the defining block for the variable, don't mark the block as
572 // having a reference outside it.
573 if (NextBlock->TheDecl == VD->getDeclContext())
574 break;
575
576 // Otherwise, the DeclRef from the inner block causes the outer one to need
577 // a snapshot as well.
578 NextBlock->hasBlockDeclRefExprs = true;
579 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000580
581 return true;
582}
583
584
585
Steve Naroff0acc9c92007-09-15 18:49:24 +0000586/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000587/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000588/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000589/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000590/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000591Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
592 IdentifierInfo &II,
593 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000594 const CXXScopeSpec *SS,
595 bool isAddressOfOperand) {
596 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000597 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000598}
599
Douglas Gregor566782a2009-01-06 05:10:23 +0000600/// BuildDeclRefExpr - Build either a DeclRefExpr or a
601/// QualifiedDeclRefExpr based on whether or not SS is a
602/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000603DeclRefExpr *
604Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
605 bool TypeDependent, bool ValueDependent,
606 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000607 if (SS && !SS->isEmpty()) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000608 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
609 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000610 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000611 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000612 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000613}
614
Douglas Gregor723d3332009-01-07 00:43:41 +0000615/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
616/// variable corresponding to the anonymous union or struct whose type
617/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000618static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
619 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000620 assert(Record->isAnonymousStructOrUnion() &&
621 "Record must be an anonymous struct or union!");
622
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000623 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000624 // be an O(1) operation rather than a slow walk through DeclContext's
625 // vector (which itself will be eliminated). DeclGroups might make
626 // this even better.
627 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000628 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
629 DEnd = Ctx->decls_end(Context);
Douglas Gregor723d3332009-01-07 00:43:41 +0000630 D != DEnd; ++D) {
631 if (*D == Record) {
632 // The object for the anonymous struct/union directly
633 // follows its type in the list of declarations.
634 ++D;
635 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000636 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000637 return *D;
638 }
639 }
640
641 assert(false && "Missing object for anonymous record");
642 return 0;
643}
644
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000645/// \brief Given a field that represents a member of an anonymous
646/// struct/union, build the path from that field's context to the
647/// actual member.
648///
649/// Construct the sequence of field member references we'll have to
650/// perform to get to the field in the anonymous union/struct. The
651/// list of members is built from the field outward, so traverse it
652/// backwards to go from an object in the current context to the field
653/// we found.
654///
655/// \returns The variable from which the field access should begin,
656/// for an anonymous struct/union that is not a member of another
657/// class. Otherwise, returns NULL.
658VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
659 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000660 assert(Field->getDeclContext()->isRecord() &&
661 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
662 && "Field must be stored inside an anonymous struct or union");
663
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000664 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000665 VarDecl *BaseObject = 0;
666 DeclContext *Ctx = Field->getDeclContext();
667 do {
668 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000669 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000670 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000671 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000672 else {
673 BaseObject = cast<VarDecl>(AnonObject);
674 break;
675 }
676 Ctx = Ctx->getParent();
677 } while (Ctx->isRecord() &&
678 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000679
680 return BaseObject;
681}
682
683Sema::OwningExprResult
684Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
685 FieldDecl *Field,
686 Expr *BaseObjectExpr,
687 SourceLocation OpLoc) {
688 llvm::SmallVector<FieldDecl *, 4> AnonFields;
689 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
690 AnonFields);
691
Douglas Gregor723d3332009-01-07 00:43:41 +0000692 // Build the expression that refers to the base object, from
693 // which we will build a sequence of member references to each
694 // of the anonymous union objects and, eventually, the field we
695 // found via name lookup.
696 bool BaseObjectIsPointer = false;
697 unsigned ExtraQuals = 0;
698 if (BaseObject) {
699 // BaseObject is an anonymous struct/union variable (and is,
700 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000701 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000702 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000703 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000704 ExtraQuals
705 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
706 } else if (BaseObjectExpr) {
707 // The caller provided the base object expression. Determine
708 // whether its a pointer and whether it adds any qualifiers to the
709 // anonymous struct/union fields we're looking into.
710 QualType ObjectType = BaseObjectExpr->getType();
711 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
712 BaseObjectIsPointer = true;
713 ObjectType = ObjectPtr->getPointeeType();
714 }
715 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
716 } else {
717 // We've found a member of an anonymous struct/union that is
718 // inside a non-anonymous struct/union, so in a well-formed
719 // program our base object expression is "this".
720 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
721 if (!MD->isStatic()) {
722 QualType AnonFieldType
723 = Context.getTagDeclType(
724 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
725 QualType ThisType = Context.getTagDeclType(MD->getParent());
726 if ((Context.getCanonicalType(AnonFieldType)
727 == Context.getCanonicalType(ThisType)) ||
728 IsDerivedFrom(ThisType, AnonFieldType)) {
729 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000730 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000731 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000732 BaseObjectIsPointer = true;
733 }
734 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000735 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
736 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000737 }
738 ExtraQuals = MD->getTypeQualifiers();
739 }
740
741 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000742 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
743 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000744 }
745
746 // Build the implicit member references to the field of the
747 // anonymous struct/union.
748 Expr *Result = BaseObjectExpr;
749 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
750 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
751 FI != FIEnd; ++FI) {
752 QualType MemberType = (*FI)->getType();
753 if (!(*FI)->isMutable()) {
754 unsigned combinedQualifiers
755 = MemberType.getCVRQualifiers() | ExtraQuals;
756 MemberType = MemberType.getQualifiedType(combinedQualifiers);
757 }
Steve Naroff774e4152009-01-21 00:14:39 +0000758 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
759 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000760 BaseObjectIsPointer = false;
761 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000762 }
763
Sebastian Redlcd883f72009-01-18 18:53:16 +0000764 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000765}
766
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000767/// ActOnDeclarationNameExpr - The parser has read some kind of name
768/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
769/// performs lookup on that name and returns an expression that refers
770/// to that name. This routine isn't directly called from the parser,
771/// because the parser doesn't know about DeclarationName. Rather,
772/// this routine is called by ActOnIdentifierExpr,
773/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
774/// which form the DeclarationName from the corresponding syntactic
775/// forms.
776///
777/// HasTrailingLParen indicates whether this identifier is used in a
778/// function call context. LookupCtx is only used for a C++
779/// qualified-id (foo::bar) to indicate the class or namespace that
780/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000781///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000782/// isAddressOfOperand means that this expression is the direct operand
783/// of an address-of operator. This matters because this is the only
784/// situation where a qualified name referencing a non-static member may
785/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000786Sema::OwningExprResult
787Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
788 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000789 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000790 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000791 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000792 if (SS && SS->isInvalid())
793 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000794
795 // C++ [temp.dep.expr]p3:
796 // An id-expression is type-dependent if it contains:
797 // -- a nested-name-specifier that contains a class-name that
798 // names a dependent type.
799 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000800 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
801 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000802 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000803 }
804
Douglas Gregor411889e2009-02-13 23:20:09 +0000805 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
806 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000807
Sebastian Redlcd883f72009-01-18 18:53:16 +0000808 if (Lookup.isAmbiguous()) {
809 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
810 SS && SS->isSet() ? SS->getRange()
811 : SourceRange());
812 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000813 }
814
815 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000816
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000817 // If this reference is in an Objective-C method, then ivar lookup happens as
818 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000819 IdentifierInfo *II = Name.getAsIdentifierInfo();
820 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000821 // There are two cases to handle here. 1) scoped lookup could have failed,
822 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000823 // found a decl, but that decl is outside the current instance method (i.e.
824 // a global variable). In these two cases, we do a lookup for an ivar with
825 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000826 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000827 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000828 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000829 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
830 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000831 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000832 if (DiagnoseUseOfDecl(IV, Loc))
833 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000834
835 // If we're referencing an invalid decl, just return this as a silent
836 // error node. The error diagnostic was already emitted on the decl.
837 if (IV->isInvalidDecl())
838 return ExprError();
839
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000840 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
841 // If a class method attemps to use a free standing ivar, this is
842 // an error.
843 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
844 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
845 << IV->getDeclName());
846 // If a class method uses a global variable, even if an ivar with
847 // same name exists, use the global.
848 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000849 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
850 ClassDeclared != IFace)
851 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000852 // FIXME: This should use a new expr for a direct reference, don't turn
853 // this into Self->ivar, just return a BareIVarExpr or something.
854 IdentifierInfo &II = Context.Idents.get("self");
855 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000856 return Owned(new (Context)
857 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000858 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000859 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000860 }
861 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000862 else if (getCurMethodDecl()->isInstanceMethod()) {
863 // We should warn if a local variable hides an ivar.
864 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000865 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000866 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
867 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000868 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
869 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000870 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000871 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000872 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000873 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000874 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000875 QualType T;
876
877 if (getCurMethodDecl()->isInstanceMethod())
878 T = Context.getPointerType(Context.getObjCInterfaceType(
879 getCurMethodDecl()->getClassInterface()));
880 else
881 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000882 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000883 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000884 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000885
Douglas Gregoraa57e862009-02-18 21:56:37 +0000886 // Determine whether this name might be a candidate for
887 // argument-dependent lookup.
888 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
889 HasTrailingLParen;
890
891 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000892 // We've seen something of the form
893 //
894 // identifier(
895 //
896 // and we did not find any entity by the name
897 // "identifier". However, this identifier is still subject to
898 // argument-dependent lookup, so keep track of the name.
899 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
900 Context.OverloadTy,
901 Loc));
902 }
903
Chris Lattner4b009652007-07-25 00:24:17 +0000904 if (D == 0) {
905 // Otherwise, this could be an implicitly declared function reference (legal
906 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000907 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000908 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000909 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000910 else {
911 // If this name wasn't predeclared and if this is not a function call,
912 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000913 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000914 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
915 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000916 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
917 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000918 return ExprError(Diag(Loc, diag::err_undeclared_use)
919 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000920 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000921 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000922 }
923 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000924
Sebastian Redl0c9da212009-02-03 20:19:35 +0000925 // If this is an expression of the form &Class::member, don't build an
926 // implicit member ref, because we want a pointer to the member in general,
927 // not any specific instance's member.
928 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000929 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000930 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000931 QualType DType;
932 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
933 DType = FD->getType().getNonReferenceType();
934 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
935 DType = Method->getType();
936 } else if (isa<OverloadedFunctionDecl>(D)) {
937 DType = Context.OverloadTy;
938 }
939 // Could be an inner type. That's diagnosed below, so ignore it here.
940 if (!DType.isNull()) {
941 // The pointer is type- and value-dependent if it points into something
942 // dependent.
943 bool Dependent = false;
944 for (; DC; DC = DC->getParent()) {
945 // FIXME: could stop early at namespace scope.
946 if (DC->isRecord()) {
947 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
948 if (Context.getTypeDeclType(Record)->isDependentType()) {
949 Dependent = true;
950 break;
951 }
952 }
953 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000954 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000955 }
956 }
957 }
958
Douglas Gregor723d3332009-01-07 00:43:41 +0000959 // We may have found a field within an anonymous union or struct
960 // (C++ [class.union]).
961 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
962 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
963 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000964
Douglas Gregor3257fb52008-12-22 05:46:06 +0000965 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
966 if (!MD->isStatic()) {
967 // C++ [class.mfct.nonstatic]p2:
968 // [...] if name lookup (3.4.1) resolves the name in the
969 // id-expression to a nonstatic nontype member of class X or of
970 // a base class of X, the id-expression is transformed into a
971 // class member access expression (5.2.5) using (*this) (9.3.2)
972 // as the postfix-expression to the left of the '.' operator.
973 DeclContext *Ctx = 0;
974 QualType MemberType;
975 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
976 Ctx = FD->getDeclContext();
977 MemberType = FD->getType();
978
979 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
980 MemberType = RefType->getPointeeType();
981 else if (!FD->isMutable()) {
982 unsigned combinedQualifiers
983 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
984 MemberType = MemberType.getQualifiedType(combinedQualifiers);
985 }
986 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
987 if (!Method->isStatic()) {
988 Ctx = Method->getParent();
989 MemberType = Method->getType();
990 }
991 } else if (OverloadedFunctionDecl *Ovl
992 = dyn_cast<OverloadedFunctionDecl>(D)) {
993 for (OverloadedFunctionDecl::function_iterator
994 Func = Ovl->function_begin(),
995 FuncEnd = Ovl->function_end();
996 Func != FuncEnd; ++Func) {
997 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
998 if (!DMethod->isStatic()) {
999 Ctx = Ovl->getDeclContext();
1000 MemberType = Context.OverloadTy;
1001 break;
1002 }
1003 }
1004 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001005
1006 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001007 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1008 QualType ThisType = Context.getTagDeclType(MD->getParent());
1009 if ((Context.getCanonicalType(CtxType)
1010 == Context.getCanonicalType(ThisType)) ||
1011 IsDerivedFrom(ThisType, CtxType)) {
1012 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001013 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001014 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +00001015 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001016 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001017 }
1018 }
1019 }
1020 }
1021
Douglas Gregor8acb7272008-12-11 16:49:14 +00001022 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001023 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1024 if (MD->isStatic())
1025 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1027 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001028 }
1029
Douglas Gregor3257fb52008-12-22 05:46:06 +00001030 // Any other ways we could have found the field in a well-formed
1031 // program would have been turned into implicit member expressions
1032 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1034 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001035 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001036
Chris Lattner4b009652007-07-25 00:24:17 +00001037 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001038 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001039 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001041 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001042 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001043
Steve Naroffd6163f32008-09-05 22:11:13 +00001044 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001045 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1047 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001048 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1049 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1050 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +00001051 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052
Douglas Gregoraa57e862009-02-18 21:56:37 +00001053 // Check whether this declaration can be used. Note that we suppress
1054 // this check when we're going to perform argument-dependent lookup
1055 // on this function name, because this might not be the function
1056 // that overload resolution actually selects.
1057 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1058 return ExprError();
1059
Douglas Gregor48840c72008-12-10 23:01:14 +00001060 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +00001061 // Warn about constructs like:
1062 // if (void *X = foo()) { ... } else { X }.
1063 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +00001064 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1065 Scope *CheckS = S;
1066 while (CheckS) {
1067 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00001068 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +00001069 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001070 ExprError(Diag(Loc, diag::warn_value_always_false)
1071 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001072 else
Sebastian Redlcd883f72009-01-18 18:53:16 +00001073 ExprError(Diag(Loc, diag::warn_value_always_zero)
1074 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001075 break;
1076 }
1077
1078 // Move up one more control parent to check again.
1079 CheckS = CheckS->getControlParent();
1080 if (CheckS)
1081 CheckS = CheckS->getParent();
1082 }
1083 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001084 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
1085 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1086 // C99 DR 316 says that, if a function type comes from a
1087 // function definition (without a prototype), that type is only
1088 // used for checking compatibility. Therefore, when referencing
1089 // the function, we pretend that we don't have the full function
1090 // type.
1091 QualType T = Func->getType();
1092 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001093 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1094 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001095 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
1096 }
Douglas Gregor48840c72008-12-10 23:01:14 +00001097 }
Steve Naroffd6163f32008-09-05 22:11:13 +00001098
1099 // Only create DeclRefExpr's for valid Decl's.
1100 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001101 return ExprError();
1102
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001103 // If the identifier reference is inside a block, and it refers to a value
1104 // that is outside the block, create a BlockDeclRefExpr instead of a
1105 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1106 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001107 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001108 // We do not do this for things like enum constants, global variables, etc,
1109 // as they do not get snapshotted.
1110 //
1111 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001112 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001113 // The BlocksAttr indicates the variable is bound by-reference.
1114 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001115 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001116
Steve Naroff52059382008-10-10 01:28:17 +00001117 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001118 ExprTy.addConst();
1119 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +00001120 }
1121 // If this reference is not in a block or if the referenced variable is
1122 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001123
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001124 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001125 bool ValueDependent = false;
1126 if (getLangOptions().CPlusPlus) {
1127 // C++ [temp.dep.expr]p3:
1128 // An id-expression is type-dependent if it contains:
1129 // - an identifier that was declared with a dependent type,
1130 if (VD->getType()->isDependentType())
1131 TypeDependent = true;
1132 // - FIXME: a template-id that is dependent,
1133 // - a conversion-function-id that specifies a dependent type,
1134 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1135 Name.getCXXNameType()->isDependentType())
1136 TypeDependent = true;
1137 // - a nested-name-specifier that contains a class-name that
1138 // names a dependent type.
1139 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001140 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001141 DC; DC = DC->getParent()) {
1142 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001143 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001144 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1145 if (Context.getTypeDeclType(Record)->isDependentType()) {
1146 TypeDependent = true;
1147 break;
1148 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001149 }
1150 }
1151 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001152
Douglas Gregora5d84612008-12-10 20:57:37 +00001153 // C++ [temp.dep.constexpr]p2:
1154 //
1155 // An identifier is value-dependent if it is:
1156 // - a name declared with a dependent type,
1157 if (TypeDependent)
1158 ValueDependent = true;
1159 // - the name of a non-type template parameter,
1160 else if (isa<NonTypeTemplateParmDecl>(VD))
1161 ValueDependent = true;
1162 // - a constant with integral or enumeration type and is
1163 // initialized with an expression that is value-dependent
1164 // (FIXME!).
1165 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001166
Sebastian Redlcd883f72009-01-18 18:53:16 +00001167 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1168 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +00001169}
1170
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1172 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001173 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001174
Chris Lattner4b009652007-07-25 00:24:17 +00001175 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001176 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001177 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1178 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1179 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001180 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001181
Chris Lattner7e637512008-01-12 08:14:25 +00001182 // Pre-defined identifiers are of type char[x], where x is the length of the
1183 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001184 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001185 if (FunctionDecl *FD = getCurFunctionDecl())
1186 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001187 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1188 Length = MD->getSynthesizedMethodSize();
1189 else {
1190 Diag(Loc, diag::ext_predef_outside_function);
1191 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1192 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1193 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001194
1195
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001196 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001197 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001198 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001199 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001200}
1201
Sebastian Redlcd883f72009-01-18 18:53:16 +00001202Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001203 llvm::SmallString<16> CharBuffer;
1204 CharBuffer.resize(Tok.getLength());
1205 const char *ThisTokBegin = &CharBuffer[0];
1206 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001207
Chris Lattner4b009652007-07-25 00:24:17 +00001208 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1209 Tok.getLocation(), PP);
1210 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001211 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001212
1213 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1214
Sebastian Redl75324932009-01-20 22:23:13 +00001215 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1216 Literal.isWide(),
1217 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001218}
1219
Sebastian Redlcd883f72009-01-18 18:53:16 +00001220Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1221 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001222 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1223 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001224 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001225 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001226 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001227 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001228 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001229
Chris Lattner4b009652007-07-25 00:24:17 +00001230 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001231 // Add padding so that NumericLiteralParser can overread by one character.
1232 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001233 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001234
Chris Lattner4b009652007-07-25 00:24:17 +00001235 // Get the spelling of the token, which eliminates trigraphs, etc.
1236 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001237
Chris Lattner4b009652007-07-25 00:24:17 +00001238 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1239 Tok.getLocation(), PP);
1240 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001241 return ExprError();
1242
Chris Lattner1de66eb2007-08-26 03:42:43 +00001243 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001244
Chris Lattner1de66eb2007-08-26 03:42:43 +00001245 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001246 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001247 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001248 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001249 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001250 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001251 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001252 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001253
1254 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1255
Ted Kremenekddedbe22007-11-29 00:56:49 +00001256 // isExact will be set by GetFloatValue().
1257 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001258 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1259 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001260
Chris Lattner1de66eb2007-08-26 03:42:43 +00001261 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001262 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001263 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001264 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001265
Neil Booth7421e9c2007-08-29 22:00:19 +00001266 // long long is a C99 feature.
1267 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001268 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001269 Diag(Tok.getLocation(), diag::ext_longlong);
1270
Chris Lattner4b009652007-07-25 00:24:17 +00001271 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001272 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001273
Chris Lattner4b009652007-07-25 00:24:17 +00001274 if (Literal.GetIntegerValue(ResultVal)) {
1275 // If this value didn't fit into uintmax_t, warn and force to ull.
1276 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001277 Ty = Context.UnsignedLongLongTy;
1278 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001279 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001280 } else {
1281 // If this value fits into a ULL, try to figure out what else it fits into
1282 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1285 // be an unsigned int.
1286 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1287
1288 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001289 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001290 if (!Literal.isLong && !Literal.isLongLong) {
1291 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001292 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001293
Chris Lattner4b009652007-07-25 00:24:17 +00001294 // Does it fit in a unsigned int?
1295 if (ResultVal.isIntN(IntSize)) {
1296 // Does it fit in a signed int?
1297 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001298 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001299 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001300 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001301 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001302 }
Chris Lattner4b009652007-07-25 00:24:17 +00001303 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001304
Chris Lattner4b009652007-07-25 00:24:17 +00001305 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001306 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001307 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001308
Chris Lattner4b009652007-07-25 00:24:17 +00001309 // Does it fit in a unsigned long?
1310 if (ResultVal.isIntN(LongSize)) {
1311 // Does it fit in a signed long?
1312 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001313 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001314 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001315 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001316 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001317 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001318 }
1319
Chris Lattner4b009652007-07-25 00:24:17 +00001320 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001321 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001322 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001323
Chris Lattner4b009652007-07-25 00:24:17 +00001324 // Does it fit in a unsigned long long?
1325 if (ResultVal.isIntN(LongLongSize)) {
1326 // Does it fit in a signed long long?
1327 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001328 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001329 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001330 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001331 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001332 }
1333 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001334
Chris Lattner4b009652007-07-25 00:24:17 +00001335 // If we still couldn't decide a type, we probably have something that
1336 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001337 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001338 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001339 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001340 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001341 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001342
Chris Lattnere4068872008-05-09 05:59:00 +00001343 if (ResultVal.getBitWidth() != Width)
1344 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001345 }
Sebastian Redl75324932009-01-20 22:23:13 +00001346 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001347 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001348
Chris Lattner1de66eb2007-08-26 03:42:43 +00001349 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1350 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001351 Res = new (Context) ImaginaryLiteral(Res,
1352 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001353
1354 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001355}
1356
Sebastian Redlcd883f72009-01-18 18:53:16 +00001357Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1358 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001359 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001360 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001361 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001362}
1363
1364/// The UsualUnaryConversions() function is *not* called by this routine.
1365/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001366bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001367 SourceLocation OpLoc,
1368 const SourceRange &ExprRange,
1369 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001370 if (exprType->isDependentType())
1371 return false;
1372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001374 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001375 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001376 if (isSizeof)
1377 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1378 return false;
1379 }
1380
Chris Lattner95933c12009-04-24 00:30:45 +00001381 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001382 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001383 Diag(OpLoc, diag::ext_sizeof_void_type)
1384 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001385 return false;
1386 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001387
Chris Lattner95933c12009-04-24 00:30:45 +00001388 if (RequireCompleteType(OpLoc, exprType,
1389 isSizeof ? diag::err_sizeof_incomplete_type :
1390 diag::err_alignof_incomplete_type,
1391 ExprRange))
1392 return true;
1393
1394 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001395 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001396 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001397 << exprType << isSizeof << ExprRange;
1398 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001399 }
1400
Chris Lattner95933c12009-04-24 00:30:45 +00001401 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001402}
1403
Chris Lattner8d9f7962009-01-24 20:17:12 +00001404bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1405 const SourceRange &ExprRange) {
1406 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001407
Chris Lattner8d9f7962009-01-24 20:17:12 +00001408 // alignof decl is always ok.
1409 if (isa<DeclRefExpr>(E))
1410 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001411
1412 // Cannot know anything else if the expression is dependent.
1413 if (E->isTypeDependent())
1414 return false;
1415
Douglas Gregor531434b2009-05-02 02:18:30 +00001416 if (E->getBitField()) {
1417 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1418 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001419 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001420
1421 // Alignment of a field access is always okay, so long as it isn't a
1422 // bit-field.
1423 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1424 if (dyn_cast<FieldDecl>(ME->getMemberDecl()))
1425 return false;
1426
Chris Lattner8d9f7962009-01-24 20:17:12 +00001427 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1428}
1429
Douglas Gregor396f1142009-03-13 21:01:28 +00001430/// \brief Build a sizeof or alignof expression given a type operand.
1431Action::OwningExprResult
1432Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1433 bool isSizeOf, SourceRange R) {
1434 if (T.isNull())
1435 return ExprError();
1436
1437 if (!T->isDependentType() &&
1438 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1439 return ExprError();
1440
1441 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1442 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1443 Context.getSizeType(), OpLoc,
1444 R.getEnd()));
1445}
1446
1447/// \brief Build a sizeof or alignof expression given an expression
1448/// operand.
1449Action::OwningExprResult
1450Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1451 bool isSizeOf, SourceRange R) {
1452 // Verify that the operand is valid.
1453 bool isInvalid = false;
1454 if (E->isTypeDependent()) {
1455 // Delay type-checking for type-dependent expressions.
1456 } else if (!isSizeOf) {
1457 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001458 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001459 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1460 isInvalid = true;
1461 } else {
1462 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1463 }
1464
1465 if (isInvalid)
1466 return ExprError();
1467
1468 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1469 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1470 Context.getSizeType(), OpLoc,
1471 R.getEnd()));
1472}
1473
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001474/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1475/// the same for @c alignof and @c __alignof
1476/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001477Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001478Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1479 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001480 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001481 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001482
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001483 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001484 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1485 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1486 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001487
Douglas Gregor396f1142009-03-13 21:01:28 +00001488 // Get the end location.
1489 Expr *ArgEx = (Expr *)TyOrEx;
1490 Action::OwningExprResult Result
1491 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1492
1493 if (Result.isInvalid())
1494 DeleteExpr(ArgEx);
1495
1496 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001497}
1498
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001499QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001500 if (V->isTypeDependent())
1501 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001502
Chris Lattnera16e42d2007-08-26 05:39:26 +00001503 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001504 if (const ComplexType *CT = V->getType()->getAsComplexType())
1505 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001506
1507 // Otherwise they pass through real integer and floating point types here.
1508 if (V->getType()->isArithmeticType())
1509 return V->getType();
1510
1511 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001512 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1513 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001514 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001515}
1516
1517
Chris Lattner4b009652007-07-25 00:24:17 +00001518
Sebastian Redl8b769972009-01-19 00:08:26 +00001519Action::OwningExprResult
1520Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1521 tok::TokenKind Kind, ExprArg Input) {
1522 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001523
Chris Lattner4b009652007-07-25 00:24:17 +00001524 UnaryOperator::Opcode Opc;
1525 switch (Kind) {
1526 default: assert(0 && "Unknown unary op!");
1527 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1528 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1529 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001530
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001531 if (getLangOptions().CPlusPlus &&
1532 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1533 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001534 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001535 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1536
1537 // C++ [over.inc]p1:
1538 //
1539 // [...] If the function is a member function with one
1540 // parameter (which shall be of type int) or a non-member
1541 // function with two parameters (the second of which shall be
1542 // of type int), it defines the postfix increment operator ++
1543 // for objects of that type. When the postfix increment is
1544 // called as a result of using the ++ operator, the int
1545 // argument will have value zero.
1546 Expr *Args[2] = {
1547 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001548 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1549 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001550 };
1551
1552 // Build the candidate set for overloading
1553 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001554 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001555
1556 // Perform overload resolution.
1557 OverloadCandidateSet::iterator Best;
1558 switch (BestViableFunction(CandidateSet, Best)) {
1559 case OR_Success: {
1560 // We found a built-in operator or an overloaded operator.
1561 FunctionDecl *FnDecl = Best->Function;
1562
1563 if (FnDecl) {
1564 // We matched an overloaded operator. Build a call to that
1565 // operator.
1566
1567 // Convert the arguments.
1568 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1569 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001570 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001571 } else {
1572 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001573 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001574 FnDecl->getParamDecl(0)->getType(),
1575 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001576 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001577 }
1578
1579 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001580 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001581 = FnDecl->getType()->getAsFunctionType()->getResultType();
1582 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001583
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001584 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001585 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001586 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001587 UsualUnaryConversions(FnExpr);
1588
Sebastian Redl8b769972009-01-19 00:08:26 +00001589 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001590 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1591 Args, 2, ResultTy,
1592 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001593 } else {
1594 // We matched a built-in operator. Convert the arguments, then
1595 // break out so that we will build the appropriate built-in
1596 // operator node.
1597 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1598 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001599 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001600
1601 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001602 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001603 }
1604
1605 case OR_No_Viable_Function:
1606 // No viable function; fall through to handling this as a
1607 // built-in operator, which will produce an error message for us.
1608 break;
1609
1610 case OR_Ambiguous:
1611 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1612 << UnaryOperator::getOpcodeStr(Opc)
1613 << Arg->getSourceRange();
1614 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001615 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001616
1617 case OR_Deleted:
1618 Diag(OpLoc, diag::err_ovl_deleted_oper)
1619 << Best->Function->isDeleted()
1620 << UnaryOperator::getOpcodeStr(Opc)
1621 << Arg->getSourceRange();
1622 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1623 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001624 }
1625
1626 // Either we found no viable overloaded operator or we matched a
1627 // built-in operator. In either case, fall through to trying to
1628 // build a built-in operation.
1629 }
1630
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001631 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1632 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001633 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001634 return ExprError();
1635 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001636 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001637}
1638
Sebastian Redl8b769972009-01-19 00:08:26 +00001639Action::OwningExprResult
1640Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1641 ExprArg Idx, SourceLocation RLoc) {
1642 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1643 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001644
Douglas Gregor80723c52008-11-19 17:17:41 +00001645 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001646 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001647 LHSExp->getType()->isEnumeralType() ||
1648 RHSExp->getType()->isRecordType() ||
1649 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001650 // Add the appropriate overloaded operators (C++ [over.match.oper])
1651 // to the candidate set.
1652 OverloadCandidateSet CandidateSet;
1653 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001654 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1655 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001656
Douglas Gregor80723c52008-11-19 17:17:41 +00001657 // Perform overload resolution.
1658 OverloadCandidateSet::iterator Best;
1659 switch (BestViableFunction(CandidateSet, Best)) {
1660 case OR_Success: {
1661 // We found a built-in operator or an overloaded operator.
1662 FunctionDecl *FnDecl = Best->Function;
1663
1664 if (FnDecl) {
1665 // We matched an overloaded operator. Build a call to that
1666 // operator.
1667
1668 // Convert the arguments.
1669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1670 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1671 PerformCopyInitialization(RHSExp,
1672 FnDecl->getParamDecl(0)->getType(),
1673 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001675 } else {
1676 // Convert the arguments.
1677 if (PerformCopyInitialization(LHSExp,
1678 FnDecl->getParamDecl(0)->getType(),
1679 "passing") ||
1680 PerformCopyInitialization(RHSExp,
1681 FnDecl->getParamDecl(1)->getType(),
1682 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001684 }
1685
1686 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001687 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001688 = FnDecl->getType()->getAsFunctionType()->getResultType();
1689 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001690
Douglas Gregor80723c52008-11-19 17:17:41 +00001691 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001692 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1693 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001694 UsualUnaryConversions(FnExpr);
1695
Sebastian Redl8b769972009-01-19 00:08:26 +00001696 Base.release();
1697 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001698 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1699 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001700 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001701 } else {
1702 // We matched a built-in operator. Convert the arguments, then
1703 // break out so that we will build the appropriate built-in
1704 // operator node.
1705 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1706 "passing") ||
1707 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1708 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001709 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001710
1711 break;
1712 }
1713 }
1714
1715 case OR_No_Viable_Function:
1716 // No viable function; fall through to handling this as a
1717 // built-in operator, which will produce an error message for us.
1718 break;
1719
1720 case OR_Ambiguous:
1721 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1722 << "[]"
1723 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1724 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001725 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001726
1727 case OR_Deleted:
1728 Diag(LLoc, diag::err_ovl_deleted_oper)
1729 << Best->Function->isDeleted()
1730 << "[]"
1731 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1732 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1733 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001734 }
1735
1736 // Either we found no viable overloaded operator or we matched a
1737 // built-in operator. In either case, fall through to trying to
1738 // build a built-in operation.
1739 }
1740
Chris Lattner4b009652007-07-25 00:24:17 +00001741 // Perform default conversions.
1742 DefaultFunctionArrayConversion(LHSExp);
1743 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001744
Chris Lattner4b009652007-07-25 00:24:17 +00001745 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1746
1747 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001748 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001749 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001750 // and index from the expression types.
1751 Expr *BaseExpr, *IndexExpr;
1752 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001753 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1754 BaseExpr = LHSExp;
1755 IndexExpr = RHSExp;
1756 ResultType = Context.DependentTy;
1757 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001758 BaseExpr = LHSExp;
1759 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001760 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001761 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001762 // Handle the uncommon case of "123[Ptr]".
1763 BaseExpr = RHSExp;
1764 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001765 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001766 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1767 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001768 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001769
Chris Lattner4b009652007-07-25 00:24:17 +00001770 // FIXME: need to deal with const...
1771 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001772 } else if (LHSTy->isArrayType()) {
1773 // If we see an array that wasn't promoted by
1774 // DefaultFunctionArrayConversion, it must be an array that
1775 // wasn't promoted because of the C90 rule that doesn't
1776 // allow promoting non-lvalue arrays. Warn, then
1777 // force the promotion here.
1778 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1779 LHSExp->getSourceRange();
1780 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1781 LHSTy = LHSExp->getType();
1782
1783 BaseExpr = LHSExp;
1784 IndexExpr = RHSExp;
1785 ResultType = LHSTy->getAsPointerType()->getPointeeType();
1786 } else if (RHSTy->isArrayType()) {
1787 // Same as previous, except for 123[f().a] case
1788 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1789 RHSExp->getSourceRange();
1790 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1791 RHSTy = RHSExp->getType();
1792
1793 BaseExpr = RHSExp;
1794 IndexExpr = LHSExp;
1795 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001796 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001797 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1798 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001799 }
Chris Lattner4b009652007-07-25 00:24:17 +00001800 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001801 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001802 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1803 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001804
Douglas Gregor05e28f62009-03-24 19:52:54 +00001805 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1806 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1807 // type. Note that Functions are not objects, and that (in C99 parlance)
1808 // incomplete types are not object types.
1809 if (ResultType->isFunctionType()) {
1810 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1811 << ResultType << BaseExpr->getSourceRange();
1812 return ExprError();
1813 }
Chris Lattner95933c12009-04-24 00:30:45 +00001814
Douglas Gregor05e28f62009-03-24 19:52:54 +00001815 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001816 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001817 BaseExpr->getSourceRange()))
1818 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001819
1820 // Diagnose bad cases where we step over interface counts.
1821 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1822 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1823 << ResultType << BaseExpr->getSourceRange();
1824 return ExprError();
1825 }
1826
Sebastian Redl8b769972009-01-19 00:08:26 +00001827 Base.release();
1828 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001829 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001830 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001831}
1832
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001833QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001834CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001835 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001836 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001837
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001838 // The vector accessor can't exceed the number of elements.
1839 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001840
Mike Stump9afab102009-02-19 03:04:26 +00001841 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001842 // special names that indicate a subset of exactly half the elements are
1843 // to be selected.
1844 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001845
Nate Begeman1486b502009-01-18 01:47:54 +00001846 // This flag determines whether or not CompName has an 's' char prefix,
1847 // indicating that it is a string of hex values to be used as vector indices.
1848 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001849
1850 // Check that we've found one of the special components, or that the component
1851 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001852 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001853 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1854 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001855 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001856 do
1857 compStr++;
1858 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001859 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001860 do
1861 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001862 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001863 }
Nate Begeman1486b502009-01-18 01:47:54 +00001864
Mike Stump9afab102009-02-19 03:04:26 +00001865 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001866 // We didn't get to the end of the string. This means the component names
1867 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001868 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1869 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001870 return QualType();
1871 }
Mike Stump9afab102009-02-19 03:04:26 +00001872
Nate Begeman1486b502009-01-18 01:47:54 +00001873 // Ensure no component accessor exceeds the width of the vector type it
1874 // operates on.
1875 if (!HalvingSwizzle) {
1876 compStr = CompName.getName();
1877
1878 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001879 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001880
1881 while (*compStr) {
1882 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1883 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1884 << baseType << SourceRange(CompLoc);
1885 return QualType();
1886 }
1887 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001888 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001889
Nate Begeman1486b502009-01-18 01:47:54 +00001890 // If this is a halving swizzle, verify that the base type has an even
1891 // number of elements.
1892 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001893 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001894 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001895 return QualType();
1896 }
Mike Stump9afab102009-02-19 03:04:26 +00001897
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001898 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001899 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001900 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001901 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001902 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001903 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1904 : CompName.getLength();
1905 if (HexSwizzle)
1906 CompSize--;
1907
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001908 if (CompSize == 1)
1909 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001910
Nate Begemanaf6ed502008-04-18 23:10:10 +00001911 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001912 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001913 // diagostics look bad. We want extended vector types to appear built-in.
1914 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1915 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1916 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001917 }
1918 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001919}
1920
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001921static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1922 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001923 const Selector &Sel,
1924 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001925
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001926 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001927 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001928 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001929 return OMD;
1930
1931 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1932 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001933 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1934 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001935 return D;
1936 }
1937 return 0;
1938}
1939
1940static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1941 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001942 const Selector &Sel,
1943 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001944 // Check protocols on qualified interfaces.
1945 Decl *GDecl = 0;
1946 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1947 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001948 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001949 GDecl = PD;
1950 break;
1951 }
1952 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001953 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001954 GDecl = OMD;
1955 break;
1956 }
1957 }
1958 if (!GDecl) {
1959 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1960 E = QIdTy->qual_end(); I != E; ++I) {
1961 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001962 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001963 if (GDecl)
1964 return GDecl;
1965 }
1966 }
1967 return GDecl;
1968}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001969
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001970/// FindMethodInNestedImplementations - Look up a method in current and
1971/// all base class implementations.
1972///
1973ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1974 const ObjCInterfaceDecl *IFace,
1975 const Selector &Sel) {
1976 ObjCMethodDecl *Method = 0;
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001977 if (ObjCImplementationDecl *ImpDecl
1978 = LookupObjCImplementation(IFace->getIdentifier()))
Douglas Gregorcd19b572009-04-23 01:02:12 +00001979 Method = ImpDecl->getInstanceMethod(Context, Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001980
1981 if (!Method && IFace->getSuperClass())
1982 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1983 return Method;
1984}
1985
Sebastian Redl8b769972009-01-19 00:08:26 +00001986Action::OwningExprResult
1987Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1988 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001989 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001990 DeclPtrTy ObjCImpDecl) {
Anders Carlssonc154a722009-05-01 19:30:39 +00001991 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001992 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001993
1994 // Perform default conversions.
1995 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001996
Steve Naroff2cb66382007-07-26 03:11:44 +00001997 QualType BaseType = BaseExpr->getType();
1998 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001999
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002000 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2001 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002002 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00002003 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00002004 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00002005 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00002006 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
2007 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00002008 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002009 return ExprError(Diag(MemberLoc,
2010 diag::err_typecheck_member_reference_arrow)
2011 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002012 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002013
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002014 // Handle field access to simple records. This also handles access to fields
2015 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00002016 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002017 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002018 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002019 diag::err_typecheck_incomplete_tag,
2020 BaseExpr->getSourceRange()))
2021 return ExprError();
2022
Steve Naroff2cb66382007-07-26 03:11:44 +00002023 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002024 // FIXME: Qualified name lookup for C++ is a bit more complicated
2025 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00002026 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00002027 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002028 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002029
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002030 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002031 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2032 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002033 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002034 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2035 MemberLoc, BaseExpr->getSourceRange());
2036 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002037 }
2038
2039 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002040
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002041 // If the decl being referenced had an error, return an error for this
2042 // sub-expr without emitting another error, in order to avoid cascading
2043 // error cases.
2044 if (MemberDecl->isInvalidDecl())
2045 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002046
Douglas Gregoraa57e862009-02-18 21:56:37 +00002047 // Check the use of this field
2048 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2049 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002050
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002051 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002052 // We may have found a field within an anonymous union or struct
2053 // (C++ [class.union]).
2054 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002055 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002056 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002057
Douglas Gregor82d44772008-12-20 23:49:58 +00002058 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2059 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002060 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00002061 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
2062 MemberType = Ref->getPointeeType();
2063 else {
2064 unsigned combinedQualifiers =
2065 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002066 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002067 combinedQualifiers &= ~QualType::Const;
2068 MemberType = MemberType.getQualifiedType(combinedQualifiers);
2069 }
Eli Friedman76b49832008-02-06 22:48:16 +00002070
Steve Naroff774e4152009-01-21 00:14:39 +00002071 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2072 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002073 }
2074
2075 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002076 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002077 Var, MemberLoc,
2078 Var->getType().getNonReferenceType()));
2079 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002080 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002081 MemberFn, MemberLoc,
2082 MemberFn->getType()));
2083 if (OverloadedFunctionDecl *Ovl
2084 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002085 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002086 MemberLoc, Context.OverloadTy));
2087 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002088 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2089 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00002090 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002091 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2092 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002093
Douglas Gregor82d44772008-12-20 23:49:58 +00002094 // We found a declaration kind that we didn't expect. This is a
2095 // generic error message that tells the user that she can't refer
2096 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002097 return ExprError(Diag(MemberLoc,
2098 diag::err_typecheck_member_reference_unknown)
2099 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002100 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002101
Chris Lattnere9d71612008-07-21 04:59:05 +00002102 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2103 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002104 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002105 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002106 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
2107 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002108 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002109 // If the decl being referenced had an error, return an error for this
2110 // sub-expr without emitting another error, in order to avoid cascading
2111 // error cases.
2112 if (IV->isInvalidDecl())
2113 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002114
2115 // Check whether we can reference this field.
2116 if (DiagnoseUseOfDecl(IV, MemberLoc))
2117 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00002118 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2119 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002120 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2121 if (ObjCMethodDecl *MD = getCurMethodDecl())
2122 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002123 else if (ObjCImpDecl && getCurFunctionDecl()) {
2124 // Case of a c-function declared inside an objc implementation.
2125 // FIXME: For a c-style function nested inside an objc implementation
2126 // class, there is no implementation context available, so we pass down
2127 // the context as argument to this routine. Ideally, this context need
2128 // be passed down in the AST node and somehow calculated from the AST
2129 // for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002130 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002131 if (ObjCImplementationDecl *IMPD =
2132 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2133 ClassOfMethodDecl = IMPD->getClassInterface();
2134 else if (ObjCCategoryImplDecl* CatImplClass =
2135 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2136 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00002137 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002138
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002139 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002140 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002141 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002142 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2143 }
2144 // @protected
2145 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2146 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2147 }
Mike Stump9afab102009-02-19 03:04:26 +00002148
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002149 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00002150 MemberLoc, BaseExpr,
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002151 OpKind == tok::arrow));
Fariborz Jahanian09772392008-12-13 22:20:28 +00002152 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002153 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2154 << IFTy->getDecl()->getDeclName() << &Member
2155 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00002156 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002157
Chris Lattnere9d71612008-07-21 04:59:05 +00002158 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2159 // pointer to a (potentially qualified) interface type.
2160 const PointerType *PTy;
2161 const ObjCInterfaceType *IFTy;
2162 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2163 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2164 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00002165
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002166 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002167 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
2168 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002169 // Check whether we can reference this property.
2170 if (DiagnoseUseOfDecl(PD, MemberLoc))
2171 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002172 QualType ResTy = PD->getType();
2173 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2174 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002175 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2176 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002177 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002178 MemberLoc, BaseExpr));
2179 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002180
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002181 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00002182 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2183 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002184 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
2185 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002186 // Check whether we can reference this property.
2187 if (DiagnoseUseOfDecl(PD, MemberLoc))
2188 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002189
Steve Naroff774e4152009-01-21 00:14:39 +00002190 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002191 MemberLoc, BaseExpr));
2192 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002193
2194 // If that failed, look for an "implicit" property by seeing if the nullary
2195 // selector is implemented.
2196
2197 // FIXME: The logic for looking up nullary and unary selectors should be
2198 // shared with the code in ActOnInstanceMessage.
2199
2200 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002201 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002202
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002203 // If this reference is in an @implementation, check for 'private' methods.
2204 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002205 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002206
Steve Naroff04151f32008-10-22 19:16:27 +00002207 // Look through local category implementations associated with the class.
2208 if (!Getter) {
2209 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2210 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002211 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
Steve Naroff04151f32008-10-22 19:16:27 +00002212 }
2213 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002214 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002215 // Check if we can reference this property.
2216 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2217 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002218 }
2219 // If we found a getter then this may be a valid dot-reference, we
2220 // will look for the matching setter, in case it is needed.
2221 Selector SetterSel =
2222 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2223 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002224 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002225 if (!Setter) {
2226 // If this reference is in an @implementation, also check for 'private'
2227 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002228 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002229 }
2230 // Look through local category implementations associated with the class.
2231 if (!Setter) {
2232 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2233 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002234 Setter = ObjCCategoryImpls[i]->getInstanceMethod(Context, SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002235 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002236 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002237
Steve Naroffdede0c92009-03-11 13:48:17 +00002238 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2239 return ExprError();
2240
2241 if (Getter || Setter) {
2242 QualType PType;
2243
2244 if (Getter)
2245 PType = Getter->getResultType();
2246 else {
2247 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2248 E = Setter->param_end(); PI != E; ++PI)
2249 PType = (*PI)->getType();
2250 }
2251 // FIXME: we must check that the setter has property type.
2252 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2253 Setter, MemberLoc, BaseExpr));
2254 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002255 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2256 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002257 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002258 // Handle properties on qualified "id" protocols.
2259 const ObjCQualifiedIdType *QIdTy;
2260 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2261 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002262 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002263 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002264 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002265 // Check the use of this declaration
2266 if (DiagnoseUseOfDecl(PD, MemberLoc))
2267 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002268
Steve Naroff774e4152009-01-21 00:14:39 +00002269 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002270 MemberLoc, BaseExpr));
2271 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002272 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002273 // Check the use of this method.
2274 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2275 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002276
Mike Stump9afab102009-02-19 03:04:26 +00002277 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002278 OMD->getResultType(),
2279 OMD, OpLoc, MemberLoc,
2280 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002281 }
2282 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002283
2284 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2285 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002286 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002287 // Handle properties on ObjC 'Class' types.
2288 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2289 // Also must look for a getter name which uses property syntax.
2290 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2291 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002292 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2293 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002294 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002295 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002296 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002297 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002298 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002299 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002300 // If we found a getter then this may be a valid dot-reference, we
2301 // will look for the matching setter, in case it is needed.
2302 Selector SetterSel =
2303 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2304 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002305 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002306 if (!Setter) {
2307 // If this reference is in an @implementation, also check for 'private'
2308 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002309 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002310 }
2311 // Look through local category implementations associated with the class.
2312 if (!Setter) {
2313 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2314 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002315 Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002316 }
2317 }
2318
2319 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2320 return ExprError();
2321
2322 if (Getter || Setter) {
2323 QualType PType;
2324
2325 if (Getter)
2326 PType = Getter->getResultType();
2327 else {
2328 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2329 E = Setter->param_end(); PI != E; ++PI)
2330 PType = (*PI)->getType();
2331 }
2332 // FIXME: we must check that the setter has property type.
2333 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2334 Setter, MemberLoc, BaseExpr));
2335 }
2336 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2337 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002338 }
2339 }
2340
Chris Lattnera57cf472008-07-21 04:28:12 +00002341 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002342 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002343 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2344 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002345 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002346 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002347 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002348 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002349
Douglas Gregor762da552009-03-27 06:00:30 +00002350 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2351 << BaseType << BaseExpr->getSourceRange();
2352
2353 // If the user is trying to apply -> or . to a function or function
2354 // pointer, it's probably because they forgot parentheses to call
2355 // the function. Suggest the addition of those parentheses.
2356 if (BaseType == Context.OverloadTy ||
2357 BaseType->isFunctionType() ||
2358 (BaseType->isPointerType() &&
2359 BaseType->getAsPointerType()->isFunctionType())) {
2360 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2361 Diag(Loc, diag::note_member_reference_needs_call)
2362 << CodeModificationHint::CreateInsertion(Loc, "()");
2363 }
2364
2365 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002366}
2367
Douglas Gregor3257fb52008-12-22 05:46:06 +00002368/// ConvertArgumentsForCall - Converts the arguments specified in
2369/// Args/NumArgs to the parameter types of the function FDecl with
2370/// function prototype Proto. Call is the call expression itself, and
2371/// Fn is the function expression. For a C++ member function, this
2372/// routine does not attempt to convert the object argument. Returns
2373/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002374bool
2375Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002376 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002377 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002378 Expr **Args, unsigned NumArgs,
2379 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002380 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002381 // assignment, to the types of the corresponding parameter, ...
2382 unsigned NumArgsInProto = Proto->getNumArgs();
2383 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002384 bool Invalid = false;
2385
Douglas Gregor3257fb52008-12-22 05:46:06 +00002386 // If too few arguments are available (and we don't have default
2387 // arguments for the remaining parameters), don't make the call.
2388 if (NumArgs < NumArgsInProto) {
2389 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2390 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2391 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2392 // Use default arguments for missing arguments
2393 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002394 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002395 }
2396
2397 // If too many are passed and not variadic, error on the extras and drop
2398 // them.
2399 if (NumArgs > NumArgsInProto) {
2400 if (!Proto->isVariadic()) {
2401 Diag(Args[NumArgsInProto]->getLocStart(),
2402 diag::err_typecheck_call_too_many_args)
2403 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2404 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2405 Args[NumArgs-1]->getLocEnd());
2406 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002407 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002408 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002409 }
2410 NumArgsToCheck = NumArgsInProto;
2411 }
Mike Stump9afab102009-02-19 03:04:26 +00002412
Douglas Gregor3257fb52008-12-22 05:46:06 +00002413 // Continue to check argument types (even if we have too few/many args).
2414 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2415 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002416
Douglas Gregor3257fb52008-12-22 05:46:06 +00002417 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002418 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002419 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002420
Eli Friedman83dec9e2009-03-22 22:00:50 +00002421 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2422 ProtoArgType,
2423 diag::err_call_incomplete_argument,
2424 Arg->getSourceRange()))
2425 return true;
2426
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002427 // Pass the argument.
2428 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2429 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002430 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002431 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002432 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002433 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002434
Douglas Gregor3257fb52008-12-22 05:46:06 +00002435 Call->setArg(i, Arg);
2436 }
Mike Stump9afab102009-02-19 03:04:26 +00002437
Douglas Gregor3257fb52008-12-22 05:46:06 +00002438 // If this is a variadic call, handle args passed through "...".
2439 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002440 VariadicCallType CallType = VariadicFunction;
2441 if (Fn->getType()->isBlockPointerType())
2442 CallType = VariadicBlock; // Block
2443 else if (isa<MemberExpr>(Fn))
2444 CallType = VariadicMethod;
2445
Douglas Gregor3257fb52008-12-22 05:46:06 +00002446 // Promote the arguments (C99 6.5.2.2p7).
2447 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2448 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002449 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002450 Call->setArg(i, Arg);
2451 }
2452 }
2453
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002454 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002455}
2456
Steve Naroff87d58b42007-09-16 03:34:24 +00002457/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002458/// This provides the location of the left/right parens and a list of comma
2459/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002460Action::OwningExprResult
2461Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2462 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002463 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002464 unsigned NumArgs = args.size();
Anders Carlssonc154a722009-05-01 19:30:39 +00002465 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002466 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002467 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002468 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002469 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002470
Douglas Gregor3257fb52008-12-22 05:46:06 +00002471 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002472 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002473 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002474 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2475 bool Dependent = false;
2476 if (Fn->isTypeDependent())
2477 Dependent = true;
2478 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2479 Dependent = true;
2480
2481 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002482 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002483 Context.DependentTy, RParenLoc));
2484
2485 // Determine whether this is a call to an object (C++ [over.call.object]).
2486 if (Fn->getType()->isRecordType())
2487 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2488 CommaLocs, RParenLoc));
2489
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002490 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002491 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2492 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2493 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002494 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2495 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002496 }
2497
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002498 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002499 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002500 Expr *FnExpr = Fn;
2501 bool ADL = true;
2502 while (true) {
2503 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2504 FnExpr = IcExpr->getSubExpr();
2505 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002506 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002507 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002508 ADL = false;
2509 FnExpr = PExpr->getSubExpr();
2510 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002511 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002512 == UnaryOperator::AddrOf) {
2513 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002514 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2515 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2516 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2517 break;
Mike Stump9afab102009-02-19 03:04:26 +00002518 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002519 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2520 UnqualifiedName = DepName->getName();
2521 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002522 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002523 // Any kind of name that does not refer to a declaration (or
2524 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2525 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002526 break;
2527 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002528 }
Mike Stump9afab102009-02-19 03:04:26 +00002529
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002530 OverloadedFunctionDecl *Ovl = 0;
2531 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002532 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002533 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2534 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002535
Douglas Gregorfcb19192009-02-11 23:02:49 +00002536 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002537 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002538 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002539 ADL = false;
2540
Douglas Gregorfcb19192009-02-11 23:02:49 +00002541 // We don't perform ADL in C.
2542 if (!getLangOptions().CPlusPlus)
2543 ADL = false;
2544
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002545 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002546 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2547 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002548 NumArgs, CommaLocs, RParenLoc, ADL);
2549 if (!FDecl)
2550 return ExprError();
2551
2552 // Update Fn to refer to the actual function selected.
2553 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002554 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002555 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002556 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2557 QDRExpr->getLocation(),
2558 false, false,
2559 QDRExpr->getQualifierRange(),
2560 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002561 else
Mike Stump9afab102009-02-19 03:04:26 +00002562 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002563 Fn->getSourceRange().getBegin());
2564 Fn->Destroy(Context);
2565 Fn = NewFn;
2566 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002567 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002568
2569 // Promote the function operand.
2570 UsualUnaryConversions(Fn);
2571
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002572 // Make the call expr early, before semantic checks. This guarantees cleanup
2573 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002574 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2575 Args, NumArgs,
2576 Context.BoolTy,
2577 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002578
Steve Naroffd6163f32008-09-05 22:11:13 +00002579 const FunctionType *FuncT;
2580 if (!Fn->getType()->isBlockPointerType()) {
2581 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2582 // have type pointer to function".
2583 const PointerType *PT = Fn->getType()->getAsPointerType();
2584 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002585 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2586 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002587 FuncT = PT->getPointeeType()->getAsFunctionType();
2588 } else { // This is a block call.
2589 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2590 getAsFunctionType();
2591 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002592 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002593 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2594 << Fn->getType() << Fn->getSourceRange());
2595
Eli Friedman83dec9e2009-03-22 22:00:50 +00002596 // Check for a valid return type
2597 if (!FuncT->getResultType()->isVoidType() &&
2598 RequireCompleteType(Fn->getSourceRange().getBegin(),
2599 FuncT->getResultType(),
2600 diag::err_call_incomplete_return,
2601 TheCall->getSourceRange()))
2602 return ExprError();
2603
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002604 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002605 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002606
Douglas Gregor4fa58902009-02-26 23:50:07 +00002607 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002608 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002609 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002610 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002611 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002612 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002613
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002614 if (FDecl) {
2615 // Check if we have too few/too many template arguments, based
2616 // on our knowledge of the function definition.
2617 const FunctionDecl *Def = 0;
Douglas Gregore3241e92009-04-18 00:02:19 +00002618 if (FDecl->getBody(Context, Def) && NumArgs != Def->param_size())
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002619 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2620 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2621 }
2622
Steve Naroffdb65e052007-08-28 23:30:39 +00002623 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002624 for (unsigned i = 0; i != NumArgs; i++) {
2625 Expr *Arg = Args[i];
2626 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002627 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2628 Arg->getType(),
2629 diag::err_call_incomplete_argument,
2630 Arg->getSourceRange()))
2631 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002632 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002633 }
Chris Lattner4b009652007-07-25 00:24:17 +00002634 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002635
Douglas Gregor3257fb52008-12-22 05:46:06 +00002636 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2637 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002638 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2639 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002640
Chris Lattner2e64c072007-08-10 20:18:51 +00002641 // Do special checking on direct calls to functions.
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +00002642 if (FDecl) {
2643 DiagnoseSentinelCalls(FDecl, LParenLoc, Args, NumArgs);
Eli Friedmand0e9d092008-05-14 19:38:39 +00002644 return CheckFunctionCall(FDecl, TheCall.take());
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +00002645 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002646
Sebastian Redl8b769972009-01-19 00:08:26 +00002647 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002648}
2649
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002650Action::OwningExprResult
2651Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2652 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002653 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002654 QualType literalType = QualType::getFromOpaquePtr(Ty);
2655 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002656 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002657 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002658
Eli Friedman8c2173d2008-05-20 05:22:08 +00002659 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002660 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002661 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2662 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002663 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002664 diag::err_typecheck_decl_incomplete_type,
2665 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002666 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002667
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002668 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002669 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002670 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002671
Chris Lattnere5cb5862008-12-04 23:50:19 +00002672 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002673 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002674 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002675 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002676 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002677 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002678 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002679 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002680}
2681
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002682Action::OwningExprResult
2683Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002684 SourceLocation RBraceLoc) {
2685 unsigned NumInit = initlist.size();
2686 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002687
Steve Naroff0acc9c92007-09-15 18:49:24 +00002688 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002689 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002690
Mike Stump9afab102009-02-19 03:04:26 +00002691 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002692 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002693 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002694 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002695}
2696
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002697/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002698bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002699 UsualUnaryConversions(castExpr);
2700
2701 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2702 // type needs to be scalar.
2703 if (castType->isVoidType()) {
2704 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002705 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2706 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002707 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002708 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2709 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2710 (castType->isStructureType() || castType->isUnionType())) {
2711 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002712 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002713 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2714 << castType << castExpr->getSourceRange();
2715 } else if (castType->isUnionType()) {
2716 // GCC cast to union extension
2717 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2718 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002719 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002720 Field != FieldEnd; ++Field) {
2721 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2722 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2723 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2724 << castExpr->getSourceRange();
2725 break;
2726 }
2727 }
2728 if (Field == FieldEnd)
2729 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2730 << castExpr->getType() << castExpr->getSourceRange();
2731 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002732 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002733 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002734 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002735 }
Mike Stump9afab102009-02-19 03:04:26 +00002736 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002737 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002738 return Diag(castExpr->getLocStart(),
2739 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002740 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002741 } else if (castExpr->getType()->isVectorType()) {
2742 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2743 return true;
2744 } else if (castType->isVectorType()) {
2745 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2746 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002747 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002748 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002749 } else if (!castType->isArithmeticType()) {
2750 QualType castExprType = castExpr->getType();
2751 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2752 return Diag(castExpr->getLocStart(),
2753 diag::err_cast_pointer_from_non_pointer_int)
2754 << castExprType << castExpr->getSourceRange();
2755 } else if (!castExpr->getType()->isArithmeticType()) {
2756 if (!castType->isIntegralType() && castType->isArithmeticType())
2757 return Diag(castExpr->getLocStart(),
2758 diag::err_cast_pointer_to_non_pointer_int)
2759 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002760 }
2761 return false;
2762}
2763
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002764bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002765 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002766
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002767 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002768 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002769 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002770 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002771 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002772 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002773 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002774 } else
2775 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002776 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002777 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002778
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002779 return false;
2780}
2781
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002782Action::OwningExprResult
2783Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2784 SourceLocation RParenLoc, ExprArg Op) {
2785 assert((Ty != 0) && (Op.get() != 0) &&
2786 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002787
Anders Carlssonc154a722009-05-01 19:30:39 +00002788 Expr *castExpr = Op.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00002789 QualType castType = QualType::getFromOpaquePtr(Ty);
2790
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002791 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002792 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002793 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002794 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002795}
2796
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002797/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2798/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002799/// C99 6.5.15
2800QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2801 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002802 // C++ is sufficiently different to merit its own checker.
2803 if (getLangOptions().CPlusPlus)
2804 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
2805
Chris Lattnere2897262009-02-18 04:28:32 +00002806 UsualUnaryConversions(Cond);
2807 UsualUnaryConversions(LHS);
2808 UsualUnaryConversions(RHS);
2809 QualType CondTy = Cond->getType();
2810 QualType LHSTy = LHS->getType();
2811 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002812
2813 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00002814 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2815 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2816 << CondTy;
2817 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002818 }
Mike Stump9afab102009-02-19 03:04:26 +00002819
Chris Lattner992ae932008-01-06 22:42:25 +00002820 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002821
Chris Lattner992ae932008-01-06 22:42:25 +00002822 // If both operands have arithmetic type, do the usual arithmetic conversions
2823 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002824 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2825 UsualArithmeticConversions(LHS, RHS);
2826 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002827 }
Mike Stump9afab102009-02-19 03:04:26 +00002828
Chris Lattner992ae932008-01-06 22:42:25 +00002829 // If both operands are the same structure or union type, the result is that
2830 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002831 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2832 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002833 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002834 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002835 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002836 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002837 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002838 }
Mike Stump9afab102009-02-19 03:04:26 +00002839
Chris Lattner992ae932008-01-06 22:42:25 +00002840 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002841 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002842 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2843 if (!LHSTy->isVoidType())
2844 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2845 << RHS->getSourceRange();
2846 if (!RHSTy->isVoidType())
2847 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2848 << LHS->getSourceRange();
2849 ImpCastExprToType(LHS, Context.VoidTy);
2850 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002851 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002852 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002853 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2854 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002855 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2856 Context.isObjCObjectPointerType(LHSTy)) &&
2857 RHS->isNullPointerConstant(Context)) {
2858 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2859 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002860 }
Chris Lattnere2897262009-02-18 04:28:32 +00002861 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2862 Context.isObjCObjectPointerType(RHSTy)) &&
2863 LHS->isNullPointerConstant(Context)) {
2864 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2865 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002866 }
Mike Stump9afab102009-02-19 03:04:26 +00002867
Mike Stumpe97a8542009-05-07 03:14:14 +00002868 const PointerType *LHSPT = LHSTy->getAsPointerType();
2869 const PointerType *RHSPT = RHSTy->getAsPointerType();
2870 const BlockPointerType *LHSBPT = LHSTy->getAsBlockPointerType();
2871 const BlockPointerType *RHSBPT = RHSTy->getAsBlockPointerType();
2872
Chris Lattner0ac51632008-01-06 22:50:31 +00002873 // Handle the case where both operands are pointers before we handle null
2874 // pointer constants in case both operands are null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00002875 if ((LHSPT || LHSBPT) && (RHSPT || RHSBPT)) { // C99 6.5.15p3,6
2876 // get the "pointed to" types
Mike Stumpea3d74e2009-05-07 18:43:07 +00002877 QualType lhptee = (LHSPT ? LHSPT->getPointeeType()
2878 : LHSBPT->getPointeeType());
2879 QualType rhptee = (RHSPT ? RHSPT->getPointeeType()
2880 : RHSBPT->getPointeeType());
Chris Lattner4b009652007-07-25 00:24:17 +00002881
Mike Stumpe97a8542009-05-07 03:14:14 +00002882 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2883 if (lhptee->isVoidType()
2884 && (RHSBPT || rhptee->isIncompleteOrObjectType())) {
2885 // Figure out necessary qualifiers (C99 6.5.15p6)
2886 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2887 QualType destType = Context.getPointerType(destPointee);
2888 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2889 ImpCastExprToType(RHS, destType); // promote to void*
2890 return destType;
2891 }
2892 if (rhptee->isVoidType()
2893 && (LHSBPT || lhptee->isIncompleteOrObjectType())) {
2894 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2895 QualType destType = Context.getPointerType(destPointee);
2896 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2897 ImpCastExprToType(RHS, destType); // promote to void*
2898 return destType;
2899 }
Chris Lattner4b009652007-07-25 00:24:17 +00002900
Mike Stumpe97a8542009-05-07 03:14:14 +00002901 bool sameKind = (LHSPT && RHSPT) || (LHSBPT && RHSBPT);
2902 if (sameKind
2903 && Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2904 // Two identical pointer types are always compatible.
2905 return LHSTy;
2906 }
Mike Stump9afab102009-02-19 03:04:26 +00002907
Mike Stumpe97a8542009-05-07 03:14:14 +00002908 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002909
Mike Stumpe97a8542009-05-07 03:14:14 +00002910 // If either type is an Objective-C object type then check
2911 // compatibility according to Objective-C.
2912 if (Context.isObjCObjectPointerType(LHSTy) ||
2913 Context.isObjCObjectPointerType(RHSTy)) {
2914 // If both operands are interfaces and either operand can be
2915 // assigned to the other, use that type as the composite
2916 // type. This allows
2917 // xxx ? (A*) a : (B*) b
2918 // where B is a subclass of A.
2919 //
2920 // Additionally, as for assignment, if either type is 'id'
2921 // allow silent coercion. Finally, if the types are
2922 // incompatible then make sure to use 'id' as the composite
2923 // type so the result is acceptable for sending messages to.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002924
Mike Stumpe97a8542009-05-07 03:14:14 +00002925 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2926 // It could return the composite type.
2927 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2928 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2929 if (LHSIface && RHSIface &&
2930 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2931 compositeType = LHSTy;
2932 } else if (LHSIface && RHSIface &&
2933 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2934 compositeType = RHSTy;
2935 } else if (Context.isObjCIdStructType(lhptee) ||
2936 Context.isObjCIdStructType(rhptee)) {
2937 compositeType = Context.getObjCIdType();
2938 } else if (LHSBPT || RHSBPT) {
2939 if (!sameKind
2940 || !Context.typesAreBlockCompatible(lhptee.getUnqualifiedType(),
2941 rhptee.getUnqualifiedType()))
2942 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2943 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2944 return QualType();
2945 } else {
2946 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
2947 << LHSTy << RHSTy
2948 << LHS->getSourceRange() << RHS->getSourceRange();
2949 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002950 ImpCastExprToType(LHS, incompatTy);
2951 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002952 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002953 }
Mike Stumpe97a8542009-05-07 03:14:14 +00002954 } else if (!sameKind
2955 || !Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2956 rhptee.getUnqualifiedType())) {
2957 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2958 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2959 // In this situation, we assume void* type. No especially good
2960 // reason, but this is what gcc does, and we do have to pick
2961 // to get a consistent AST.
2962 QualType incompatTy = Context.getPointerType(Context.VoidTy);
2963 ImpCastExprToType(LHS, incompatTy);
2964 ImpCastExprToType(RHS, incompatTy);
2965 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002966 }
Mike Stumpe97a8542009-05-07 03:14:14 +00002967 // The pointer types are compatible.
2968 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2969 // differently qualified versions of compatible types, the result type is
2970 // a pointer to an appropriately qualified version of the *composite*
2971 // type.
2972 // FIXME: Need to calculate the composite type.
2973 // FIXME: Need to add qualifiers
2974 ImpCastExprToType(LHS, compositeType);
2975 ImpCastExprToType(RHS, compositeType);
2976 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002977 }
Mike Stump9afab102009-02-19 03:04:26 +00002978
Steve Naroff6ba22682009-04-08 17:05:15 +00002979 // GCC compatibility: soften pointer/integer mismatch.
2980 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
2981 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2982 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2983 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
2984 return RHSTy;
2985 }
2986 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
2987 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2988 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2989 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
2990 return LHSTy;
2991 }
2992
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002993 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2994 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002995 // id with statically typed objects).
2996 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002997 // GCC allows qualified id and any Objective-C type to devolve to
2998 // id. Currently localizing to here until clear this should be
2999 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003000 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00003001 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00003002 Context.isObjCObjectPointerType(RHSTy)) ||
3003 (RHSTy->isObjCQualifiedIdType() &&
3004 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003005 // FIXME: This is not the correct composite type. This only
3006 // happens to work because id can more or less be used anywhere,
3007 // however this may change the type of method sends.
3008 // FIXME: gcc adds some type-checking of the arguments and emits
3009 // (confusing) incompatible comparison warnings in some
3010 // cases. Investigate.
3011 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00003012 ImpCastExprToType(LHS, compositeType);
3013 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003014 return compositeType;
3015 }
3016 }
3017
Chris Lattner992ae932008-01-06 22:42:25 +00003018 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003019 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3020 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003021 return QualType();
3022}
3023
Steve Naroff87d58b42007-09-16 03:34:24 +00003024/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003025/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003026Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3027 SourceLocation ColonLoc,
3028 ExprArg Cond, ExprArg LHS,
3029 ExprArg RHS) {
3030 Expr *CondExpr = (Expr *) Cond.get();
3031 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003032
3033 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3034 // was the condition.
3035 bool isLHSNull = LHSExpr == 0;
3036 if (isLHSNull)
3037 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003038
3039 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003040 RHSExpr, QuestionLoc);
3041 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003042 return ExprError();
3043
3044 Cond.release();
3045 LHS.release();
3046 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003047 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003048 isLHSNull ? 0 : LHSExpr,
3049 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003050}
3051
Chris Lattner4b009652007-07-25 00:24:17 +00003052
3053// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003054// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003055// routine is it effectively iqnores the qualifiers on the top level pointee.
3056// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3057// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003058Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003059Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3060 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003061
Chris Lattner4b009652007-07-25 00:24:17 +00003062 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00003063 lhptee = lhsType->getAsPointerType()->getPointeeType();
3064 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003065
Chris Lattner4b009652007-07-25 00:24:17 +00003066 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003067 lhptee = Context.getCanonicalType(lhptee);
3068 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003069
Chris Lattner005ed752008-01-04 18:04:52 +00003070 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003071
3072 // C99 6.5.16.1p1: This following citation is common to constraints
3073 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3074 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003075 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003076 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003077 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003078
Mike Stump9afab102009-02-19 03:04:26 +00003079 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3080 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003081 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003082 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003083 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003084 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003085
Chris Lattner4ca3d772008-01-03 22:56:36 +00003086 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003087 assert(rhptee->isFunctionType());
3088 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003089 }
Mike Stump9afab102009-02-19 03:04:26 +00003090
Chris Lattner4ca3d772008-01-03 22:56:36 +00003091 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003092 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003093 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003094
3095 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003096 assert(lhptee->isFunctionType());
3097 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003098 }
Mike Stump9afab102009-02-19 03:04:26 +00003099 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003100 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003101 lhptee = lhptee.getUnqualifiedType();
3102 rhptee = rhptee.getUnqualifiedType();
3103 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3104 // Check if the pointee types are compatible ignoring the sign.
3105 // We explicitly check for char so that we catch "char" vs
3106 // "unsigned char" on systems where "char" is unsigned.
3107 if (lhptee->isCharType()) {
3108 lhptee = Context.UnsignedCharTy;
3109 } else if (lhptee->isSignedIntegerType()) {
3110 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3111 }
3112 if (rhptee->isCharType()) {
3113 rhptee = Context.UnsignedCharTy;
3114 } else if (rhptee->isSignedIntegerType()) {
3115 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3116 }
3117 if (lhptee == rhptee) {
3118 // Types are compatible ignoring the sign. Qualifier incompatibility
3119 // takes priority over sign incompatibility because the sign
3120 // warning can be disabled.
3121 if (ConvTy != Compatible)
3122 return ConvTy;
3123 return IncompatiblePointerSign;
3124 }
3125 // General pointer incompatibility takes priority over qualifiers.
3126 return IncompatiblePointer;
3127 }
Chris Lattner005ed752008-01-04 18:04:52 +00003128 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003129}
3130
Steve Naroff3454b6c2008-09-04 15:10:53 +00003131/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3132/// block pointer types are compatible or whether a block and normal pointer
3133/// are compatible. It is more restrict than comparing two function pointer
3134// types.
Mike Stump9afab102009-02-19 03:04:26 +00003135Sema::AssignConvertType
3136Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003137 QualType rhsType) {
3138 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003139
Steve Naroff3454b6c2008-09-04 15:10:53 +00003140 // get the "pointed to" type (ignoring qualifiers at the top level)
3141 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003142 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3143
Steve Naroff3454b6c2008-09-04 15:10:53 +00003144 // make sure we operate on the canonical type
3145 lhptee = Context.getCanonicalType(lhptee);
3146 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003147
Steve Naroff3454b6c2008-09-04 15:10:53 +00003148 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003149
Steve Naroff3454b6c2008-09-04 15:10:53 +00003150 // For blocks we enforce that qualifiers are identical.
3151 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3152 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003153
Steve Naroff3454b6c2008-09-04 15:10:53 +00003154 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003155 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003156 return ConvTy;
3157}
3158
Mike Stump9afab102009-02-19 03:04:26 +00003159/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3160/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003161/// pointers. Here are some objectionable examples that GCC considers warnings:
3162///
3163/// int a, *pint;
3164/// short *pshort;
3165/// struct foo *pfoo;
3166///
3167/// pint = pshort; // warning: assignment from incompatible pointer type
3168/// a = pint; // warning: assignment makes integer from pointer without a cast
3169/// pint = a; // warning: assignment makes pointer from integer without a cast
3170/// pint = pfoo; // warning: assignment from incompatible pointer type
3171///
3172/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003173/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003174///
Chris Lattner005ed752008-01-04 18:04:52 +00003175Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003176Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003177 // Get canonical types. We're not formatting these types, just comparing
3178 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003179 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3180 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003181
3182 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003183 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003184
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003185 // If the left-hand side is a reference type, then we are in a
3186 // (rare!) case where we've allowed the use of references in C,
3187 // e.g., as a parameter type in a built-in function. In this case,
3188 // just make sure that the type referenced is compatible with the
3189 // right-hand side type. The caller is responsible for adjusting
3190 // lhsType so that the resulting expression does not have reference
3191 // type.
3192 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3193 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003194 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003195 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003196 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003197
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003198 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3199 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003200 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00003201 // Relax integer conversions like we do for pointers below.
3202 if (rhsType->isIntegerType())
3203 return IntToPointer;
3204 if (lhsType->isIntegerType())
3205 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00003206 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003207 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003208
Nate Begemanc5f0f652008-07-14 18:02:46 +00003209 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00003210 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00003211 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
3212 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003213 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003214
Nate Begemanc5f0f652008-07-14 18:02:46 +00003215 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003216 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003217 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003218 if (getLangOptions().LaxVectorConversions &&
3219 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003220 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003221 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003222 }
3223 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003224 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003225
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003226 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003227 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003228
Chris Lattner390564e2008-04-07 06:49:41 +00003229 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003230 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003231 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003232
Chris Lattner390564e2008-04-07 06:49:41 +00003233 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003234 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003235
Steve Naroffa982c712008-09-29 18:10:17 +00003236 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00003237 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003238 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003239
3240 // Treat block pointers as objects.
3241 if (getLangOptions().ObjC1 &&
3242 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3243 return Compatible;
3244 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003245 return Incompatible;
3246 }
3247
3248 if (isa<BlockPointerType>(lhsType)) {
3249 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003250 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003251
Steve Naroffa982c712008-09-29 18:10:17 +00003252 // Treat block pointers as objects.
3253 if (getLangOptions().ObjC1 &&
3254 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3255 return Compatible;
3256
Steve Naroff3454b6c2008-09-04 15:10:53 +00003257 if (rhsType->isBlockPointerType())
3258 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003259
Steve Naroff3454b6c2008-09-04 15:10:53 +00003260 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3261 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003262 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003263 }
Chris Lattner1853da22008-01-04 23:18:45 +00003264 return Incompatible;
3265 }
3266
Chris Lattner390564e2008-04-07 06:49:41 +00003267 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003268 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003269 if (lhsType == Context.BoolTy)
3270 return Compatible;
3271
3272 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003273 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003274
Mike Stump9afab102009-02-19 03:04:26 +00003275 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003276 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003277
3278 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003279 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003280 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003281 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003282 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003283
Chris Lattner1853da22008-01-04 23:18:45 +00003284 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003285 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003286 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003287 }
3288 return Incompatible;
3289}
3290
Douglas Gregor144b06c2009-04-29 22:16:16 +00003291/// \brief Constructs a transparent union from an expression that is
3292/// used to initialize the transparent union.
3293static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3294 QualType UnionType, FieldDecl *Field) {
3295 // Build an initializer list that designates the appropriate member
3296 // of the transparent union.
3297 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3298 &E, 1,
3299 SourceLocation());
3300 Initializer->setType(UnionType);
3301 Initializer->setInitializedFieldInUnion(Field);
3302
3303 // Build a compound literal constructing a value of the transparent
3304 // union type from this initializer list.
3305 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3306 false);
3307}
3308
3309Sema::AssignConvertType
3310Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3311 QualType FromType = rExpr->getType();
3312
3313 // If the ArgType is a Union type, we want to handle a potential
3314 // transparent_union GCC extension.
3315 const RecordType *UT = ArgType->getAsUnionType();
3316 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3317 return Incompatible;
3318
3319 // The field to initialize within the transparent union.
3320 RecordDecl *UD = UT->getDecl();
3321 FieldDecl *InitField = 0;
3322 // It's compatible if the expression matches any of the fields.
3323 for (RecordDecl::field_iterator it = UD->field_begin(Context),
3324 itend = UD->field_end(Context);
3325 it != itend; ++it) {
3326 if (it->getType()->isPointerType()) {
3327 // If the transparent union contains a pointer type, we allow:
3328 // 1) void pointer
3329 // 2) null pointer constant
3330 if (FromType->isPointerType())
3331 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3332 ImpCastExprToType(rExpr, it->getType());
3333 InitField = *it;
3334 break;
3335 }
3336
3337 if (rExpr->isNullPointerConstant(Context)) {
3338 ImpCastExprToType(rExpr, it->getType());
3339 InitField = *it;
3340 break;
3341 }
3342 }
3343
3344 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3345 == Compatible) {
3346 InitField = *it;
3347 break;
3348 }
3349 }
3350
3351 if (!InitField)
3352 return Incompatible;
3353
3354 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3355 return Compatible;
3356}
3357
Chris Lattner005ed752008-01-04 18:04:52 +00003358Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003359Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003360 if (getLangOptions().CPlusPlus) {
3361 if (!lhsType->isRecordType()) {
3362 // C++ 5.17p3: If the left operand is not of class type, the
3363 // expression is implicitly converted (C++ 4) to the
3364 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003365 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3366 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003367 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003368 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003369 }
3370
3371 // FIXME: Currently, we fall through and treat C++ classes like C
3372 // structures.
3373 }
3374
Steve Naroffcdee22d2007-11-27 17:58:44 +00003375 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3376 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003377 if ((lhsType->isPointerType() ||
3378 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003379 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003380 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003381 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003382 return Compatible;
3383 }
Mike Stump9afab102009-02-19 03:04:26 +00003384
Chris Lattner5f505bf2007-10-16 02:55:40 +00003385 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003386 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003387 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003388 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003389 //
Mike Stump9afab102009-02-19 03:04:26 +00003390 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003391 if (!lhsType->isReferenceType())
3392 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003393
Chris Lattner005ed752008-01-04 18:04:52 +00003394 Sema::AssignConvertType result =
3395 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003396
Steve Naroff0f32f432007-08-24 22:33:52 +00003397 // C99 6.5.16.1p2: The value of the right operand is converted to the
3398 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003399 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3400 // so that we can use references in built-in functions even in C.
3401 // The getNonReferenceType() call makes sure that the resulting expression
3402 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003403 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003404 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003405 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003406}
3407
Chris Lattner005ed752008-01-04 18:04:52 +00003408Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003409Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3410 return CheckAssignmentConstraints(lhsType, rhsType);
3411}
3412
Chris Lattner1eafdea2008-11-18 01:30:42 +00003413QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003414 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003415 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003416 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003417 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003418}
3419
Mike Stump9afab102009-02-19 03:04:26 +00003420inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003421 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003422 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003423 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003424 QualType lhsType =
3425 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3426 QualType rhsType =
3427 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003428
Nate Begemanc5f0f652008-07-14 18:02:46 +00003429 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003430 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003431 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003432
Nate Begemanc5f0f652008-07-14 18:02:46 +00003433 // Handle the case of a vector & extvector type of the same size and element
3434 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003435 if (getLangOptions().LaxVectorConversions) {
3436 // FIXME: Should we warn here?
3437 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003438 if (const VectorType *RV = rhsType->getAsVectorType())
3439 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003440 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003441 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003442 }
3443 }
3444 }
Mike Stump9afab102009-02-19 03:04:26 +00003445
Nate Begemanc5f0f652008-07-14 18:02:46 +00003446 // If the lhs is an extended vector and the rhs is a scalar of the same type
3447 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003448 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003449 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003450
3451 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003452 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3453 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003454 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003455 return lhsType;
3456 }
3457 }
3458
Nate Begemanc5f0f652008-07-14 18:02:46 +00003459 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003460 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003461 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003462 QualType eltType = V->getElementType();
3463
Mike Stump9afab102009-02-19 03:04:26 +00003464 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003465 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3466 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003467 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003468 return rhsType;
3469 }
3470 }
3471
Chris Lattner4b009652007-07-25 00:24:17 +00003472 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003473 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003474 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003475 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003476 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003477}
3478
Chris Lattner4b009652007-07-25 00:24:17 +00003479inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003480 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003481{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003482 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003483 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003484
Steve Naroff8f708362007-08-24 19:07:16 +00003485 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003486
Chris Lattner4b009652007-07-25 00:24:17 +00003487 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003488 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003489 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003490}
3491
3492inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003493 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003494{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003495 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3496 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3497 return CheckVectorOperands(Loc, lex, rex);
3498 return InvalidOperands(Loc, lex, rex);
3499 }
Chris Lattner4b009652007-07-25 00:24:17 +00003500
Steve Naroff8f708362007-08-24 19:07:16 +00003501 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003502
Chris Lattner4b009652007-07-25 00:24:17 +00003503 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003504 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003505 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003506}
3507
3508inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003509 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003510{
Eli Friedman3cd92882009-03-28 01:22:36 +00003511 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3512 QualType compType = CheckVectorOperands(Loc, lex, rex);
3513 if (CompLHSTy) *CompLHSTy = compType;
3514 return compType;
3515 }
Chris Lattner4b009652007-07-25 00:24:17 +00003516
Eli Friedman3cd92882009-03-28 01:22:36 +00003517 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003518
Chris Lattner4b009652007-07-25 00:24:17 +00003519 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003520 if (lex->getType()->isArithmeticType() &&
3521 rex->getType()->isArithmeticType()) {
3522 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003523 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003524 }
Chris Lattner4b009652007-07-25 00:24:17 +00003525
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003526 // Put any potential pointer into PExp
3527 Expr* PExp = lex, *IExp = rex;
3528 if (IExp->getType()->isPointerType())
3529 std::swap(PExp, IExp);
3530
Chris Lattner184f92d2009-04-24 23:50:08 +00003531 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003532 if (IExp->getType()->isIntegerType()) {
Chris Lattner184f92d2009-04-24 23:50:08 +00003533 QualType PointeeTy = PTy->getPointeeType();
3534 // Check for arithmetic on pointers to incomplete types.
3535 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003536 if (getLangOptions().CPlusPlus) {
3537 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003538 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003539 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003540 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003541
3542 // GNU extension: arithmetic on pointer to void
3543 Diag(Loc, diag::ext_gnu_void_ptr)
3544 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003545 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003546 if (getLangOptions().CPlusPlus) {
3547 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3548 << lex->getType() << lex->getSourceRange();
3549 return QualType();
3550 }
3551
3552 // GNU extension: arithmetic on pointer to function
3553 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3554 << lex->getType() << lex->getSourceRange();
3555 } else if (!PTy->isDependentType() &&
Chris Lattner184f92d2009-04-24 23:50:08 +00003556 RequireCompleteType(Loc, PointeeTy,
Douglas Gregor05e28f62009-03-24 19:52:54 +00003557 diag::err_typecheck_arithmetic_incomplete_type,
Chris Lattner184f92d2009-04-24 23:50:08 +00003558 PExp->getSourceRange(), SourceRange(),
3559 PExp->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00003560 return QualType();
3561
Chris Lattner184f92d2009-04-24 23:50:08 +00003562 // Diagnose bad cases where we step over interface counts.
3563 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3564 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3565 << PointeeTy << PExp->getSourceRange();
3566 return QualType();
3567 }
3568
Eli Friedman3cd92882009-03-28 01:22:36 +00003569 if (CompLHSTy) {
3570 QualType LHSTy = lex->getType();
3571 if (LHSTy->isPromotableIntegerType())
3572 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003573 else {
3574 QualType T = isPromotableBitField(lex, Context);
3575 if (!T.isNull())
3576 LHSTy = T;
3577 }
3578
Eli Friedman3cd92882009-03-28 01:22:36 +00003579 *CompLHSTy = LHSTy;
3580 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003581 return PExp->getType();
3582 }
3583 }
3584
Chris Lattner1eafdea2008-11-18 01:30:42 +00003585 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003586}
3587
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003588// C99 6.5.6
3589QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003590 SourceLocation Loc, QualType* CompLHSTy) {
3591 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3592 QualType compType = CheckVectorOperands(Loc, lex, rex);
3593 if (CompLHSTy) *CompLHSTy = compType;
3594 return compType;
3595 }
Mike Stump9afab102009-02-19 03:04:26 +00003596
Eli Friedman3cd92882009-03-28 01:22:36 +00003597 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003598
Chris Lattnerf6da2912007-12-09 21:53:25 +00003599 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003600
Chris Lattnerf6da2912007-12-09 21:53:25 +00003601 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00003602 if (lex->getType()->isArithmeticType()
3603 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00003604 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003605 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003606 }
Mike Stump9afab102009-02-19 03:04:26 +00003607
Chris Lattnerf6da2912007-12-09 21:53:25 +00003608 // Either ptr - int or ptr - ptr.
3609 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003610 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003611
Douglas Gregor05e28f62009-03-24 19:52:54 +00003612 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003613
Douglas Gregor05e28f62009-03-24 19:52:54 +00003614 bool ComplainAboutVoid = false;
3615 Expr *ComplainAboutFunc = 0;
3616 if (lpointee->isVoidType()) {
3617 if (getLangOptions().CPlusPlus) {
3618 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3619 << lex->getSourceRange() << rex->getSourceRange();
3620 return QualType();
3621 }
3622
3623 // GNU C extension: arithmetic on pointer to void
3624 ComplainAboutVoid = true;
3625 } else if (lpointee->isFunctionType()) {
3626 if (getLangOptions().CPlusPlus) {
3627 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003628 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003629 return QualType();
3630 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003631
3632 // GNU C extension: arithmetic on pointer to function
3633 ComplainAboutFunc = lex;
3634 } else if (!lpointee->isDependentType() &&
3635 RequireCompleteType(Loc, lpointee,
3636 diag::err_typecheck_sub_ptr_object,
3637 lex->getSourceRange(),
3638 SourceRange(),
3639 lex->getType()))
3640 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003641
Chris Lattner184f92d2009-04-24 23:50:08 +00003642 // Diagnose bad cases where we step over interface counts.
3643 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3644 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3645 << lpointee << lex->getSourceRange();
3646 return QualType();
3647 }
3648
Chris Lattnerf6da2912007-12-09 21:53:25 +00003649 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003650 if (rex->getType()->isIntegerType()) {
3651 if (ComplainAboutVoid)
3652 Diag(Loc, diag::ext_gnu_void_ptr)
3653 << lex->getSourceRange() << rex->getSourceRange();
3654 if (ComplainAboutFunc)
3655 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3656 << ComplainAboutFunc->getType()
3657 << ComplainAboutFunc->getSourceRange();
3658
Eli Friedman3cd92882009-03-28 01:22:36 +00003659 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003660 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003661 }
Mike Stump9afab102009-02-19 03:04:26 +00003662
Chris Lattnerf6da2912007-12-09 21:53:25 +00003663 // Handle pointer-pointer subtractions.
3664 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003665 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003666
Douglas Gregor05e28f62009-03-24 19:52:54 +00003667 // RHS must be a completely-type object type.
3668 // Handle the GNU void* extension.
3669 if (rpointee->isVoidType()) {
3670 if (getLangOptions().CPlusPlus) {
3671 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3672 << lex->getSourceRange() << rex->getSourceRange();
3673 return QualType();
3674 }
Mike Stump9afab102009-02-19 03:04:26 +00003675
Douglas Gregor05e28f62009-03-24 19:52:54 +00003676 ComplainAboutVoid = true;
3677 } else if (rpointee->isFunctionType()) {
3678 if (getLangOptions().CPlusPlus) {
3679 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003680 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003681 return QualType();
3682 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003683
3684 // GNU extension: arithmetic on pointer to function
3685 if (!ComplainAboutFunc)
3686 ComplainAboutFunc = rex;
3687 } else if (!rpointee->isDependentType() &&
3688 RequireCompleteType(Loc, rpointee,
3689 diag::err_typecheck_sub_ptr_object,
3690 rex->getSourceRange(),
3691 SourceRange(),
3692 rex->getType()))
3693 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003694
Chris Lattnerf6da2912007-12-09 21:53:25 +00003695 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003696 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003697 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003698 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003699 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003700 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003701 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003702 return QualType();
3703 }
Mike Stump9afab102009-02-19 03:04:26 +00003704
Douglas Gregor05e28f62009-03-24 19:52:54 +00003705 if (ComplainAboutVoid)
3706 Diag(Loc, diag::ext_gnu_void_ptr)
3707 << lex->getSourceRange() << rex->getSourceRange();
3708 if (ComplainAboutFunc)
3709 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3710 << ComplainAboutFunc->getType()
3711 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003712
3713 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003714 return Context.getPointerDiffType();
3715 }
3716 }
Mike Stump9afab102009-02-19 03:04:26 +00003717
Chris Lattner1eafdea2008-11-18 01:30:42 +00003718 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003719}
3720
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003721// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003722QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003723 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003724 // C99 6.5.7p2: Each of the operands shall have integer type.
3725 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003726 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003727
Chris Lattner2c8bff72007-12-12 05:47:28 +00003728 // Shifts don't perform usual arithmetic conversions, they just do integer
3729 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003730 QualType LHSTy;
3731 if (lex->getType()->isPromotableIntegerType())
3732 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003733 else {
3734 LHSTy = isPromotableBitField(lex, Context);
3735 if (LHSTy.isNull())
3736 LHSTy = lex->getType();
3737 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003738 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003739 ImpCastExprToType(lex, LHSTy);
3740
Chris Lattner2c8bff72007-12-12 05:47:28 +00003741 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003742
Chris Lattner2c8bff72007-12-12 05:47:28 +00003743 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003744 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003745}
3746
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003747// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003748QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003749 unsigned OpaqueOpc, bool isRelational) {
3750 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3751
Nate Begemanc5f0f652008-07-14 18:02:46 +00003752 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003753 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003754
Chris Lattner254f3bc2007-08-26 01:18:55 +00003755 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003756 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3757 UsualArithmeticConversions(lex, rex);
3758 else {
3759 UsualUnaryConversions(lex);
3760 UsualUnaryConversions(rex);
3761 }
Chris Lattner4b009652007-07-25 00:24:17 +00003762 QualType lType = lex->getType();
3763 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003764
Mike Stumpea3d74e2009-05-07 18:43:07 +00003765 if (!lType->isFloatingType()
3766 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003767 // For non-floating point types, check for self-comparisons of the form
3768 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3769 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003770 // NOTE: Don't warn about comparisons of enum constants. These can arise
3771 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003772 Expr *LHSStripped = lex->IgnoreParens();
3773 Expr *RHSStripped = rex->IgnoreParens();
3774 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3775 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003776 if (DRL->getDecl() == DRR->getDecl() &&
3777 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003778 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003779
3780 if (isa<CastExpr>(LHSStripped))
3781 LHSStripped = LHSStripped->IgnoreParenCasts();
3782 if (isa<CastExpr>(RHSStripped))
3783 RHSStripped = RHSStripped->IgnoreParenCasts();
3784
3785 // Warn about comparisons against a string constant (unless the other
3786 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003787 Expr *literalString = 0;
3788 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003789 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003790 !RHSStripped->isNullPointerConstant(Context)) {
3791 literalString = lex;
3792 literalStringStripped = LHSStripped;
3793 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003794 else if ((isa<StringLiteral>(RHSStripped) ||
3795 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003796 !LHSStripped->isNullPointerConstant(Context)) {
3797 literalString = rex;
3798 literalStringStripped = RHSStripped;
3799 }
3800
3801 if (literalString) {
3802 std::string resultComparison;
3803 switch (Opc) {
3804 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3805 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3806 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3807 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3808 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3809 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3810 default: assert(false && "Invalid comparison operator");
3811 }
3812 Diag(Loc, diag::warn_stringcompare)
3813 << isa<ObjCEncodeExpr>(literalStringStripped)
3814 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003815 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3816 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3817 "strcmp(")
3818 << CodeModificationHint::CreateInsertion(
3819 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003820 resultComparison);
3821 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003822 }
Mike Stump9afab102009-02-19 03:04:26 +00003823
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003824 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003825 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003826
Chris Lattner254f3bc2007-08-26 01:18:55 +00003827 if (isRelational) {
3828 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003829 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003830 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003831 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003832 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003833 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003834 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003835 }
Mike Stump9afab102009-02-19 03:04:26 +00003836
Chris Lattner254f3bc2007-08-26 01:18:55 +00003837 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003838 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003839 }
Mike Stump9afab102009-02-19 03:04:26 +00003840
Chris Lattner22be8422007-08-26 01:10:14 +00003841 bool LHSIsNull = lex->isNullPointerConstant(Context);
3842 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003843
Chris Lattner254f3bc2007-08-26 01:18:55 +00003844 // All of the following pointer related warnings are GCC extensions, except
3845 // when handling null pointer constants. One day, we can consider making them
3846 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003847 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003848 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003849 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003850 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003851 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003852
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003853 // Simple check: if the pointee types are identical, we're done.
3854 if (LCanPointeeTy == RCanPointeeTy)
3855 return ResultTy;
3856
3857 if (getLangOptions().CPlusPlus) {
3858 // C++ [expr.rel]p2:
3859 // [...] Pointer conversions (4.10) and qualification
3860 // conversions (4.4) are performed on pointer operands (or on
3861 // a pointer operand and a null pointer constant) to bring
3862 // them to their composite pointer type. [...]
3863 //
3864 // C++ [expr.eq]p2 uses the same notion for (in)equality
3865 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00003866 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003867 if (T.isNull()) {
3868 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
3869 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3870 return QualType();
3871 }
3872
3873 ImpCastExprToType(lex, T);
3874 ImpCastExprToType(rex, T);
3875 return ResultTy;
3876 }
3877
Steve Naroff3b435622007-11-13 14:57:38 +00003878 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003879 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3880 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003881 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003882 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003883 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003884 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003885 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003886 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003887 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003888 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00003889 // C++ allows comparison of pointers with null pointer constants.
3890 if (getLangOptions().CPlusPlus) {
3891 if (lType->isPointerType() && RHSIsNull) {
3892 ImpCastExprToType(rex, lType);
3893 return ResultTy;
3894 }
3895 if (rType->isPointerType() && LHSIsNull) {
3896 ImpCastExprToType(lex, rType);
3897 return ResultTy;
3898 }
3899 // And comparison of nullptr_t with itself.
3900 if (lType->isNullPtrType() && rType->isNullPtrType())
3901 return ResultTy;
3902 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003903 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00003904 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003905 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3906 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003907
Steve Naroff3454b6c2008-09-04 15:10:53 +00003908 if (!LHSIsNull && !RHSIsNull &&
3909 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003910 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003911 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003912 }
3913 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003914 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003915 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003916 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00003917 if (!isRelational
3918 && ((lType->isBlockPointerType() && rType->isPointerType())
3919 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00003920 if (!LHSIsNull && !RHSIsNull) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003921 if (!((rType->isPointerType() && rType->getAsPointerType()
3922 ->getPointeeType()->isVoidType())
3923 || (lType->isPointerType() && lType->getAsPointerType()
3924 ->getPointeeType()->isVoidType())))
3925 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3926 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003927 }
3928 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003929 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003930 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003931
Steve Naroff936c4362008-06-03 14:04:54 +00003932 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003933 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003934 const PointerType *LPT = lType->getAsPointerType();
3935 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003936 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003937 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003938 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003939 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003940
Steve Naroff030fcda2008-11-17 19:49:16 +00003941 if (!LPtrToVoid && !RPtrToVoid &&
3942 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003943 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003944 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003945 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003946 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003947 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003948 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003949 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003950 }
Steve Naroff936c4362008-06-03 14:04:54 +00003951 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3952 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003953 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003954 } else {
3955 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003956 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003957 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003958 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003959 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003960 }
Steve Naroff936c4362008-06-03 14:04:54 +00003961 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003962 }
Mike Stump9afab102009-02-19 03:04:26 +00003963 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003964 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003965 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003966 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003967 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003968 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003969 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003970 }
Mike Stump9afab102009-02-19 03:04:26 +00003971 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003972 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003973 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003974 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003975 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003976 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003977 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003978 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003979 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00003980 if (!isRelational && RHSIsNull
3981 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00003982 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003983 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003984 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00003985 if (!isRelational && LHSIsNull
3986 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00003987 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003988 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003989 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003990 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003991}
3992
Nate Begemanc5f0f652008-07-14 18:02:46 +00003993/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003994/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003995/// like a scalar comparison, a vector comparison produces a vector of integer
3996/// types.
3997QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003998 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003999 bool isRelational) {
4000 // Check to make sure we're operating on vectors of the same type and width,
4001 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004002 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004003 if (vType.isNull())
4004 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004005
Nate Begemanc5f0f652008-07-14 18:02:46 +00004006 QualType lType = lex->getType();
4007 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004008
Nate Begemanc5f0f652008-07-14 18:02:46 +00004009 // For non-floating point types, check for self-comparisons of the form
4010 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4011 // often indicate logic errors in the program.
4012 if (!lType->isFloatingType()) {
4013 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4014 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4015 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004016 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004017 }
Mike Stump9afab102009-02-19 03:04:26 +00004018
Nate Begemanc5f0f652008-07-14 18:02:46 +00004019 // Check for comparisons of floating point operands using != and ==.
4020 if (!isRelational && lType->isFloatingType()) {
4021 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004022 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004023 }
Mike Stump9afab102009-02-19 03:04:26 +00004024
Chris Lattner10687e32009-03-31 07:46:52 +00004025 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
4026 // just reject all vector comparisons for now.
4027 if (1) {
4028 Diag(Loc, diag::err_typecheck_vector_comparison)
4029 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4030 return QualType();
4031 }
4032
Nate Begemanc5f0f652008-07-14 18:02:46 +00004033 // Return the type for the comparison, which is the same as vector type for
4034 // integer vectors, or an integer type of identical size and number of
4035 // elements for floating point vectors.
4036 if (lType->isIntegerType())
4037 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004038
Nate Begemanc5f0f652008-07-14 18:02:46 +00004039 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004040 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004041 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004042 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004043 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004044 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4045
Mike Stump9afab102009-02-19 03:04:26 +00004046 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004047 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004048 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4049}
4050
Chris Lattner4b009652007-07-25 00:24:17 +00004051inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004052 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004053{
4054 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004055 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004056
Steve Naroff8f708362007-08-24 19:07:16 +00004057 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004058
Chris Lattner4b009652007-07-25 00:24:17 +00004059 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004060 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004061 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004062}
4063
4064inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004065 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004066{
4067 UsualUnaryConversions(lex);
4068 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004069
Eli Friedmanbea3f842008-05-13 20:16:47 +00004070 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004071 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004072 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004073}
4074
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004075/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4076/// is a read-only property; return true if so. A readonly property expression
4077/// depends on various declarations and thus must be treated specially.
4078///
Mike Stump9afab102009-02-19 03:04:26 +00004079static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004080{
4081 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4082 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4083 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4084 QualType BaseType = PropExpr->getBase()->getType();
4085 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00004086 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004087 PTy->getPointeeType()->getAsObjCInterfaceType())
4088 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
4089 if (S.isPropertyReadonly(PDecl, IFace))
4090 return true;
4091 }
4092 }
4093 return false;
4094}
4095
Chris Lattner4c2642c2008-11-18 01:22:49 +00004096/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4097/// emit an error and return true. If so, return false.
4098static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004099 SourceLocation OrigLoc = Loc;
4100 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4101 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004102 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4103 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004104 if (IsLV == Expr::MLV_Valid)
4105 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004106
Chris Lattner4c2642c2008-11-18 01:22:49 +00004107 unsigned Diag = 0;
4108 bool NeedType = false;
4109 switch (IsLV) { // C99 6.5.16p2
4110 default: assert(0 && "Unknown result from isModifiableLvalue!");
4111 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004112 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004113 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4114 NeedType = true;
4115 break;
Mike Stump9afab102009-02-19 03:04:26 +00004116 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004117 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4118 NeedType = true;
4119 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004120 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004121 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4122 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004123 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004124 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4125 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004126 case Expr::MLV_IncompleteType:
4127 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004128 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004129 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4130 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004131 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004132 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4133 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004134 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004135 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4136 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004137 case Expr::MLV_ReadonlyProperty:
4138 Diag = diag::error_readonly_property_assignment;
4139 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004140 case Expr::MLV_NoSetterProperty:
4141 Diag = diag::error_nosetter_property_assignment;
4142 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004143 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004144
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004145 SourceRange Assign;
4146 if (Loc != OrigLoc)
4147 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004148 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004149 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004150 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004151 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004152 return true;
4153}
4154
4155
4156
4157// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004158QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4159 SourceLocation Loc,
4160 QualType CompoundType) {
4161 // Verify that LHS is a modifiable lvalue, and emit error if not.
4162 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004163 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004164
4165 QualType LHSType = LHS->getType();
4166 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004167
Chris Lattner005ed752008-01-04 18:04:52 +00004168 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004169 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004170 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004171 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004172 // Special case of NSObject attributes on c-style pointer types.
4173 if (ConvTy == IncompatiblePointer &&
4174 ((Context.isObjCNSObjectType(LHSType) &&
4175 Context.isObjCObjectPointerType(RHSType)) ||
4176 (Context.isObjCNSObjectType(RHSType) &&
4177 Context.isObjCObjectPointerType(LHSType))))
4178 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004179
Chris Lattner34c85082008-08-21 18:04:13 +00004180 // If the RHS is a unary plus or minus, check to see if they = and + are
4181 // right next to each other. If so, the user may have typo'd "x =+ 4"
4182 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004183 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004184 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4185 RHSCheck = ICE->getSubExpr();
4186 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4187 if ((UO->getOpcode() == UnaryOperator::Plus ||
4188 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004189 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004190 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004191 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4192 // And there is a space or other character before the subexpr of the
4193 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004194 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4195 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004196 Diag(Loc, diag::warn_not_compound_assign)
4197 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4198 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004199 }
Chris Lattner34c85082008-08-21 18:04:13 +00004200 }
4201 } else {
4202 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00004203 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004204 }
Chris Lattner005ed752008-01-04 18:04:52 +00004205
Chris Lattner1eafdea2008-11-18 01:30:42 +00004206 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4207 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004208 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004209
Chris Lattner4b009652007-07-25 00:24:17 +00004210 // C99 6.5.16p3: The type of an assignment expression is the type of the
4211 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004212 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004213 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4214 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004215 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004216 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004217 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004218}
4219
Chris Lattner1eafdea2008-11-18 01:30:42 +00004220// C99 6.5.17
4221QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004222 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004223 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004224
4225 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4226 // incomplete in C++).
4227
Chris Lattner1eafdea2008-11-18 01:30:42 +00004228 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004229}
4230
4231/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4232/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004233QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4234 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004235 if (Op->isTypeDependent())
4236 return Context.DependentTy;
4237
Chris Lattnere65182c2008-11-21 07:05:48 +00004238 QualType ResType = Op->getType();
4239 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004240
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004241 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4242 // Decrement of bool is not allowed.
4243 if (!isInc) {
4244 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4245 return QualType();
4246 }
4247 // Increment of bool sets it to true, but is deprecated.
4248 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4249 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004250 // OK!
4251 } else if (const PointerType *PT = ResType->getAsPointerType()) {
4252 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004253 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004254 if (getLangOptions().CPlusPlus) {
4255 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4256 << Op->getSourceRange();
4257 return QualType();
4258 }
4259
4260 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004261 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004262 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004263 if (getLangOptions().CPlusPlus) {
4264 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4265 << Op->getType() << Op->getSourceRange();
4266 return QualType();
4267 }
4268
4269 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004270 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004271 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4272 diag::err_typecheck_arithmetic_incomplete_type,
4273 Op->getSourceRange(), SourceRange(),
4274 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004275 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004276 } else if (ResType->isComplexType()) {
4277 // C99 does not support ++/-- on complex types, we allow as an extension.
4278 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004279 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004280 } else {
4281 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004282 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004283 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004284 }
Mike Stump9afab102009-02-19 03:04:26 +00004285 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004286 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004287 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004288 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004289 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004290}
4291
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004292/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004293/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004294/// where the declaration is needed for type checking. We only need to
4295/// handle cases when the expression references a function designator
4296/// or is an lvalue. Here are some examples:
4297/// - &(x) => x
4298/// - &*****f => f for f a function designator.
4299/// - &s.xx => s
4300/// - &s.zz[1].yy -> s, if zz is an array
4301/// - *(x + 1) -> x, if x is an array
4302/// - &"123"[2] -> 0
4303/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004304static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004305 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004306 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004307 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004308 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004309 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004310 // If this is an arrow operator, the address is an offset from
4311 // the base's value, so the object the base refers to is
4312 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004313 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004314 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004315 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004316 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004317 case Stmt::ArraySubscriptExprClass: {
Eli Friedman93ecce22009-04-20 08:23:18 +00004318 // FIXME: This code shouldn't be necessary! We should catch the
4319 // implicit promotion of register arrays earlier.
4320 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4321 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4322 if (ICE->getSubExpr()->getType()->isArrayType())
4323 return getPrimaryDecl(ICE->getSubExpr());
4324 }
4325 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004326 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004327 case Stmt::UnaryOperatorClass: {
4328 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004329
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004330 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004331 case UnaryOperator::Real:
4332 case UnaryOperator::Imag:
4333 case UnaryOperator::Extension:
4334 return getPrimaryDecl(UO->getSubExpr());
4335 default:
4336 return 0;
4337 }
4338 }
Chris Lattner4b009652007-07-25 00:24:17 +00004339 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004340 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004341 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004342 // If the result of an implicit cast is an l-value, we care about
4343 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004344 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004345 default:
4346 return 0;
4347 }
4348}
4349
4350/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004351/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004352/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004353/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004354/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004355/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004356/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004357QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004358 // Make sure to ignore parentheses in subsequent checks
4359 op = op->IgnoreParens();
4360
Douglas Gregore6be68a2008-12-17 22:52:20 +00004361 if (op->isTypeDependent())
4362 return Context.DependentTy;
4363
Steve Naroff9c6c3592008-01-13 17:10:08 +00004364 if (getLangOptions().C99) {
4365 // Implement C99-only parts of addressof rules.
4366 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4367 if (uOp->getOpcode() == UnaryOperator::Deref)
4368 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4369 // (assuming the deref expression is valid).
4370 return uOp->getSubExpr()->getType();
4371 }
4372 // Technically, there should be a check for array subscript
4373 // expressions here, but the result of one is always an lvalue anyway.
4374 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004375 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004376 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004377
Chris Lattner4b009652007-07-25 00:24:17 +00004378 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004379 // The operand must be either an l-value or a function designator
Eli Friedmane7e4dac2009-05-03 22:36:05 +00004380 if (op->getType()->isFunctionType()) {
4381 // Function designator is valid
4382 } else if (lval == Expr::LV_IncompleteVoidType) {
4383 Diag(OpLoc, diag::ext_typecheck_addrof_void)
4384 << op->getSourceRange();
4385 } else {
Chris Lattnera3249072007-11-16 17:46:48 +00004386 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004387 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4388 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004389 return QualType();
4390 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004391 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004392 // The operand cannot be a bit-field
4393 Diag(OpLoc, diag::err_typecheck_address_of)
4394 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004395 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004396 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4397 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004398 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004399 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004400 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004401 return QualType();
4402 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004403 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004404 // with the register storage-class specifier.
4405 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4406 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004407 Diag(OpLoc, diag::err_typecheck_address_of)
4408 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004409 return QualType();
4410 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004411 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004412 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004413 } else if (isa<FieldDecl>(dcl)) {
4414 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004415 // Could be a pointer to member, though, if there is an explicit
4416 // scope qualifier for the class.
4417 if (isa<QualifiedDeclRefExpr>(op)) {
4418 DeclContext *Ctx = dcl->getDeclContext();
4419 if (Ctx && Ctx->isRecord())
4420 return Context.getMemberPointerType(op->getType(),
4421 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4422 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004423 } else if (isa<FunctionDecl>(dcl)) {
4424 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004425 // As above.
4426 if (isa<QualifiedDeclRefExpr>(op)) {
4427 DeclContext *Ctx = dcl->getDeclContext();
4428 if (Ctx && Ctx->isRecord())
4429 return Context.getMemberPointerType(op->getType(),
4430 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4431 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004432 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004433 else
Chris Lattner4b009652007-07-25 00:24:17 +00004434 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004435 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004436
Chris Lattner4b009652007-07-25 00:24:17 +00004437 // If the operand has type "type", the result has type "pointer to type".
4438 return Context.getPointerType(op->getType());
4439}
4440
Chris Lattnerda5c0872008-11-23 09:13:29 +00004441QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004442 if (Op->isTypeDependent())
4443 return Context.DependentTy;
4444
Chris Lattnerda5c0872008-11-23 09:13:29 +00004445 UsualUnaryConversions(Op);
4446 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004447
Chris Lattnerda5c0872008-11-23 09:13:29 +00004448 // Note that per both C89 and C99, this is always legal, even if ptype is an
4449 // incomplete type or void. It would be possible to warn about dereferencing
4450 // a void pointer, but it's completely well-defined, and such a warning is
4451 // unlikely to catch any mistakes.
4452 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004453 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004454
Chris Lattner77d52da2008-11-20 06:06:08 +00004455 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004456 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004457 return QualType();
4458}
4459
4460static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4461 tok::TokenKind Kind) {
4462 BinaryOperator::Opcode Opc;
4463 switch (Kind) {
4464 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004465 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4466 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004467 case tok::star: Opc = BinaryOperator::Mul; break;
4468 case tok::slash: Opc = BinaryOperator::Div; break;
4469 case tok::percent: Opc = BinaryOperator::Rem; break;
4470 case tok::plus: Opc = BinaryOperator::Add; break;
4471 case tok::minus: Opc = BinaryOperator::Sub; break;
4472 case tok::lessless: Opc = BinaryOperator::Shl; break;
4473 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4474 case tok::lessequal: Opc = BinaryOperator::LE; break;
4475 case tok::less: Opc = BinaryOperator::LT; break;
4476 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4477 case tok::greater: Opc = BinaryOperator::GT; break;
4478 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4479 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4480 case tok::amp: Opc = BinaryOperator::And; break;
4481 case tok::caret: Opc = BinaryOperator::Xor; break;
4482 case tok::pipe: Opc = BinaryOperator::Or; break;
4483 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4484 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4485 case tok::equal: Opc = BinaryOperator::Assign; break;
4486 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4487 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4488 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4489 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4490 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4491 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4492 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4493 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4494 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4495 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4496 case tok::comma: Opc = BinaryOperator::Comma; break;
4497 }
4498 return Opc;
4499}
4500
4501static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4502 tok::TokenKind Kind) {
4503 UnaryOperator::Opcode Opc;
4504 switch (Kind) {
4505 default: assert(0 && "Unknown unary op!");
4506 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4507 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4508 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4509 case tok::star: Opc = UnaryOperator::Deref; break;
4510 case tok::plus: Opc = UnaryOperator::Plus; break;
4511 case tok::minus: Opc = UnaryOperator::Minus; break;
4512 case tok::tilde: Opc = UnaryOperator::Not; break;
4513 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004514 case tok::kw___real: Opc = UnaryOperator::Real; break;
4515 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4516 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4517 }
4518 return Opc;
4519}
4520
Douglas Gregord7f915e2008-11-06 23:29:22 +00004521/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4522/// operator @p Opc at location @c TokLoc. This routine only supports
4523/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004524Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4525 unsigned Op,
4526 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004527 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004528 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004529 // The following two variables are used for compound assignment operators
4530 QualType CompLHSTy; // Type of LHS after promotions for computation
4531 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004532
4533 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004534 case BinaryOperator::Assign:
4535 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4536 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004537 case BinaryOperator::PtrMemD:
4538 case BinaryOperator::PtrMemI:
4539 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4540 Opc == BinaryOperator::PtrMemI);
4541 break;
4542 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004543 case BinaryOperator::Div:
4544 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4545 break;
4546 case BinaryOperator::Rem:
4547 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4548 break;
4549 case BinaryOperator::Add:
4550 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4551 break;
4552 case BinaryOperator::Sub:
4553 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4554 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004555 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004556 case BinaryOperator::Shr:
4557 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4558 break;
4559 case BinaryOperator::LE:
4560 case BinaryOperator::LT:
4561 case BinaryOperator::GE:
4562 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004563 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004564 break;
4565 case BinaryOperator::EQ:
4566 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004567 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004568 break;
4569 case BinaryOperator::And:
4570 case BinaryOperator::Xor:
4571 case BinaryOperator::Or:
4572 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4573 break;
4574 case BinaryOperator::LAnd:
4575 case BinaryOperator::LOr:
4576 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4577 break;
4578 case BinaryOperator::MulAssign:
4579 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004580 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4581 CompLHSTy = CompResultTy;
4582 if (!CompResultTy.isNull())
4583 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004584 break;
4585 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004586 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4587 CompLHSTy = CompResultTy;
4588 if (!CompResultTy.isNull())
4589 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004590 break;
4591 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004592 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4593 if (!CompResultTy.isNull())
4594 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004595 break;
4596 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004597 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4598 if (!CompResultTy.isNull())
4599 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004600 break;
4601 case BinaryOperator::ShlAssign:
4602 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004603 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4604 CompLHSTy = CompResultTy;
4605 if (!CompResultTy.isNull())
4606 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004607 break;
4608 case BinaryOperator::AndAssign:
4609 case BinaryOperator::XorAssign:
4610 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004611 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4612 CompLHSTy = CompResultTy;
4613 if (!CompResultTy.isNull())
4614 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004615 break;
4616 case BinaryOperator::Comma:
4617 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4618 break;
4619 }
4620 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004621 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004622 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004623 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4624 else
4625 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004626 CompLHSTy, CompResultTy,
4627 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004628}
4629
Chris Lattner4b009652007-07-25 00:24:17 +00004630// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004631Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4632 tok::TokenKind Kind,
4633 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004634 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00004635 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00004636
Steve Naroff87d58b42007-09-16 03:34:24 +00004637 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4638 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004639
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004640 if (getLangOptions().CPlusPlus &&
4641 (lhs->getType()->isOverloadableType() ||
4642 rhs->getType()->isOverloadableType())) {
4643 // Find all of the overloaded operators visible from this
4644 // point. We perform both an operator-name lookup from the local
4645 // scope and an argument-dependent lookup based on the types of
4646 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004647 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004648 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4649 if (OverOp != OO_None) {
4650 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4651 Functions);
4652 Expr *Args[2] = { lhs, rhs };
4653 DeclarationName OpName
4654 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4655 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004656 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004657
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004658 // Build the (potentially-overloaded, potentially-dependent)
4659 // binary operation.
4660 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004661 }
4662
Douglas Gregord7f915e2008-11-06 23:29:22 +00004663 // Build a built-in binary operation.
4664 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004665}
4666
Douglas Gregorc78182d2009-03-13 23:49:33 +00004667Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4668 unsigned OpcIn,
4669 ExprArg InputArg) {
4670 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004671
Douglas Gregorc78182d2009-03-13 23:49:33 +00004672 // FIXME: Input is modified below, but InputArg is not updated
4673 // appropriately.
4674 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004675 QualType resultType;
4676 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004677 case UnaryOperator::PostInc:
4678 case UnaryOperator::PostDec:
4679 case UnaryOperator::OffsetOf:
4680 assert(false && "Invalid unary operator");
4681 break;
4682
Chris Lattner4b009652007-07-25 00:24:17 +00004683 case UnaryOperator::PreInc:
4684 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004685 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4686 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004687 break;
Mike Stump9afab102009-02-19 03:04:26 +00004688 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004689 resultType = CheckAddressOfOperand(Input, OpLoc);
4690 break;
Mike Stump9afab102009-02-19 03:04:26 +00004691 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004692 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004693 resultType = CheckIndirectionOperand(Input, OpLoc);
4694 break;
4695 case UnaryOperator::Plus:
4696 case UnaryOperator::Minus:
4697 UsualUnaryConversions(Input);
4698 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004699 if (resultType->isDependentType())
4700 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004701 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4702 break;
4703 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4704 resultType->isEnumeralType())
4705 break;
4706 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4707 Opc == UnaryOperator::Plus &&
4708 resultType->isPointerType())
4709 break;
4710
Sebastian Redl8b769972009-01-19 00:08:26 +00004711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4712 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004713 case UnaryOperator::Not: // bitwise complement
4714 UsualUnaryConversions(Input);
4715 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004716 if (resultType->isDependentType())
4717 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004718 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4719 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4720 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004721 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004722 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004723 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004724 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4725 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004726 break;
4727 case UnaryOperator::LNot: // logical negation
4728 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4729 DefaultFunctionArrayConversion(Input);
4730 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004731 if (resultType->isDependentType())
4732 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004733 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004734 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4735 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004736 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004737 // In C++, it's bool. C++ 5.3.1p8
4738 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004739 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004740 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004741 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004742 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004743 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004744 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004745 resultType = Input->getType();
4746 break;
4747 }
4748 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004749 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004750
4751 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004752 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004753}
4754
Douglas Gregorc78182d2009-03-13 23:49:33 +00004755// Unary Operators. 'Tok' is the token for the operator.
4756Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4757 tok::TokenKind Op, ExprArg input) {
4758 Expr *Input = (Expr*)input.get();
4759 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4760
4761 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4762 // Find all of the overloaded operators visible from this
4763 // point. We perform both an operator-name lookup from the local
4764 // scope and an argument-dependent lookup based on the types of
4765 // the arguments.
4766 FunctionSet Functions;
4767 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4768 if (OverOp != OO_None) {
4769 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4770 Functions);
4771 DeclarationName OpName
4772 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4773 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4774 }
4775
4776 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4777 }
4778
4779 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4780}
4781
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004782/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004783Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4784 SourceLocation LabLoc,
4785 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004786 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00004787 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004788
Daniel Dunbar879788d2008-08-04 16:51:22 +00004789 // If we haven't seen this label yet, create a forward reference. It
4790 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004791 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004792 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004793
Chris Lattner4b009652007-07-25 00:24:17 +00004794 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004795 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4796 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004797}
4798
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004799Sema::OwningExprResult
4800Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4801 SourceLocation RPLoc) { // "({..})"
4802 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004803 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4804 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4805
Eli Friedmanbc941e12009-01-24 23:09:00 +00004806 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00004807 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004808 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004809
Chris Lattner4b009652007-07-25 00:24:17 +00004810 // FIXME: there are a variety of strange constraints to enforce here, for
4811 // example, it is not possible to goto into a stmt expression apparently.
4812 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004813
Chris Lattner4b009652007-07-25 00:24:17 +00004814 // If there are sub stmts in the compound stmt, take the type of the last one
4815 // as the type of the stmtexpr.
4816 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004817
Chris Lattner200964f2008-07-26 19:51:01 +00004818 if (!Compound->body_empty()) {
4819 Stmt *LastStmt = Compound->body_back();
4820 // If LastStmt is a label, skip down through into the body.
4821 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4822 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004823
Chris Lattner200964f2008-07-26 19:51:01 +00004824 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004825 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004826 }
Mike Stump9afab102009-02-19 03:04:26 +00004827
Eli Friedman2b128322009-03-23 00:24:07 +00004828 // FIXME: Check that expression type is complete/non-abstract; statement
4829 // expressions are not lvalues.
4830
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004831 substmt.release();
4832 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004833}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004834
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004835Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4836 SourceLocation BuiltinLoc,
4837 SourceLocation TypeLoc,
4838 TypeTy *argty,
4839 OffsetOfComponent *CompPtr,
4840 unsigned NumComponents,
4841 SourceLocation RPLoc) {
4842 // FIXME: This function leaks all expressions in the offset components on
4843 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004844 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4845 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004846
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004847 bool Dependent = ArgTy->isDependentType();
4848
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004849 // We must have at least one component that refers to the type, and the first
4850 // one is known to be a field designator. Verify that the ArgTy represents
4851 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004852 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004853 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004854
Eli Friedman2b128322009-03-23 00:24:07 +00004855 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4856 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004857
Eli Friedman342d9432009-02-27 06:44:11 +00004858 // Otherwise, create a null pointer as the base, and iteratively process
4859 // the offsetof designators.
4860 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4861 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004862 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004863 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004864
Chris Lattnerb37522e2007-08-31 21:49:13 +00004865 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4866 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004867 // FIXME: This diagnostic isn't actually visible because the location is in
4868 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004869 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004870 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4871 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004872
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004873 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00004874 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00004875
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004876 // FIXME: Dependent case loses a lot of information here. And probably
4877 // leaks like a sieve.
4878 for (unsigned i = 0; i != NumComponents; ++i) {
4879 const OffsetOfComponent &OC = CompPtr[i];
4880 if (OC.isBrackets) {
4881 // Offset of an array sub-field. TODO: Should we allow vector elements?
4882 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4883 if (!AT) {
4884 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004885 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4886 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004887 }
4888
4889 // FIXME: C++: Verify that operator[] isn't overloaded.
4890
Eli Friedman342d9432009-02-27 06:44:11 +00004891 // Promote the array so it looks more like a normal array subscript
4892 // expression.
4893 DefaultFunctionArrayConversion(Res);
4894
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004895 // C99 6.5.2.1p1
4896 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004897 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004898 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004899 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00004900 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004901 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004902
4903 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4904 OC.LocEnd);
4905 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004906 }
Mike Stump9afab102009-02-19 03:04:26 +00004907
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004908 const RecordType *RC = Res->getType()->getAsRecordType();
4909 if (!RC) {
4910 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004911 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4912 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004913 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004914
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004915 // Get the decl corresponding to this.
4916 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00004917 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00004918 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00004919 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
4920 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
4921 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00004922 DidWarnAboutNonPOD = true;
4923 }
Anders Carlsson356946e2009-05-01 23:20:30 +00004924 }
4925
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004926 FieldDecl *MemberDecl
4927 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4928 LookupMemberName)
4929 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004930 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004931 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004932 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4933 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004934
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004935 // FIXME: C++: Verify that MemberDecl isn't a static field.
4936 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00004937 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00004938 Res = BuildAnonymousStructUnionMemberReference(
4939 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00004940 } else {
4941 // MemberDecl->getType() doesn't get the right qualifiers, but it
4942 // doesn't matter here.
4943 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4944 MemberDecl->getType().getNonReferenceType());
4945 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004946 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004947 }
Mike Stump9afab102009-02-19 03:04:26 +00004948
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004949 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4950 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004951}
4952
4953
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004954Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4955 TypeTy *arg1,TypeTy *arg2,
4956 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004957 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4958 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004959
Steve Naroff63bad2d2007-08-01 22:05:33 +00004960 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004961
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004962 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4963 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004964}
4965
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004966Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4967 ExprArg cond,
4968 ExprArg expr1, ExprArg expr2,
4969 SourceLocation RPLoc) {
4970 Expr *CondExpr = static_cast<Expr*>(cond.get());
4971 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4972 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004973
Steve Naroff93c53012007-08-03 21:21:27 +00004974 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4975
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004976 QualType resType;
4977 if (CondExpr->isValueDependent()) {
4978 resType = Context.DependentTy;
4979 } else {
4980 // The conditional expression is required to be a constant expression.
4981 llvm::APSInt condEval(32);
4982 SourceLocation ExpLoc;
4983 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004984 return ExprError(Diag(ExpLoc,
4985 diag::err_typecheck_choose_expr_requires_constant)
4986 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004987
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004988 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4989 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4990 }
4991
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004992 cond.release(); expr1.release(); expr2.release();
4993 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4994 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004995}
4996
Steve Naroff52a81c02008-09-03 18:15:37 +00004997//===----------------------------------------------------------------------===//
4998// Clang Extensions.
4999//===----------------------------------------------------------------------===//
5000
5001/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005002void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005003 // Analyze block parameters.
5004 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005005
Steve Naroff52a81c02008-09-03 18:15:37 +00005006 // Add BSI to CurBlock.
5007 BSI->PrevBlockInfo = CurBlock;
5008 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005009
Steve Naroff52a81c02008-09-03 18:15:37 +00005010 BSI->ReturnType = 0;
5011 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005012 BSI->hasBlockDeclRefExprs = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005013 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5014 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005015
Steve Naroff52059382008-10-10 01:28:17 +00005016 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005017 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005018}
5019
Mike Stumpc1fddff2009-02-04 22:31:32 +00005020void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005021 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005022
Mike Stump9e439c92009-04-29 21:40:37 +00005023 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
5024
Mike Stumpc1fddff2009-02-04 22:31:32 +00005025 if (ParamInfo.getNumTypeObjects() == 0
5026 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5027 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5028
Mike Stump458287d2009-04-28 01:10:27 +00005029 if (T->isArrayType()) {
5030 Diag(ParamInfo.getSourceRange().getBegin(),
5031 diag::err_block_returns_array);
5032 return;
5033 }
5034
Mike Stumpc1fddff2009-02-04 22:31:32 +00005035 // The parameter list is optional, if there was none, assume ().
5036 if (!T->isFunctionType())
5037 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5038
5039 CurBlock->hasPrototype = true;
5040 CurBlock->isVariadic = false;
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005041
5042 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5043
5044 // Do not allow returning a objc interface by-value.
5045 if (RetTy->isObjCInterfaceType()) {
5046 Diag(ParamInfo.getSourceRange().getBegin(),
5047 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5048 return;
5049 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005050 return;
5051 }
5052
Steve Naroff52a81c02008-09-03 18:15:37 +00005053 // Analyze arguments to block.
5054 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5055 "Not a function declarator!");
5056 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005057
Steve Naroff52059382008-10-10 01:28:17 +00005058 CurBlock->hasPrototype = FTI.hasPrototype;
5059 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005060
Steve Naroff52a81c02008-09-03 18:15:37 +00005061 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5062 // no arguments, not a function that takes a single void argument.
5063 if (FTI.hasPrototype &&
5064 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005065 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5066 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005067 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005068 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005069 } else if (FTI.hasPrototype) {
5070 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005071 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005072 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005073 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00005074 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005075 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00005076
Steve Naroff52059382008-10-10 01:28:17 +00005077 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5078 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5079 // If this has an identifier, add it to the scope stack.
5080 if ((*AI)->getIdentifier())
5081 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005082
5083 // Analyze the return type.
5084 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5085 QualType RetTy = T->getAsFunctionType()->getResultType();
5086
5087 // Do not allow returning a objc interface by-value.
5088 if (RetTy->isObjCInterfaceType()) {
5089 Diag(ParamInfo.getSourceRange().getBegin(),
5090 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5091 } else if (!RetTy->isDependentType())
5092 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00005093}
5094
5095/// ActOnBlockError - If there is an error parsing a block, this callback
5096/// is invoked to pop the information about the block from the action impl.
5097void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5098 // Ensure that CurBlock is deleted.
5099 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005100
Chris Lattnere7765e12009-04-19 05:28:12 +00005101 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5102
Steve Naroff52a81c02008-09-03 18:15:37 +00005103 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005104 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005105 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005106 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005107}
5108
5109/// ActOnBlockStmtExpr - This is called when the body of a block statement
5110/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005111Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5112 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005113 // If blocks are disabled, emit an error.
5114 if (!LangOpts.Blocks)
5115 Diag(CaretLoc, diag::err_blocks_disable);
5116
Steve Naroff52a81c02008-09-03 18:15:37 +00005117 // Ensure that CurBlock is deleted.
5118 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005119
Steve Naroff52059382008-10-10 01:28:17 +00005120 PopDeclContext();
5121
Steve Naroff52a81c02008-09-03 18:15:37 +00005122 // Pop off CurBlock, handle nested blocks.
5123 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005124
Steve Naroff52a81c02008-09-03 18:15:37 +00005125 QualType RetTy = Context.VoidTy;
5126 if (BSI->ReturnType)
5127 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005128
Steve Naroff52a81c02008-09-03 18:15:37 +00005129 llvm::SmallVector<QualType, 8> ArgTypes;
5130 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5131 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005132
Steve Naroff52a81c02008-09-03 18:15:37 +00005133 QualType BlockTy;
5134 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00005135 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00005136 else
5137 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00005138 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005139
Eli Friedman2b128322009-03-23 00:24:07 +00005140 // FIXME: Check that return/parameter types are complete/non-abstract
5141
Steve Naroff52a81c02008-09-03 18:15:37 +00005142 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005143
Chris Lattnere7765e12009-04-19 05:28:12 +00005144 // If needed, diagnose invalid gotos and switches in the block.
5145 if (CurFunctionNeedsScopeChecking)
5146 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5147 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5148
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005149 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005150 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5151 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005152}
5153
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005154Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5155 ExprArg expr, TypeTy *type,
5156 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005157 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005158 Expr *E = static_cast<Expr*>(expr.get());
5159 Expr *OrigExpr = E;
5160
Anders Carlsson36760332007-10-15 20:28:48 +00005161 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005162
5163 // Get the va_list type
5164 QualType VaListType = Context.getBuiltinVaListType();
5165 // Deal with implicit array decay; for example, on x86-64,
5166 // va_list is an array, but it's supposed to decay to
5167 // a pointer for va_arg.
5168 if (VaListType->isArrayType())
5169 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00005170 // Make sure the input expression also decays appropriately.
5171 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005172
Chris Lattnercb9469d2009-04-06 17:07:34 +00005173 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005174 return ExprError(Diag(E->getLocStart(),
5175 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005176 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005177 }
Mike Stump9afab102009-02-19 03:04:26 +00005178
Eli Friedman2b128322009-03-23 00:24:07 +00005179 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005180 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005181
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005182 expr.release();
5183 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5184 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005185}
5186
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005187Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005188 // The type of __null will be int or long, depending on the size of
5189 // pointers on the target.
5190 QualType Ty;
5191 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5192 Ty = Context.IntTy;
5193 else
5194 Ty = Context.LongTy;
5195
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005196 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005197}
5198
Chris Lattner005ed752008-01-04 18:04:52 +00005199bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5200 SourceLocation Loc,
5201 QualType DstType, QualType SrcType,
5202 Expr *SrcExpr, const char *Flavor) {
5203 // Decode the result (notice that AST's are still created for extensions).
5204 bool isInvalid = false;
5205 unsigned DiagKind;
5206 switch (ConvTy) {
5207 default: assert(0 && "Unknown conversion type");
5208 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005209 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005210 DiagKind = diag::ext_typecheck_convert_pointer_int;
5211 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005212 case IntToPointer:
5213 DiagKind = diag::ext_typecheck_convert_int_pointer;
5214 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005215 case IncompatiblePointer:
5216 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5217 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005218 case IncompatiblePointerSign:
5219 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5220 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005221 case FunctionVoidPointer:
5222 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5223 break;
5224 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005225 // If the qualifiers lost were because we were applying the
5226 // (deprecated) C++ conversion from a string literal to a char*
5227 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5228 // Ideally, this check would be performed in
5229 // CheckPointerTypesForAssignment. However, that would require a
5230 // bit of refactoring (so that the second argument is an
5231 // expression, rather than a type), which should be done as part
5232 // of a larger effort to fix CheckPointerTypesForAssignment for
5233 // C++ semantics.
5234 if (getLangOptions().CPlusPlus &&
5235 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5236 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005237 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5238 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005239 case IntToBlockPointer:
5240 DiagKind = diag::err_int_to_block_pointer;
5241 break;
5242 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005243 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005244 break;
Steve Naroff19608432008-10-14 22:18:38 +00005245 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005246 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005247 // it can give a more specific diagnostic.
5248 DiagKind = diag::warn_incompatible_qualified_id;
5249 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005250 case IncompatibleVectors:
5251 DiagKind = diag::warn_incompatible_vectors;
5252 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005253 case Incompatible:
5254 DiagKind = diag::err_typecheck_convert_incompatible;
5255 isInvalid = true;
5256 break;
5257 }
Mike Stump9afab102009-02-19 03:04:26 +00005258
Chris Lattner271d4c22008-11-24 05:29:24 +00005259 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5260 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005261 return isInvalid;
5262}
Anders Carlssond5201b92008-11-30 19:50:32 +00005263
Chris Lattnereec8ae22009-04-25 21:59:05 +00005264bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005265 llvm::APSInt ICEResult;
5266 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5267 if (Result)
5268 *Result = ICEResult;
5269 return false;
5270 }
5271
Anders Carlssond5201b92008-11-30 19:50:32 +00005272 Expr::EvalResult EvalResult;
5273
Mike Stump9afab102009-02-19 03:04:26 +00005274 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005275 EvalResult.HasSideEffects) {
5276 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5277
5278 if (EvalResult.Diag) {
5279 // We only show the note if it's not the usual "invalid subexpression"
5280 // or if it's actually in a subexpression.
5281 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5282 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5283 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5284 }
Mike Stump9afab102009-02-19 03:04:26 +00005285
Anders Carlssond5201b92008-11-30 19:50:32 +00005286 return true;
5287 }
5288
Eli Friedmance329412009-04-25 22:26:58 +00005289 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5290 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005291
Eli Friedmance329412009-04-25 22:26:58 +00005292 if (EvalResult.Diag &&
5293 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5294 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005295
Anders Carlssond5201b92008-11-30 19:50:32 +00005296 if (Result)
5297 *Result = EvalResult.Val.getInt();
5298 return false;
5299}