blob: 1abd5fb302e7e948a87eb8c7c7eaafe74c525074 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor48f3bb92009-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 Lattner76a642f2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregor48f3bb92009-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 Lattnerf15970c2009-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 Gregor6ab35242009-04-09 21:40:53 +000061 MD = Impl->getClassInterface()->getMethod(Context,
62 MD->getSelector(),
Chris Lattnerf15970c2009-02-16 19:35:30 +000063 MD->isInstanceMethod());
64 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
65 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner76a642f2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregor48f3bb92009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-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 Gregor25d944a2009-02-24 04:26:15 +000080 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
83 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner76a642f2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregor48f3bb92009-02-18 21:56:37 +000088 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian5b530052009-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 Jahanian88f1ba02009-05-13 23:20:50 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
99 if (!attr)
100 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000103
Mike Stump390b4cc2009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000120 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000121 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
131 }
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000132 else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
133 // block or function pointer call.
134 QualType Ty = V->getType();
135 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
136 const FunctionType *FT = Ty->isFunctionPointerType()
137 ? Ty->getAsPointerType()->getPointeeType()->getAsFunctionType()
138 : Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
139 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
140 unsigned NumArgsInProto = Proto->getNumArgs();
141 unsigned k;
142 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
143 if (nullPos)
144 --nullPos;
145 else
146 ++i;
147 }
148 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
149 }
150 if (Ty->isBlockPointerType())
151 isMethod = 2;
152 }
153 else
154 return;
155 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000156 else
157 return;
158
159 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000160 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 return;
163 }
164 int sentinel = i;
165 while (sentinelPos > 0 && i < NumArgs-1) {
166 --sentinelPos;
167 ++i;
168 }
169 if (sentinelPos > 0) {
170 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000171 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000172 return;
173 }
174 while (i < NumArgs-1) {
175 ++i;
176 ++sentinel;
177 }
178 Expr *sentinelExpr = Args[sentinel];
179 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
180 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000181 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000182 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000183 }
184 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000185}
186
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000187SourceRange Sema::getExprRange(ExprTy *E) const {
188 Expr *Ex = (Expr *)E;
189 return Ex? Ex->getSourceRange() : SourceRange();
190}
191
Chris Lattnere7a2e912008-07-25 21:10:04 +0000192//===----------------------------------------------------------------------===//
193// Standard Promotions and Conversions
194//===----------------------------------------------------------------------===//
195
Chris Lattnere7a2e912008-07-25 21:10:04 +0000196/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
197void Sema::DefaultFunctionArrayConversion(Expr *&E) {
198 QualType Ty = E->getType();
199 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
200
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201 if (Ty->isFunctionType())
202 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +0000203 else if (Ty->isArrayType()) {
204 // In C90 mode, arrays only promote to pointers if the array expression is
205 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
206 // type 'array of type' is converted to an expression that has type 'pointer
207 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
208 // that has type 'array of type' ...". The relevant change is "an lvalue"
209 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000210 //
211 // C++ 4.2p1:
212 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
213 // T" can be converted to an rvalue of type "pointer to T".
214 //
215 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
216 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +0000217 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
218 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000219}
220
Douglas Gregorfc24e442009-05-01 20:41:21 +0000221/// \brief Whether this is a promotable bitfield reference according
222/// to C99 6.3.1.1p2, bullet 2.
223///
224/// \returns the type this bit-field will promote to, or NULL if no
225/// promotion occurs.
226static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000227 FieldDecl *Field = E->getBitField();
228 if (!Field)
Douglas Gregorfc24e442009-05-01 20:41:21 +0000229 return QualType();
230
231 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
232 if (!BT)
233 return QualType();
234
235 if (BT->getKind() != BuiltinType::Bool &&
236 BT->getKind() != BuiltinType::Int &&
237 BT->getKind() != BuiltinType::UInt)
238 return QualType();
239
240 llvm::APSInt BitWidthAP;
241 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
242 return QualType();
243
244 uint64_t BitWidth = BitWidthAP.getZExtValue();
245 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
246 if (BitWidth < IntSize ||
247 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
248 return Context.IntTy;
249
250 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
251 return Context.UnsignedIntTy;
252
253 return QualType();
254}
255
Chris Lattnere7a2e912008-07-25 21:10:04 +0000256/// UsualUnaryConversions - Performs various conversions that are common to most
257/// operators (C99 6.3). The conversions of array and function types are
258/// sometimes surpressed. For example, the array->pointer conversion doesn't
259/// apply if the array is an argument to the sizeof or address (&) operators.
260/// In these instances, this routine should *not* be called.
261Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
262 QualType Ty = Expr->getType();
263 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
264
Douglas Gregorfc24e442009-05-01 20:41:21 +0000265 // C99 6.3.1.1p2:
266 //
267 // The following may be used in an expression wherever an int or
268 // unsigned int may be used:
269 // - an object or expression with an integer type whose integer
270 // conversion rank is less than or equal to the rank of int
271 // and unsigned int.
272 // - A bit-field of type _Bool, int, signed int, or unsigned int.
273 //
274 // If an int can represent all values of the original type, the
275 // value is converted to an int; otherwise, it is converted to an
276 // unsigned int. These are called the integer promotions. All
277 // other types are unchanged by the integer promotions.
278 if (Ty->isPromotableIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000280 return Expr;
281 } else {
282 QualType T = isPromotableBitField(Expr, Context);
283 if (!T.isNull()) {
284 ImpCastExprToType(Expr, T);
285 return Expr;
286 }
287 }
288
289 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000290 return Expr;
291}
292
Chris Lattner05faf172008-07-25 22:25:12 +0000293/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
294/// do not have a prototype. Arguments that have type float are promoted to
295/// double. All other argument types are converted by UsualUnaryConversions().
296void Sema::DefaultArgumentPromotion(Expr *&Expr) {
297 QualType Ty = Expr->getType();
298 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
299
300 // If this is a 'float' (CVR qualified or typedef) promote to double.
301 if (const BuiltinType *BT = Ty->getAsBuiltinType())
302 if (BT->getKind() == BuiltinType::Float)
303 return ImpCastExprToType(Expr, Context.DoubleTy);
304
305 UsualUnaryConversions(Expr);
306}
307
Chris Lattner312531a2009-04-12 08:11:20 +0000308/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
309/// will warn if the resulting type is not a POD type, and rejects ObjC
310/// interfaces passed by value. This returns true if the argument type is
311/// completely illegal.
312bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000313 DefaultArgumentPromotion(Expr);
314
Chris Lattner312531a2009-04-12 08:11:20 +0000315 if (Expr->getType()->isObjCInterfaceType()) {
316 Diag(Expr->getLocStart(),
317 diag::err_cannot_pass_objc_interface_to_vararg)
318 << Expr->getType() << CT;
319 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000320 }
Chris Lattner312531a2009-04-12 08:11:20 +0000321
322 if (!Expr->getType()->isPODType())
323 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
324 << Expr->getType() << CT;
325
326 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000327}
328
329
Chris Lattnere7a2e912008-07-25 21:10:04 +0000330/// UsualArithmeticConversions - Performs various conversions that are common to
331/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
332/// routine returns the first non-arithmetic type found. The client is
333/// responsible for emitting appropriate error diagnostics.
334/// FIXME: verify the conversion rules for "complex int" are consistent with
335/// GCC.
336QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
337 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000338 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000339 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000340
341 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000342
Chris Lattnere7a2e912008-07-25 21:10:04 +0000343 // For conversion purposes, we ignore any qualifiers.
344 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000345 QualType lhs =
346 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
347 QualType rhs =
348 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000349
350 // If both types are identical, no conversion is needed.
351 if (lhs == rhs)
352 return lhs;
353
354 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
355 // The caller can deal with this (e.g. pointer + int).
356 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
357 return lhs;
358
Douglas Gregor2d833e32009-05-02 00:36:19 +0000359 // Perform bitfield promotions.
360 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
361 if (!LHSBitfieldPromoteTy.isNull())
362 lhs = LHSBitfieldPromoteTy;
363 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
364 if (!RHSBitfieldPromoteTy.isNull())
365 rhs = RHSBitfieldPromoteTy;
366
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000367 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000368 if (!isCompAssign)
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000369 ImpCastExprToType(lhsExpr, destType);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000370 ImpCastExprToType(rhsExpr, destType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000371 return destType;
372}
373
374QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
375 // Perform the usual unary conversions. We do this early so that
376 // integral promotions to "int" can allow us to exit early, in the
377 // lhs == rhs check. Also, for conversion purposes, we ignore any
378 // qualifiers. For example, "const float" and "float" are
379 // equivalent.
Chris Lattner76a642f2009-02-15 22:43:40 +0000380 if (lhs->isPromotableIntegerType())
381 lhs = Context.IntTy;
382 else
383 lhs = lhs.getUnqualifiedType();
384 if (rhs->isPromotableIntegerType())
385 rhs = Context.IntTy;
386 else
387 rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000388
Chris Lattnere7a2e912008-07-25 21:10:04 +0000389 // If both types are identical, no conversion is needed.
390 if (lhs == rhs)
391 return lhs;
392
393 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
394 // The caller can deal with this (e.g. pointer + int).
395 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
396 return lhs;
397
398 // At this point, we have two different arithmetic types.
399
400 // Handle complex types first (C99 6.3.1.8p1).
401 if (lhs->isComplexType() || rhs->isComplexType()) {
402 // if we have an integer operand, the result is the complex type.
403 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
404 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000405 return lhs;
406 }
407 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
408 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000409 return rhs;
410 }
411 // This handles complex/complex, complex/float, or float/complex.
412 // When both operands are complex, the shorter operand is converted to the
413 // type of the longer, and that is the type of the result. This corresponds
414 // to what is done when combining two real floating-point operands.
415 // The fun begins when size promotion occur across type domains.
416 // From H&S 6.3.4: When one operand is complex and the other is a real
417 // floating-point type, the less precise type is converted, within it's
418 // real or complex domain, to the precision of the other type. For example,
419 // when combining a "long double" with a "double _Complex", the
420 // "double _Complex" is promoted to "long double _Complex".
421 int result = Context.getFloatingTypeOrder(lhs, rhs);
422
423 if (result > 0) { // The left side is bigger, convert rhs.
424 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000425 } else if (result < 0) { // The right side is bigger, convert lhs.
426 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000427 }
428 // At this point, lhs and rhs have the same rank/size. Now, make sure the
429 // domains match. This is a requirement for our implementation, C99
430 // does not require this promotion.
431 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
432 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000433 return rhs;
434 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000435 return lhs;
436 }
437 }
438 return lhs; // The domain/size match exactly.
439 }
440 // Now handle "real" floating types (i.e. float, double, long double).
441 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
442 // if we have an integer operand, the result is the real floating type.
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000443 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000444 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000445 return lhs;
446 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000447 if (rhs->isComplexIntegerType()) {
448 // convert rhs to the complex floating point type.
449 return Context.getComplexType(lhs);
450 }
451 if (lhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000452 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000453 return rhs;
454 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000455 if (lhs->isComplexIntegerType()) {
456 // convert lhs to the complex floating point type.
457 return Context.getComplexType(rhs);
458 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000459 // We have two real floating types, float/complex combos were handled above.
460 // Convert the smaller operand to the bigger result.
461 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner76a642f2009-02-15 22:43:40 +0000462 if (result > 0) // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000463 return lhs;
Chris Lattner76a642f2009-02-15 22:43:40 +0000464 assert(result < 0 && "illegal float comparison");
465 return rhs; // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000466 }
467 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
468 // Handle GCC complex int extension.
469 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
470 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
471
472 if (lhsComplexInt && rhsComplexInt) {
473 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner76a642f2009-02-15 22:43:40 +0000474 rhsComplexInt->getElementType()) >= 0)
475 return lhs; // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000476 return rhs;
477 } else if (lhsComplexInt && rhs->isIntegerType()) {
478 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000479 return lhs;
480 } else if (rhsComplexInt && lhs->isIntegerType()) {
481 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000482 return rhs;
483 }
484 }
485 // Finally, we have two differing integer types.
486 // The rules for this case are in C99 6.3.1.8
487 int compare = Context.getIntegerTypeOrder(lhs, rhs);
488 bool lhsSigned = lhs->isSignedIntegerType(),
489 rhsSigned = rhs->isSignedIntegerType();
490 QualType destType;
491 if (lhsSigned == rhsSigned) {
492 // Same signedness; use the higher-ranked type
493 destType = compare >= 0 ? lhs : rhs;
494 } else if (compare != (lhsSigned ? 1 : -1)) {
495 // The unsigned type has greater than or equal rank to the
496 // signed type, so use the unsigned type
497 destType = lhsSigned ? rhs : lhs;
498 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
499 // The two types are different widths; if we are here, that
500 // means the signed type is larger than the unsigned type, so
501 // use the signed type.
502 destType = lhsSigned ? lhs : rhs;
503 } else {
504 // The signed type is higher-ranked than the unsigned type,
505 // but isn't actually any bigger (like unsigned int and long
506 // on most 32-bit systems). Use the unsigned type corresponding
507 // to the signed type.
508 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
509 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000510 return destType;
511}
512
513//===----------------------------------------------------------------------===//
514// Semantic Analysis for various Expression Types
515//===----------------------------------------------------------------------===//
516
517
Steve Narofff69936d2007-09-16 03:34:24 +0000518/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000519/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
520/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
521/// multiple tokens. However, the common case is that StringToks points to one
522/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000523///
524Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000525Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 assert(NumStringToks && "Must have at least one string!");
527
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000528 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000530 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000531
532 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
533 for (unsigned i = 0; i != NumStringToks; ++i)
534 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000535
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000536 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000537 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000538 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000539
540 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
541 if (getLangOptions().CPlusPlus)
542 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000543
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000544 // Get an array type for the string, according to C99 6.4.5. This includes
545 // the nul terminator character as well as the string length for pascal
546 // strings.
547 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000548 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000549 ArrayType::Normal, 0);
Chris Lattner726e1682009-02-18 05:49:11 +0000550
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattner2085fd62009-02-18 06:40:38 +0000552 return Owned(StringLiteral::Create(Context, Literal.GetString(),
553 Literal.GetStringLength(),
554 Literal.AnyWide, StrTy,
555 &StringTokLocs[0],
556 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000557}
558
Chris Lattner639e2d32008-10-20 05:16:36 +0000559/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
560/// CurBlock to VD should cause it to be snapshotted (as we do for auto
561/// variables defined outside the block) or false if this is not needed (e.g.
562/// for values inside the block or for globals).
563///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000564/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
565/// up-to-date.
566///
Chris Lattner639e2d32008-10-20 05:16:36 +0000567static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
568 ValueDecl *VD) {
569 // If the value is defined inside the block, we couldn't snapshot it even if
570 // we wanted to.
571 if (CurBlock->TheDecl == VD->getDeclContext())
572 return false;
573
574 // If this is an enum constant or function, it is constant, don't snapshot.
575 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
576 return false;
577
578 // If this is a reference to an extern, static, or global variable, no need to
579 // snapshot it.
580 // FIXME: What about 'const' variables in C++?
581 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000582 if (!Var->hasLocalStorage())
583 return false;
584
585 // Blocks that have these can't be constant.
586 CurBlock->hasBlockDeclRefExprs = true;
587
588 // If we have nested blocks, the decl may be declared in an outer block (in
589 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
590 // be defined outside all of the current blocks (in which case the blocks do
591 // all get the bit). Walk the nesting chain.
592 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
593 NextBlock = NextBlock->PrevBlockInfo) {
594 // If we found the defining block for the variable, don't mark the block as
595 // having a reference outside it.
596 if (NextBlock->TheDecl == VD->getDeclContext())
597 break;
598
599 // Otherwise, the DeclRef from the inner block causes the outer one to need
600 // a snapshot as well.
601 NextBlock->hasBlockDeclRefExprs = true;
602 }
Chris Lattner639e2d32008-10-20 05:16:36 +0000603
604 return true;
605}
606
607
608
Steve Naroff08d92e42007-09-15 18:49:24 +0000609/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000610/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000611/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000612/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000614Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
615 IdentifierInfo &II,
616 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000617 const CXXScopeSpec *SS,
618 bool isAddressOfOperand) {
619 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000620 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000621}
622
Douglas Gregor1a49af92009-01-06 05:10:23 +0000623/// BuildDeclRefExpr - Build either a DeclRefExpr or a
624/// QualifiedDeclRefExpr based on whether or not SS is a
625/// nested-name-specifier.
Sebastian Redlebc07d52009-02-03 20:19:35 +0000626DeclRefExpr *
627Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
628 bool TypeDependent, bool ValueDependent,
629 const CXXScopeSpec *SS) {
Douglas Gregorbad35182009-03-19 03:51:16 +0000630 if (SS && !SS->isEmpty()) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000631 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
632 ValueDependent, SS->getRange(),
Douglas Gregor35073692009-03-26 23:56:24 +0000633 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregorbad35182009-03-19 03:51:16 +0000634 } else
Steve Naroff6ece14c2009-01-21 00:14:39 +0000635 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000636}
637
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000638/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
639/// variable corresponding to the anonymous union or struct whose type
640/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000641static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
642 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000643 assert(Record->isAnonymousStructOrUnion() &&
644 "Record must be an anonymous struct or union!");
645
Mike Stump390b4cc2009-05-16 07:39:55 +0000646 // FIXME: Once Decls are directly linked together, this will be an O(1)
647 // operation rather than a slow walk through DeclContext's vector (which
648 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000649 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000650 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
651 DEnd = Ctx->decls_end(Context);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000652 D != DEnd; ++D) {
653 if (*D == Record) {
654 // The object for the anonymous struct/union directly
655 // follows its type in the list of declarations.
656 ++D;
657 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000658 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000659 return *D;
660 }
661 }
662
663 assert(false && "Missing object for anonymous record");
664 return 0;
665}
666
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000667/// \brief Given a field that represents a member of an anonymous
668/// struct/union, build the path from that field's context to the
669/// actual member.
670///
671/// Construct the sequence of field member references we'll have to
672/// perform to get to the field in the anonymous union/struct. The
673/// list of members is built from the field outward, so traverse it
674/// backwards to go from an object in the current context to the field
675/// we found.
676///
677/// \returns The variable from which the field access should begin,
678/// for an anonymous struct/union that is not a member of another
679/// class. Otherwise, returns NULL.
680VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
681 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000682 assert(Field->getDeclContext()->isRecord() &&
683 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
684 && "Field must be stored inside an anonymous struct or union");
685
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000686 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000687 VarDecl *BaseObject = 0;
688 DeclContext *Ctx = Field->getDeclContext();
689 do {
690 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000691 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000692 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000693 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000694 else {
695 BaseObject = cast<VarDecl>(AnonObject);
696 break;
697 }
698 Ctx = Ctx->getParent();
699 } while (Ctx->isRecord() &&
700 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000701
702 return BaseObject;
703}
704
705Sema::OwningExprResult
706Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
707 FieldDecl *Field,
708 Expr *BaseObjectExpr,
709 SourceLocation OpLoc) {
710 llvm::SmallVector<FieldDecl *, 4> AnonFields;
711 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
712 AnonFields);
713
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000714 // Build the expression that refers to the base object, from
715 // which we will build a sequence of member references to each
716 // of the anonymous union objects and, eventually, the field we
717 // found via name lookup.
718 bool BaseObjectIsPointer = false;
719 unsigned ExtraQuals = 0;
720 if (BaseObject) {
721 // BaseObject is an anonymous struct/union variable (and is,
722 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000723 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000724 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000725 SourceLocation());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000726 ExtraQuals
727 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
728 } else if (BaseObjectExpr) {
729 // The caller provided the base object expression. Determine
730 // whether its a pointer and whether it adds any qualifiers to the
731 // anonymous struct/union fields we're looking into.
732 QualType ObjectType = BaseObjectExpr->getType();
733 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
734 BaseObjectIsPointer = true;
735 ObjectType = ObjectPtr->getPointeeType();
736 }
737 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
738 } else {
739 // We've found a member of an anonymous struct/union that is
740 // inside a non-anonymous struct/union, so in a well-formed
741 // program our base object expression is "this".
742 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
743 if (!MD->isStatic()) {
744 QualType AnonFieldType
745 = Context.getTagDeclType(
746 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
747 QualType ThisType = Context.getTagDeclType(MD->getParent());
748 if ((Context.getCanonicalType(AnonFieldType)
749 == Context.getCanonicalType(ThisType)) ||
750 IsDerivedFrom(ThisType, AnonFieldType)) {
751 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000752 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000753 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000754 BaseObjectIsPointer = true;
755 }
756 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000757 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
758 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000759 }
760 ExtraQuals = MD->getTypeQualifiers();
761 }
762
763 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000764 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
765 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000766 }
767
768 // Build the implicit member references to the field of the
769 // anonymous struct/union.
770 Expr *Result = BaseObjectExpr;
771 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
772 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
773 FI != FIEnd; ++FI) {
774 QualType MemberType = (*FI)->getType();
775 if (!(*FI)->isMutable()) {
776 unsigned combinedQualifiers
777 = MemberType.getCVRQualifiers() | ExtraQuals;
778 MemberType = MemberType.getQualifiedType(combinedQualifiers);
779 }
Steve Naroff6ece14c2009-01-21 00:14:39 +0000780 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
781 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000782 BaseObjectIsPointer = false;
783 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000784 }
785
Sebastian Redlcd965b92009-01-18 18:53:16 +0000786 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000787}
788
Douglas Gregor10c42622008-11-18 15:03:34 +0000789/// ActOnDeclarationNameExpr - The parser has read some kind of name
790/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
791/// performs lookup on that name and returns an expression that refers
792/// to that name. This routine isn't directly called from the parser,
793/// because the parser doesn't know about DeclarationName. Rather,
794/// this routine is called by ActOnIdentifierExpr,
795/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
796/// which form the DeclarationName from the corresponding syntactic
797/// forms.
798///
799/// HasTrailingLParen indicates whether this identifier is used in a
800/// function call context. LookupCtx is only used for a C++
801/// qualified-id (foo::bar) to indicate the class or namespace that
802/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000803///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000804/// isAddressOfOperand means that this expression is the direct operand
805/// of an address-of operator. This matters because this is the only
806/// situation where a qualified name referencing a non-static member may
807/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000808Sema::OwningExprResult
809Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
810 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000811 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000812 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000813 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000814 if (SS && SS->isInvalid())
815 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000816
817 // C++ [temp.dep.expr]p3:
818 // An id-expression is type-dependent if it contains:
819 // -- a nested-name-specifier that contains a class-name that
820 // names a dependent type.
Douglas Gregor00c44862009-05-29 14:49:33 +0000821 // FIXME: Member of the current instantiation.
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000822 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000823 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
824 Loc, SS->getRange(),
Douglas Gregor35073692009-03-26 23:56:24 +0000825 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000826 }
827
Douglas Gregor3e41d602009-02-13 23:20:09 +0000828 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
829 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000830
Sebastian Redlcd965b92009-01-18 18:53:16 +0000831 if (Lookup.isAmbiguous()) {
832 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
833 SS && SS->isSet() ? SS->getRange()
834 : SourceRange());
835 return ExprError();
Chris Lattner5cb10d32009-04-24 22:30:50 +0000836 }
837
838 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000839
Chris Lattner8a934232008-03-31 00:36:02 +0000840 // If this reference is in an Objective-C method, then ivar lookup happens as
841 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000842 IdentifierInfo *II = Name.getAsIdentifierInfo();
843 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000844 // There are two cases to handle here. 1) scoped lookup could have failed,
845 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000846 // found a decl, but that decl is outside the current instance method (i.e.
847 // a global variable). In these two cases, we do a lookup for an ivar with
848 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000849 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000850 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000851 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000852 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
853 ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000854 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000855 if (DiagnoseUseOfDecl(IV, Loc))
856 return ExprError();
Chris Lattner5cb10d32009-04-24 22:30:50 +0000857
858 // If we're referencing an invalid decl, just return this as a silent
859 // error node. The error diagnostic was already emitted on the decl.
860 if (IV->isInvalidDecl())
861 return ExprError();
862
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000863 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
864 // If a class method attemps to use a free standing ivar, this is
865 // an error.
866 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
867 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
868 << IV->getDeclName());
869 // If a class method uses a global variable, even if an ivar with
870 // same name exists, use the global.
871 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000872 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
873 ClassDeclared != IFace)
874 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump390b4cc2009-05-16 07:39:55 +0000875 // FIXME: This should use a new expr for a direct reference, don't
876 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000877 IdentifierInfo &II = Context.Idents.get("self");
878 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Daniel Dunbar525c9b72009-04-21 01:19:28 +0000879 return Owned(new (Context)
880 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssone9146f22009-05-01 19:49:17 +0000881 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000882 }
Chris Lattner8a934232008-03-31 00:36:02 +0000883 }
884 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000885 else if (getCurMethodDecl()->isInstanceMethod()) {
886 // We should warn if a local variable hides an ivar.
887 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000888 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000889 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
890 ClassDeclared)) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000891 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
892 IFace == ClassDeclared)
Chris Lattner5cb10d32009-04-24 22:30:50 +0000893 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000894 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000895 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000896 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000897 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000898 QualType T;
899
900 if (getCurMethodDecl()->isInstanceMethod())
901 T = Context.getPointerType(Context.getObjCInterfaceType(
902 getCurMethodDecl()->getClassInterface()));
903 else
904 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000905 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000906 }
Chris Lattner8a934232008-03-31 00:36:02 +0000907 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000908
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000909 // Determine whether this name might be a candidate for
910 // argument-dependent lookup.
911 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
912 HasTrailingLParen;
913
914 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000915 // We've seen something of the form
916 //
917 // identifier(
918 //
919 // and we did not find any entity by the name
920 // "identifier". However, this identifier is still subject to
921 // argument-dependent lookup, so keep track of the name.
922 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
923 Context.OverloadTy,
924 Loc));
925 }
926
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 if (D == 0) {
928 // Otherwise, this could be an implicitly declared function reference (legal
929 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000930 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000931 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000932 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 else {
934 // If this name wasn't predeclared and if this is not a function call,
935 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000936 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000937 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
938 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000939 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
940 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000941 return ExprError(Diag(Loc, diag::err_undeclared_use)
942 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000943 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000944 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 }
946 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000947
Sebastian Redlebc07d52009-02-03 20:19:35 +0000948 // If this is an expression of the form &Class::member, don't build an
949 // implicit member ref, because we want a pointer to the member in general,
950 // not any specific instance's member.
951 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000952 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000953 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000954 QualType DType;
955 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
956 DType = FD->getType().getNonReferenceType();
957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
958 DType = Method->getType();
959 } else if (isa<OverloadedFunctionDecl>(D)) {
960 DType = Context.OverloadTy;
961 }
962 // Could be an inner type. That's diagnosed below, so ignore it here.
963 if (!DType.isNull()) {
964 // The pointer is type- and value-dependent if it points into something
965 // dependent.
Douglas Gregor00c44862009-05-29 14:49:33 +0000966 bool Dependent = DC->isDependentContext();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000967 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000968 }
969 }
970 }
971
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000972 // We may have found a field within an anonymous union or struct
973 // (C++ [class.union]).
974 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
975 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
976 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000977
Douglas Gregor88a35142008-12-22 05:46:06 +0000978 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
979 if (!MD->isStatic()) {
980 // C++ [class.mfct.nonstatic]p2:
981 // [...] if name lookup (3.4.1) resolves the name in the
982 // id-expression to a nonstatic nontype member of class X or of
983 // a base class of X, the id-expression is transformed into a
984 // class member access expression (5.2.5) using (*this) (9.3.2)
985 // as the postfix-expression to the left of the '.' operator.
986 DeclContext *Ctx = 0;
987 QualType MemberType;
988 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
989 Ctx = FD->getDeclContext();
990 MemberType = FD->getType();
991
992 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
993 MemberType = RefType->getPointeeType();
994 else if (!FD->isMutable()) {
995 unsigned combinedQualifiers
996 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
997 MemberType = MemberType.getQualifiedType(combinedQualifiers);
998 }
999 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1000 if (!Method->isStatic()) {
1001 Ctx = Method->getParent();
1002 MemberType = Method->getType();
1003 }
1004 } else if (OverloadedFunctionDecl *Ovl
1005 = dyn_cast<OverloadedFunctionDecl>(D)) {
1006 for (OverloadedFunctionDecl::function_iterator
1007 Func = Ovl->function_begin(),
1008 FuncEnd = Ovl->function_end();
1009 Func != FuncEnd; ++Func) {
1010 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1011 if (!DMethod->isStatic()) {
1012 Ctx = Ovl->getDeclContext();
1013 MemberType = Context.OverloadTy;
1014 break;
1015 }
1016 }
1017 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001018
1019 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001020 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1021 QualType ThisType = Context.getTagDeclType(MD->getParent());
1022 if ((Context.getCanonicalType(CtxType)
1023 == Context.getCanonicalType(ThisType)) ||
1024 IsDerivedFrom(ThisType, CtxType)) {
1025 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001026 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00001027 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001028 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman72527132009-04-29 17:56:47 +00001029 Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +00001030 }
1031 }
1032 }
1033 }
1034
Douglas Gregor44b43212008-12-11 16:49:14 +00001035 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001036 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1037 if (MD->isStatic())
1038 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +00001039 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1040 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001041 }
1042
Douglas Gregor88a35142008-12-22 05:46:06 +00001043 // Any other ways we could have found the field in a well-formed
1044 // program would have been turned into implicit member expressions
1045 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001046 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1047 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001048 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001051 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001052 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001053 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001054 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001055 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001056
Steve Naroffdd972f22008-09-05 22:11:13 +00001057 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001058 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001059 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1060 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +00001061 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1062 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1063 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +00001064 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001065
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001066 // Check whether this declaration can be used. Note that we suppress
1067 // this check when we're going to perform argument-dependent lookup
1068 // on this function name, because this might not be the function
1069 // that overload resolution actually selects.
1070 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1071 return ExprError();
1072
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001073 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner553905d2009-02-16 17:19:12 +00001074 // Warn about constructs like:
1075 // if (void *X = foo()) { ... } else { X }.
1076 // In the else block, the pointer is always false.
Douglas Gregor00c44862009-05-29 14:49:33 +00001077
1078 // FIXME: In a template instantiation, we don't have scope
1079 // information to check this property.
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001080 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1081 Scope *CheckS = S;
1082 while (CheckS) {
1083 if (CheckS->isWithinElse() &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00001084 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001085 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001086 ExprError(Diag(Loc, diag::warn_value_always_false)
1087 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001088 else
Sebastian Redlcd965b92009-01-18 18:53:16 +00001089 ExprError(Diag(Loc, diag::warn_value_always_zero)
1090 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001091 break;
1092 }
1093
1094 // Move up one more control parent to check again.
1095 CheckS = CheckS->getControlParent();
1096 if (CheckS)
1097 CheckS = CheckS->getParent();
1098 }
1099 }
Douglas Gregor2224f842009-02-25 16:33:18 +00001100 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
1101 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1102 // C99 DR 316 says that, if a function type comes from a
1103 // function definition (without a prototype), that type is only
1104 // used for checking compatibility. Therefore, when referencing
1105 // the function, we pretend that we don't have the full function
1106 // type.
1107 QualType T = Func->getType();
1108 QualType NoProtoType = T;
Douglas Gregor72564e72009-02-26 23:50:07 +00001109 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1110 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor2224f842009-02-25 16:33:18 +00001111 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
1112 }
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001113 }
Steve Naroffdd972f22008-09-05 22:11:13 +00001114
1115 // Only create DeclRefExpr's for valid Decl's.
1116 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001117 return ExprError();
1118
Chris Lattner639e2d32008-10-20 05:16:36 +00001119 // If the identifier reference is inside a block, and it refers to a value
1120 // that is outside the block, create a BlockDeclRefExpr instead of a
1121 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1122 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001123 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001124 // We do not do this for things like enum constants, global variables, etc,
1125 // as they do not get snapshotted.
1126 //
1127 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Eli Friedman5fdeae12009-03-22 23:00:19 +00001128 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001129 // The BlocksAttr indicates the variable is bound by-reference.
1130 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001131 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001132
Steve Naroff090276f2008-10-10 01:28:17 +00001133 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman5fdeae12009-03-22 23:00:19 +00001134 ExprTy.addConst();
1135 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +00001136 }
1137 // If this reference is not in a block or if the referenced variable is
1138 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001139
Douglas Gregor898574e2008-12-05 23:32:09 +00001140 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001141 bool ValueDependent = false;
1142 if (getLangOptions().CPlusPlus) {
1143 // C++ [temp.dep.expr]p3:
1144 // An id-expression is type-dependent if it contains:
1145 // - an identifier that was declared with a dependent type,
1146 if (VD->getType()->isDependentType())
1147 TypeDependent = true;
1148 // - FIXME: a template-id that is dependent,
1149 // - a conversion-function-id that specifies a dependent type,
1150 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1151 Name.getCXXNameType()->isDependentType())
1152 TypeDependent = true;
1153 // - a nested-name-specifier that contains a class-name that
1154 // names a dependent type.
1155 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001156 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +00001157 DC; DC = DC->getParent()) {
1158 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001159 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001160 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1161 if (Context.getTypeDeclType(Record)->isDependentType()) {
1162 TypeDependent = true;
1163 break;
1164 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001165 }
1166 }
1167 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001168
Douglas Gregor83f96f62008-12-10 20:57:37 +00001169 // C++ [temp.dep.constexpr]p2:
1170 //
1171 // An identifier is value-dependent if it is:
1172 // - a name declared with a dependent type,
1173 if (TypeDependent)
1174 ValueDependent = true;
1175 // - the name of a non-type template parameter,
1176 else if (isa<NonTypeTemplateParmDecl>(VD))
1177 ValueDependent = true;
1178 // - a constant with integral or enumeration type and is
1179 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001180 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1181 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1182 Dcl->getInit()) {
1183 ValueDependent = Dcl->getInit()->isValueDependent();
1184 }
1185 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001186 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001187
Sebastian Redlcd965b92009-01-18 18:53:16 +00001188 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1189 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +00001190}
1191
Sebastian Redlcd965b92009-01-18 18:53:16 +00001192Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1193 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001194 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001195
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001197 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001198 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1199 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1200 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001202
Chris Lattnerfa28b302008-01-12 08:14:25 +00001203 // Pre-defined identifiers are of type char[x], where x is the length of the
1204 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +00001205 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +00001206 if (FunctionDecl *FD = getCurFunctionDecl())
1207 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001208 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1209 Length = MD->getSynthesizedMethodSize();
1210 else {
1211 Diag(Loc, diag::ext_predef_outside_function);
1212 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1213 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1214 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001215
1216
Chris Lattner8f978d52008-01-12 19:32:28 +00001217 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +00001218 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +00001219 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +00001220 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001221}
1222
Sebastian Redlcd965b92009-01-18 18:53:16 +00001223Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 llvm::SmallString<16> CharBuffer;
1225 CharBuffer.resize(Tok.getLength());
1226 const char *ThisTokBegin = &CharBuffer[0];
1227 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1230 Tok.getLocation(), PP);
1231 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001232 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001233
1234 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1235
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001236 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1237 Literal.isWide(),
1238 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001239}
1240
Sebastian Redlcd965b92009-01-18 18:53:16 +00001241Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1242 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1244 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001245 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001246 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001247 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001248 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 }
Ted Kremenek28396602009-01-13 23:19:12 +00001250
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001252 // Add padding so that NumericLiteralParser can overread by one character.
1253 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001255
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 // Get the spelling of the token, which eliminates trigraphs, etc.
1257 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001258
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1260 Tok.getLocation(), PP);
1261 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001262 return ExprError();
1263
Chris Lattner5d661452007-08-26 03:42:43 +00001264 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001265
Chris Lattner5d661452007-08-26 03:42:43 +00001266 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001267 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001268 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001269 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001270 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001271 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001272 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001273 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001274
1275 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1276
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001277 // isExact will be set by GetFloatValue().
1278 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001279 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1280 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001281
Chris Lattner5d661452007-08-26 03:42:43 +00001282 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001283 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001284 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001285 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001286
Neil Boothb9449512007-08-29 22:00:19 +00001287 // long long is a C99 feature.
1288 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001289 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001290 Diag(Tok.getLocation(), diag::ext_longlong);
1291
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001293 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001294
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 if (Literal.GetIntegerValue(ResultVal)) {
1296 // If this value didn't fit into uintmax_t, warn and force to ull.
1297 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001298 Ty = Context.UnsignedLongLongTy;
1299 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001300 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 } else {
1302 // If this value fits into a ULL, try to figure out what else it fits into
1303 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001304
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1306 // be an unsigned int.
1307 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1308
1309 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001310 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001311 if (!Literal.isLong && !Literal.isLongLong) {
1312 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001313 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001314
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 // Does it fit in a unsigned int?
1316 if (ResultVal.isIntN(IntSize)) {
1317 // Does it fit in a signed int?
1318 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001319 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001321 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001322 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001327 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001328 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001329
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 // Does it fit in a unsigned long?
1331 if (ResultVal.isIntN(LongSize)) {
1332 // Does it fit in a signed long?
1333 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001334 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001336 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001337 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001339 }
1340
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001342 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001343 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 // Does it fit in a unsigned long long?
1346 if (ResultVal.isIntN(LongLongSize)) {
1347 // Does it fit in a signed long long?
1348 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001349 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001351 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001352 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 }
1354 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // If we still couldn't decide a type, we probably have something that
1357 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001358 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001360 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001361 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001363
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001364 if (ResultVal.getBitWidth() != Width)
1365 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001367 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001369
Chris Lattner5d661452007-08-26 03:42:43 +00001370 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1371 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001372 Res = new (Context) ImaginaryLiteral(Res,
1373 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001374
1375 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001376}
1377
Sebastian Redlcd965b92009-01-18 18:53:16 +00001378Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1379 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001380 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001381 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001382 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001383}
1384
1385/// The UsualUnaryConversions() function is *not* called by this routine.
1386/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001387bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001388 SourceLocation OpLoc,
1389 const SourceRange &ExprRange,
1390 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001391 if (exprType->isDependentType())
1392 return false;
1393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001395 if (isa<FunctionType>(exprType)) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001396 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001397 if (isSizeof)
1398 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1399 return false;
1400 }
1401
Chris Lattner1efaa952009-04-24 00:30:45 +00001402 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001403 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001404 Diag(OpLoc, diag::ext_sizeof_void_type)
1405 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001406 return false;
1407 }
Chris Lattnerca790922009-04-21 19:55:16 +00001408
Chris Lattner1efaa952009-04-24 00:30:45 +00001409 if (RequireCompleteType(OpLoc, exprType,
1410 isSizeof ? diag::err_sizeof_incomplete_type :
1411 diag::err_alignof_incomplete_type,
1412 ExprRange))
1413 return true;
1414
1415 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001416 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001417 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001418 << exprType << isSizeof << ExprRange;
1419 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001420 }
1421
Chris Lattner1efaa952009-04-24 00:30:45 +00001422 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001423}
1424
Chris Lattner31e21e02009-01-24 20:17:12 +00001425bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1426 const SourceRange &ExprRange) {
1427 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001428
Chris Lattner31e21e02009-01-24 20:17:12 +00001429 // alignof decl is always ok.
1430 if (isa<DeclRefExpr>(E))
1431 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001432
1433 // Cannot know anything else if the expression is dependent.
1434 if (E->isTypeDependent())
1435 return false;
1436
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001437 if (E->getBitField()) {
1438 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1439 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001440 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001441
1442 // Alignment of a field access is always okay, so long as it isn't a
1443 // bit-field.
1444 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1445 if (dyn_cast<FieldDecl>(ME->getMemberDecl()))
1446 return false;
1447
Chris Lattner31e21e02009-01-24 20:17:12 +00001448 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1449}
1450
Douglas Gregorba498172009-03-13 21:01:28 +00001451/// \brief Build a sizeof or alignof expression given a type operand.
1452Action::OwningExprResult
1453Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1454 bool isSizeOf, SourceRange R) {
1455 if (T.isNull())
1456 return ExprError();
1457
1458 if (!T->isDependentType() &&
1459 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1460 return ExprError();
1461
1462 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1463 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1464 Context.getSizeType(), OpLoc,
1465 R.getEnd()));
1466}
1467
1468/// \brief Build a sizeof or alignof expression given an expression
1469/// operand.
1470Action::OwningExprResult
1471Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1472 bool isSizeOf, SourceRange R) {
1473 // Verify that the operand is valid.
1474 bool isInvalid = false;
1475 if (E->isTypeDependent()) {
1476 // Delay type-checking for type-dependent expressions.
1477 } else if (!isSizeOf) {
1478 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001479 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001480 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1481 isInvalid = true;
1482 } else {
1483 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1484 }
1485
1486 if (isInvalid)
1487 return ExprError();
1488
1489 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1490 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1491 Context.getSizeType(), OpLoc,
1492 R.getEnd()));
1493}
1494
Sebastian Redl05189992008-11-11 17:56:53 +00001495/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1496/// the same for @c alignof and @c __alignof
1497/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001498Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001499Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1500 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001502 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001503
Sebastian Redl05189992008-11-11 17:56:53 +00001504 if (isType) {
Douglas Gregorba498172009-03-13 21:01:28 +00001505 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1506 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1507 }
Sebastian Redl05189992008-11-11 17:56:53 +00001508
Douglas Gregorba498172009-03-13 21:01:28 +00001509 // Get the end location.
1510 Expr *ArgEx = (Expr *)TyOrEx;
1511 Action::OwningExprResult Result
1512 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1513
1514 if (Result.isInvalid())
1515 DeleteExpr(ArgEx);
1516
1517 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001518}
1519
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001520QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001521 if (V->isTypeDependent())
1522 return Context.DependentTy;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001523
Chris Lattnercc26ed72007-08-26 05:39:26 +00001524 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001525 if (const ComplexType *CT = V->getType()->getAsComplexType())
1526 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001527
1528 // Otherwise they pass through real integer and floating point types here.
1529 if (V->getType()->isArithmeticType())
1530 return V->getType();
1531
1532 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001533 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1534 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001535 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001536}
1537
1538
Reid Spencer5f016e22007-07-11 17:01:13 +00001539
Sebastian Redl0eb23302009-01-19 00:08:26 +00001540Action::OwningExprResult
1541Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1542 tok::TokenKind Kind, ExprArg Input) {
1543 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 UnaryOperator::Opcode Opc;
1546 switch (Kind) {
1547 default: assert(0 && "Unknown unary op!");
1548 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1549 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1550 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001551
Douglas Gregor74253732008-11-19 15:42:04 +00001552 if (getLangOptions().CPlusPlus &&
1553 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1554 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001555 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001556 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1557
1558 // C++ [over.inc]p1:
1559 //
1560 // [...] If the function is a member function with one
1561 // parameter (which shall be of type int) or a non-member
1562 // function with two parameters (the second of which shall be
1563 // of type int), it defines the postfix increment operator ++
1564 // for objects of that type. When the postfix increment is
1565 // called as a result of using the ++ operator, the int
1566 // argument will have value zero.
1567 Expr *Args[2] = {
1568 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001569 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1570 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001571 };
1572
1573 // Build the candidate set for overloading
1574 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001575 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001576
1577 // Perform overload resolution.
1578 OverloadCandidateSet::iterator Best;
1579 switch (BestViableFunction(CandidateSet, Best)) {
1580 case OR_Success: {
1581 // We found a built-in operator or an overloaded operator.
1582 FunctionDecl *FnDecl = Best->Function;
1583
1584 if (FnDecl) {
1585 // We matched an overloaded operator. Build a call to that
1586 // operator.
1587
1588 // Convert the arguments.
1589 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1590 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001591 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001592 } else {
1593 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001594 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001595 FnDecl->getParamDecl(0)->getType(),
1596 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001597 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001598 }
1599
1600 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001601 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001602 = FnDecl->getType()->getAsFunctionType()->getResultType();
1603 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001604
Douglas Gregor74253732008-11-19 15:42:04 +00001605 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001606 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001607 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001608 UsualUnaryConversions(FnExpr);
1609
Sebastian Redl0eb23302009-01-19 00:08:26 +00001610 Input.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001611 Args[0] = Arg;
Douglas Gregor063daf62009-03-13 18:40:31 +00001612 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1613 Args, 2, ResultTy,
1614 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001615 } else {
1616 // We matched a built-in operator. Convert the arguments, then
1617 // break out so that we will build the appropriate built-in
1618 // operator node.
1619 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1620 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001621 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001622
1623 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001624 }
Douglas Gregor74253732008-11-19 15:42:04 +00001625 }
1626
1627 case OR_No_Viable_Function:
1628 // No viable function; fall through to handling this as a
1629 // built-in operator, which will produce an error message for us.
1630 break;
1631
1632 case OR_Ambiguous:
1633 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1634 << UnaryOperator::getOpcodeStr(Opc)
1635 << Arg->getSourceRange();
1636 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001637 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001638
1639 case OR_Deleted:
1640 Diag(OpLoc, diag::err_ovl_deleted_oper)
1641 << Best->Function->isDeleted()
1642 << UnaryOperator::getOpcodeStr(Opc)
1643 << Arg->getSourceRange();
1644 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1645 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001646 }
1647
1648 // Either we found no viable overloaded operator or we matched a
1649 // built-in operator. In either case, fall through to trying to
1650 // build a built-in operation.
1651 }
1652
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001653 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1654 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001656 return ExprError();
1657 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001658 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001659}
1660
Sebastian Redl0eb23302009-01-19 00:08:26 +00001661Action::OwningExprResult
1662Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1663 ExprArg Idx, SourceLocation RLoc) {
1664 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1665 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001666
Douglas Gregor337c6b92008-11-19 17:17:41 +00001667 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001668 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1669 Base.release();
1670 Idx.release();
1671 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1672 Context.DependentTy, RLoc));
1673 }
1674
1675 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001676 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001677 LHSExp->getType()->isEnumeralType() ||
1678 RHSExp->getType()->isRecordType() ||
1679 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001680 // Add the appropriate overloaded operators (C++ [over.match.oper])
1681 // to the candidate set.
1682 OverloadCandidateSet CandidateSet;
1683 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor063daf62009-03-13 18:40:31 +00001684 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1685 SourceRange(LLoc, RLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001686
Douglas Gregor337c6b92008-11-19 17:17:41 +00001687 // Perform overload resolution.
1688 OverloadCandidateSet::iterator Best;
1689 switch (BestViableFunction(CandidateSet, Best)) {
1690 case OR_Success: {
1691 // We found a built-in operator or an overloaded operator.
1692 FunctionDecl *FnDecl = Best->Function;
1693
1694 if (FnDecl) {
1695 // We matched an overloaded operator. Build a call to that
1696 // operator.
1697
1698 // Convert the arguments.
1699 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1700 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1701 PerformCopyInitialization(RHSExp,
1702 FnDecl->getParamDecl(0)->getType(),
1703 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001704 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001705 } else {
1706 // Convert the arguments.
1707 if (PerformCopyInitialization(LHSExp,
1708 FnDecl->getParamDecl(0)->getType(),
1709 "passing") ||
1710 PerformCopyInitialization(RHSExp,
1711 FnDecl->getParamDecl(1)->getType(),
1712 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001713 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001714 }
1715
1716 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001717 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001718 = FnDecl->getType()->getAsFunctionType()->getResultType();
1719 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001720
Douglas Gregor337c6b92008-11-19 17:17:41 +00001721 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001722 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1723 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001724 UsualUnaryConversions(FnExpr);
1725
Sebastian Redl0eb23302009-01-19 00:08:26 +00001726 Base.release();
1727 Idx.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001728 Args[0] = LHSExp;
1729 Args[1] = RHSExp;
Douglas Gregor063daf62009-03-13 18:40:31 +00001730 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1731 FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001732 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001733 } else {
1734 // We matched a built-in operator. Convert the arguments, then
1735 // break out so that we will build the appropriate built-in
1736 // operator node.
1737 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1738 "passing") ||
1739 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1740 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001741 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001742
1743 break;
1744 }
1745 }
1746
1747 case OR_No_Viable_Function:
1748 // No viable function; fall through to handling this as a
1749 // built-in operator, which will produce an error message for us.
1750 break;
1751
1752 case OR_Ambiguous:
1753 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1754 << "[]"
1755 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1756 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001757 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001758
1759 case OR_Deleted:
1760 Diag(LLoc, diag::err_ovl_deleted_oper)
1761 << Best->Function->isDeleted()
1762 << "[]"
1763 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1764 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1765 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001766 }
1767
1768 // Either we found no viable overloaded operator or we matched a
1769 // built-in operator. In either case, fall through to trying to
1770 // build a built-in operation.
1771 }
1772
Chris Lattner12d9ff62007-07-16 00:14:47 +00001773 // Perform default conversions.
1774 DefaultFunctionArrayConversion(LHSExp);
1775 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001776
Chris Lattner12d9ff62007-07-16 00:14:47 +00001777 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001780 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001781 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001783 Expr *BaseExpr, *IndexExpr;
1784 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001785 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1786 BaseExpr = LHSExp;
1787 IndexExpr = RHSExp;
1788 ResultType = Context.DependentTy;
1789 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001790 BaseExpr = LHSExp;
1791 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001792 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001793 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001794 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001795 BaseExpr = RHSExp;
1796 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001797 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001798 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1799 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001800 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001801
Chris Lattner12d9ff62007-07-16 00:14:47 +00001802 // FIXME: need to deal with const...
1803 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001804 } else if (LHSTy->isArrayType()) {
1805 // If we see an array that wasn't promoted by
1806 // DefaultFunctionArrayConversion, it must be an array that
1807 // wasn't promoted because of the C90 rule that doesn't
1808 // allow promoting non-lvalue arrays. Warn, then
1809 // force the promotion here.
1810 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1811 LHSExp->getSourceRange();
1812 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1813 LHSTy = LHSExp->getType();
1814
1815 BaseExpr = LHSExp;
1816 IndexExpr = RHSExp;
1817 ResultType = LHSTy->getAsPointerType()->getPointeeType();
1818 } else if (RHSTy->isArrayType()) {
1819 // Same as previous, except for 123[f().a] case
1820 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1821 RHSExp->getSourceRange();
1822 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1823 RHSTy = RHSExp->getType();
1824
1825 BaseExpr = RHSExp;
1826 IndexExpr = LHSExp;
1827 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001829 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1830 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001831 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 // C99 6.5.2.1p1
Sebastian Redl28507842009-02-26 14:39:58 +00001833 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001834 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1835 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001836
Douglas Gregore7450f52009-03-24 19:52:54 +00001837 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1838 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1839 // type. Note that Functions are not objects, and that (in C99 parlance)
1840 // incomplete types are not object types.
1841 if (ResultType->isFunctionType()) {
1842 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1843 << ResultType << BaseExpr->getSourceRange();
1844 return ExprError();
1845 }
Chris Lattner1efaa952009-04-24 00:30:45 +00001846
Douglas Gregore7450f52009-03-24 19:52:54 +00001847 if (!ResultType->isDependentType() &&
Chris Lattner1efaa952009-04-24 00:30:45 +00001848 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregore7450f52009-03-24 19:52:54 +00001849 BaseExpr->getSourceRange()))
1850 return ExprError();
Chris Lattner1efaa952009-04-24 00:30:45 +00001851
1852 // Diagnose bad cases where we step over interface counts.
1853 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1854 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1855 << ResultType << BaseExpr->getSourceRange();
1856 return ExprError();
1857 }
1858
Sebastian Redl0eb23302009-01-19 00:08:26 +00001859 Base.release();
1860 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001861 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001862 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001863}
1864
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001865QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001866CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001867 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001868 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001869
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001870 // The vector accessor can't exceed the number of elements.
1871 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001872
Mike Stumpeed9cac2009-02-19 03:04:26 +00001873 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001874 // special names that indicate a subset of exactly half the elements are
1875 // to be selected.
1876 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001877
Nate Begeman353417a2009-01-18 01:47:54 +00001878 // This flag determines whether or not CompName has an 's' char prefix,
1879 // indicating that it is a string of hex values to be used as vector indices.
1880 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001881
1882 // Check that we've found one of the special components, or that the component
1883 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001884 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001885 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1886 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001887 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001888 do
1889 compStr++;
1890 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001891 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001892 do
1893 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001894 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001895 }
Nate Begeman353417a2009-01-18 01:47:54 +00001896
Mike Stumpeed9cac2009-02-19 03:04:26 +00001897 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001898 // We didn't get to the end of the string. This means the component names
1899 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001900 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1901 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001902 return QualType();
1903 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001904
Nate Begeman353417a2009-01-18 01:47:54 +00001905 // Ensure no component accessor exceeds the width of the vector type it
1906 // operates on.
1907 if (!HalvingSwizzle) {
1908 compStr = CompName.getName();
1909
1910 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001911 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001912
1913 while (*compStr) {
1914 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1915 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1916 << baseType << SourceRange(CompLoc);
1917 return QualType();
1918 }
1919 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001920 }
Nate Begeman8a997642008-05-09 06:41:27 +00001921
Nate Begeman353417a2009-01-18 01:47:54 +00001922 // If this is a halving swizzle, verify that the base type has an even
1923 // number of elements.
1924 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001925 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001926 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001927 return QualType();
1928 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001929
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001930 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001931 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001932 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001933 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001934 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001935 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1936 : CompName.getLength();
1937 if (HexSwizzle)
1938 CompSize--;
1939
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001940 if (CompSize == 1)
1941 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001942
Nate Begeman213541a2008-04-18 23:10:10 +00001943 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001944 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001945 // diagostics look bad. We want extended vector types to appear built-in.
1946 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1947 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1948 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001949 }
1950 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001951}
1952
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001953static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1954 IdentifierInfo &Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001955 const Selector &Sel,
1956 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001957
Douglas Gregor6ab35242009-04-09 21:40:53 +00001958 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001959 return PD;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001960 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001961 return OMD;
1962
1963 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1964 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001965 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1966 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001967 return D;
1968 }
1969 return 0;
1970}
1971
1972static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1973 IdentifierInfo &Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001974 const Selector &Sel,
1975 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001976 // Check protocols on qualified interfaces.
1977 Decl *GDecl = 0;
1978 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1979 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001980 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001981 GDecl = PD;
1982 break;
1983 }
1984 // Also must look for a getter name which uses property syntax.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001985 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001986 GDecl = OMD;
1987 break;
1988 }
1989 }
1990 if (!GDecl) {
1991 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1992 E = QIdTy->qual_end(); I != E; ++I) {
1993 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001994 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001995 if (GDecl)
1996 return GDecl;
1997 }
1998 }
1999 return GDecl;
2000}
Chris Lattner76a642f2009-02-15 22:43:40 +00002001
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002002/// FindMethodInNestedImplementations - Look up a method in current and
2003/// all base class implementations.
2004///
2005ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2006 const ObjCInterfaceDecl *IFace,
2007 const Selector &Sel) {
2008 ObjCMethodDecl *Method = 0;
Douglas Gregor8fc463a2009-04-24 00:11:27 +00002009 if (ObjCImplementationDecl *ImpDecl
2010 = LookupObjCImplementation(IFace->getIdentifier()))
Douglas Gregor653f1b12009-04-23 01:02:12 +00002011 Method = ImpDecl->getInstanceMethod(Context, Sel);
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002012
2013 if (!Method && IFace->getSuperClass())
2014 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2015 return Method;
2016}
2017
Sebastian Redl0eb23302009-01-19 00:08:26 +00002018Action::OwningExprResult
2019Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2020 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00002021 IdentifierInfo &Member,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002022 DeclPtrTy ObjCImpDecl) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002023 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002024 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00002025
2026 // Perform default conversions.
2027 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002028
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002029 QualType BaseType = BaseExpr->getType();
2030 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002031
Chris Lattner68a057b2008-07-21 04:36:39 +00002032 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2033 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 if (OpKind == tok::arrow) {
Anders Carlssonffce2df2009-05-15 23:10:19 +00002035 if (BaseType->isDependentType())
Douglas Gregor1c0ca592009-05-22 21:13:27 +00002036 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2037 BaseExpr, true,
2038 OpLoc,
2039 DeclarationName(&Member),
2040 MemberLoc));
Anders Carlssonffce2df2009-05-15 23:10:19 +00002041 else if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002042 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00002043 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002044 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
2045 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002046 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002047 return ExprError(Diag(MemberLoc,
2048 diag::err_typecheck_member_reference_arrow)
2049 << BaseType << BaseExpr->getSourceRange());
Anders Carlssonffce2df2009-05-15 23:10:19 +00002050 } else {
Anders Carlsson4ef27702009-05-16 20:31:20 +00002051 if (BaseType->isDependentType()) {
2052 // Require that the base type isn't a pointer type
2053 // (so we'll report an error for)
2054 // T* t;
2055 // t.f;
2056 //
2057 // In Obj-C++, however, the above expression is valid, since it could be
2058 // accessing the 'f' property if T is an Obj-C interface. The extra check
2059 // allows this, while still reporting an error if T is a struct pointer.
2060 const PointerType *PT = BaseType->getAsPointerType();
2061
2062 if (!PT || (getLangOptions().ObjC1 &&
2063 !PT->getPointeeType()->isRecordType()))
Douglas Gregor1c0ca592009-05-22 21:13:27 +00002064 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2065 BaseExpr, false,
2066 OpLoc,
2067 DeclarationName(&Member),
2068 MemberLoc));
Anders Carlsson4ef27702009-05-16 20:31:20 +00002069 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002071
Chris Lattner68a057b2008-07-21 04:36:39 +00002072 // Handle field access to simple records. This also handles access to fields
2073 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00002074 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002075 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002076 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002077 diag::err_typecheck_incomplete_tag,
2078 BaseExpr->getSourceRange()))
2079 return ExprError();
2080
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002081 // The record definition is complete, now make sure the member is valid.
Mike Stump390b4cc2009-05-16 07:39:55 +00002082 // FIXME: Qualified name lookup for C++ is a bit more complicated than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002083 LookupResult Result
Mike Stumpeed9cac2009-02-19 03:04:26 +00002084 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002085 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002086
Douglas Gregor7176fff2009-01-15 00:26:24 +00002087 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002088 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2089 << &Member << BaseExpr->getSourceRange());
Chris Lattnera3d25242009-03-31 08:18:48 +00002090 if (Result.isAmbiguous()) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002091 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2092 MemberLoc, BaseExpr->getSourceRange());
2093 return ExprError();
Chris Lattnera3d25242009-03-31 08:18:48 +00002094 }
2095
2096 NamedDecl *MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00002097
Chris Lattner56cd21b2009-02-13 22:08:30 +00002098 // If the decl being referenced had an error, return an error for this
2099 // sub-expr without emitting another error, in order to avoid cascading
2100 // error cases.
2101 if (MemberDecl->isInvalidDecl())
2102 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002103
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002104 // Check the use of this field
2105 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2106 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002107
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002108 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002109 // We may have found a field within an anonymous union or struct
2110 // (C++ [class.union]).
2111 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002112 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002113 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002114
Douglas Gregor86f19402008-12-20 23:49:58 +00002115 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2116 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002117 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00002118 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
2119 MemberType = Ref->getPointeeType();
2120 else {
2121 unsigned combinedQualifiers =
2122 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002123 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00002124 combinedQualifiers &= ~QualType::Const;
2125 MemberType = MemberType.getQualifiedType(combinedQualifiers);
2126 }
Eli Friedman51019072008-02-06 22:48:16 +00002127
Steve Naroff6ece14c2009-01-21 00:14:39 +00002128 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2129 MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002130 }
2131
2132 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00002133 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattnera3d25242009-03-31 08:18:48 +00002134 Var, MemberLoc,
2135 Var->getType().getNonReferenceType()));
2136 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002137 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattnera3d25242009-03-31 08:18:48 +00002138 MemberFn, MemberLoc,
2139 MemberFn->getType()));
2140 if (OverloadedFunctionDecl *Ovl
2141 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00002142 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattnera3d25242009-03-31 08:18:48 +00002143 MemberLoc, Context.OverloadTy));
2144 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stumpeed9cac2009-02-19 03:04:26 +00002145 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2146 Enum, MemberLoc, Enum->getType()));
Chris Lattnera3d25242009-03-31 08:18:48 +00002147 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002148 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2149 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002150
Douglas Gregor86f19402008-12-20 23:49:58 +00002151 // We found a declaration kind that we didn't expect. This is a
2152 // generic error message that tells the user that she can't refer
2153 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002154 return ExprError(Diag(MemberLoc,
2155 diag::err_typecheck_member_reference_unknown)
2156 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002157 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002158
Chris Lattnera38e6b12008-07-21 04:59:05 +00002159 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2160 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00002161 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002162 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregor6ab35242009-04-09 21:40:53 +00002163 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
2164 &Member,
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002165 ClassDeclared)) {
Chris Lattner56cd21b2009-02-13 22:08:30 +00002166 // If the decl being referenced had an error, return an error for this
2167 // sub-expr without emitting another error, in order to avoid cascading
2168 // error cases.
2169 if (IV->isInvalidDecl())
2170 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002171
2172 // Check whether we can reference this field.
2173 if (DiagnoseUseOfDecl(IV, MemberLoc))
2174 return ExprError();
Steve Naroff8bfd1b82009-03-26 16:01:08 +00002175 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2176 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002177 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2178 if (ObjCMethodDecl *MD = getCurMethodDecl())
2179 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00002180 else if (ObjCImpDecl && getCurFunctionDecl()) {
2181 // Case of a c-function declared inside an objc implementation.
2182 // FIXME: For a c-style function nested inside an objc implementation
Mike Stump390b4cc2009-05-16 07:39:55 +00002183 // class, there is no implementation context available, so we pass
2184 // down the context as argument to this routine. Ideally, this context
2185 // need be passed down in the AST node and somehow calculated from the
2186 // AST for a function decl.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002187 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00002188 if (ObjCImplementationDecl *IMPD =
2189 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2190 ClassOfMethodDecl = IMPD->getClassInterface();
2191 else if (ObjCCategoryImplDecl* CatImplClass =
2192 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2193 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Naroffb06d8752009-03-04 18:34:24 +00002194 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002195
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00002196 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002197 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahaniana6e3ac52009-03-04 22:30:12 +00002198 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002199 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2200 }
2201 // @protected
2202 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2203 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2204 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002205
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002206 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff6ece14c2009-01-21 00:14:39 +00002207 MemberLoc, BaseExpr,
Daniel Dunbar525c9b72009-04-21 01:19:28 +00002208 OpKind == tok::arrow));
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002209 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002210 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2211 << IFTy->getDecl()->getDeclName() << &Member
2212 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002213 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002214
Chris Lattnera38e6b12008-07-21 04:59:05 +00002215 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2216 // pointer to a (potentially qualified) interface type.
2217 const PointerType *PTy;
2218 const ObjCInterfaceType *IFTy;
2219 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2220 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2221 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00002222
Daniel Dunbar2307d312008-09-03 01:05:41 +00002223 // Search for a declared property first.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002224 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
2225 &Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002226 // Check whether we can reference this property.
2227 if (DiagnoseUseOfDecl(PD, MemberLoc))
2228 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002229 QualType ResTy = PD->getType();
2230 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2231 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002232 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2233 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002234 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002235 MemberLoc, BaseExpr));
2236 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002237
Daniel Dunbar2307d312008-09-03 01:05:41 +00002238 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00002239 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2240 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregor6ab35242009-04-09 21:40:53 +00002241 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
2242 &Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002243 // Check whether we can reference this property.
2244 if (DiagnoseUseOfDecl(PD, MemberLoc))
2245 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002246
Steve Naroff6ece14c2009-01-21 00:14:39 +00002247 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002248 MemberLoc, BaseExpr));
2249 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002250
2251 // If that failed, look for an "implicit" property by seeing if the nullary
2252 // selector is implemented.
2253
2254 // FIXME: The logic for looking up nullary and unary selectors should be
2255 // shared with the code in ActOnInstanceMessage.
2256
2257 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002258 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002259
Daniel Dunbar2307d312008-09-03 01:05:41 +00002260 // If this reference is in an @implementation, check for 'private' methods.
2261 if (!Getter)
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002262 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002263
Steve Naroff7692ed62008-10-22 19:16:27 +00002264 // Look through local category implementations associated with the class.
2265 if (!Getter) {
2266 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2267 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregor653f1b12009-04-23 01:02:12 +00002268 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
Steve Naroff7692ed62008-10-22 19:16:27 +00002269 }
2270 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002271 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002272 // Check if we can reference this property.
2273 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2274 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002275 }
2276 // If we found a getter then this may be a valid dot-reference, we
2277 // will look for the matching setter, in case it is needed.
2278 Selector SetterSel =
2279 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2280 PP.getSelectorTable(), &Member);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002281 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002282 if (!Setter) {
2283 // If this reference is in an @implementation, also check for 'private'
2284 // methods.
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002285 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002286 }
2287 // Look through local category implementations associated with the class.
2288 if (!Setter) {
2289 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2290 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregor653f1b12009-04-23 01:02:12 +00002291 Setter = ObjCCategoryImpls[i]->getInstanceMethod(Context, SetterSel);
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00002292 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002293 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002294
Steve Naroff1ca66942009-03-11 13:48:17 +00002295 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2296 return ExprError();
2297
2298 if (Getter || Setter) {
2299 QualType PType;
2300
2301 if (Getter)
2302 PType = Getter->getResultType();
2303 else {
2304 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2305 E = Setter->param_end(); PI != E; ++PI)
2306 PType = (*PI)->getType();
2307 }
2308 // FIXME: we must check that the setter has property type.
2309 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2310 Setter, MemberLoc, BaseExpr));
2311 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002312 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2313 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002314 }
Steve Naroff18bc1642008-10-20 22:53:06 +00002315 // Handle properties on qualified "id" protocols.
2316 const ObjCQualifiedIdType *QIdTy;
2317 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2318 // Check protocols on qualified interfaces.
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002319 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002320 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002321 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002322 // Check the use of this declaration
2323 if (DiagnoseUseOfDecl(PD, MemberLoc))
2324 return ExprError();
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002325
Steve Naroff6ece14c2009-01-21 00:14:39 +00002326 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002327 MemberLoc, BaseExpr));
2328 }
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002329 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002330 // Check the use of this method.
2331 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2332 return ExprError();
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002333
Mike Stumpeed9cac2009-02-19 03:04:26 +00002334 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002335 OMD->getResultType(),
2336 OMD, OpLoc, MemberLoc,
2337 NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00002338 }
2339 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002340
2341 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2342 << &Member << BaseType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002343 }
Steve Naroffdd53eb52009-03-05 20:12:00 +00002344 // Handle properties on ObjC 'Class' types.
2345 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2346 // Also must look for a getter name which uses property syntax.
2347 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2348 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff335c6802009-03-11 20:12:18 +00002349 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2350 ObjCMethodDecl *Getter;
Steve Naroffdd53eb52009-03-05 20:12:00 +00002351 // FIXME: need to also look locally in the implementation.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002352 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffdd53eb52009-03-05 20:12:00 +00002353 // Check the use of this method.
Steve Naroff335c6802009-03-11 20:12:18 +00002354 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffdd53eb52009-03-05 20:12:00 +00002355 return ExprError();
Steve Naroffdd53eb52009-03-05 20:12:00 +00002356 }
Steve Naroff335c6802009-03-11 20:12:18 +00002357 // If we found a getter then this may be a valid dot-reference, we
2358 // will look for the matching setter, in case it is needed.
2359 Selector SetterSel =
2360 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2361 PP.getSelectorTable(), &Member);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002362 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff335c6802009-03-11 20:12:18 +00002363 if (!Setter) {
2364 // If this reference is in an @implementation, also check for 'private'
2365 // methods.
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002366 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff335c6802009-03-11 20:12:18 +00002367 }
2368 // Look through local category implementations associated with the class.
2369 if (!Setter) {
2370 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2371 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregor653f1b12009-04-23 01:02:12 +00002372 Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
Steve Naroff335c6802009-03-11 20:12:18 +00002373 }
2374 }
2375
2376 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2377 return ExprError();
2378
2379 if (Getter || Setter) {
2380 QualType PType;
2381
2382 if (Getter)
2383 PType = Getter->getResultType();
2384 else {
2385 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2386 E = Setter->param_end(); PI != E; ++PI)
2387 PType = (*PI)->getType();
2388 }
2389 // FIXME: we must check that the setter has property type.
2390 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2391 Setter, MemberLoc, BaseExpr));
2392 }
2393 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2394 << &Member << BaseType);
Steve Naroffdd53eb52009-03-05 20:12:00 +00002395 }
2396 }
2397
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002398 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002399 if (BaseType->isExtVectorType()) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002400 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2401 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002402 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002403 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002404 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002405 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002406
Douglas Gregor214f31a2009-03-27 06:00:30 +00002407 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2408 << BaseType << BaseExpr->getSourceRange();
2409
2410 // If the user is trying to apply -> or . to a function or function
2411 // pointer, it's probably because they forgot parentheses to call
2412 // the function. Suggest the addition of those parentheses.
2413 if (BaseType == Context.OverloadTy ||
2414 BaseType->isFunctionType() ||
2415 (BaseType->isPointerType() &&
2416 BaseType->getAsPointerType()->isFunctionType())) {
2417 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2418 Diag(Loc, diag::note_member_reference_needs_call)
2419 << CodeModificationHint::CreateInsertion(Loc, "()");
2420 }
2421
2422 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002423}
2424
Douglas Gregor88a35142008-12-22 05:46:06 +00002425/// ConvertArgumentsForCall - Converts the arguments specified in
2426/// Args/NumArgs to the parameter types of the function FDecl with
2427/// function prototype Proto. Call is the call expression itself, and
2428/// Fn is the function expression. For a C++ member function, this
2429/// routine does not attempt to convert the object argument. Returns
2430/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002431bool
2432Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002433 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002434 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002435 Expr **Args, unsigned NumArgs,
2436 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002437 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002438 // assignment, to the types of the corresponding parameter, ...
2439 unsigned NumArgsInProto = Proto->getNumArgs();
2440 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002441 bool Invalid = false;
2442
Douglas Gregor88a35142008-12-22 05:46:06 +00002443 // If too few arguments are available (and we don't have default
2444 // arguments for the remaining parameters), don't make the call.
2445 if (NumArgs < NumArgsInProto) {
2446 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2447 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2448 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2449 // Use default arguments for missing arguments
2450 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002451 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002452 }
2453
2454 // If too many are passed and not variadic, error on the extras and drop
2455 // them.
2456 if (NumArgs > NumArgsInProto) {
2457 if (!Proto->isVariadic()) {
2458 Diag(Args[NumArgsInProto]->getLocStart(),
2459 diag::err_typecheck_call_too_many_args)
2460 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2461 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2462 Args[NumArgs-1]->getLocEnd());
2463 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002464 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002465 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002466 }
2467 NumArgsToCheck = NumArgsInProto;
2468 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002469
Douglas Gregor88a35142008-12-22 05:46:06 +00002470 // Continue to check argument types (even if we have too few/many args).
2471 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2472 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002473
Douglas Gregor88a35142008-12-22 05:46:06 +00002474 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002475 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002476 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002477
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002478 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2479 ProtoArgType,
2480 diag::err_call_incomplete_argument,
2481 Arg->getSourceRange()))
2482 return true;
2483
Douglas Gregor61366e92008-12-24 00:01:03 +00002484 // Pass the argument.
2485 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2486 return true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002487 } else
Douglas Gregor61366e92008-12-24 00:01:03 +00002488 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00002489 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00002490 QualType ArgType = Arg->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002491
Douglas Gregor88a35142008-12-22 05:46:06 +00002492 Call->setArg(i, Arg);
2493 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002494
Douglas Gregor88a35142008-12-22 05:46:06 +00002495 // If this is a variadic call, handle args passed through "...".
2496 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002497 VariadicCallType CallType = VariadicFunction;
2498 if (Fn->getType()->isBlockPointerType())
2499 CallType = VariadicBlock; // Block
2500 else if (isa<MemberExpr>(Fn))
2501 CallType = VariadicMethod;
2502
Douglas Gregor88a35142008-12-22 05:46:06 +00002503 // Promote the arguments (C99 6.5.2.2p7).
2504 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2505 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002506 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002507 Call->setArg(i, Arg);
2508 }
2509 }
2510
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002511 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002512}
2513
Steve Narofff69936d2007-09-16 03:34:24 +00002514/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002515/// This provides the location of the left/right parens and a list of comma
2516/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002517Action::OwningExprResult
2518Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2519 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002520 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002521 unsigned NumArgs = args.size();
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002522 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002523 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002524 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002525 FunctionDecl *FDecl = NULL;
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002526 NamedDecl *NDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002527 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00002528
Douglas Gregor88a35142008-12-22 05:46:06 +00002529 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00002530 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002531 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002532 // FIXME: Will need to cache the results of name lookup (including ADL) in
2533 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002534 bool Dependent = false;
2535 if (Fn->isTypeDependent())
2536 Dependent = true;
2537 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2538 Dependent = true;
2539
2540 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002541 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002542 Context.DependentTy, RParenLoc));
2543
2544 // Determine whether this is a call to an object (C++ [over.call.object]).
2545 if (Fn->getType()->isRecordType())
2546 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2547 CommaLocs, RParenLoc));
2548
Douglas Gregorfa047642009-02-04 00:32:51 +00002549 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00002550 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2551 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2552 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002553 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2554 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00002555 }
2556
Douglas Gregorfa047642009-02-04 00:32:51 +00002557 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00002558 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00002559 Expr *FnExpr = Fn;
2560 bool ADL = true;
2561 while (true) {
2562 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2563 FnExpr = IcExpr->getSubExpr();
2564 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002565 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002566 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002567 ADL = false;
2568 FnExpr = PExpr->getSubExpr();
2569 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002570 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002571 == UnaryOperator::AddrOf) {
2572 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattner90e150d2009-02-14 07:22:29 +00002573 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2574 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2575 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2576 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002577 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002578 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2579 UnqualifiedName = DepName->getName();
2580 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002581 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002582 // Any kind of name that does not refer to a declaration (or
2583 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2584 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002585 break;
2586 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002587 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002588
Douglas Gregor17330012009-02-04 15:01:18 +00002589 OverloadedFunctionDecl *Ovl = 0;
2590 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00002591 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00002592 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002593 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00002594 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002595
Douglas Gregorf9201e02009-02-11 23:02:49 +00002596 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002597 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002598 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002599 ADL = false;
2600
Douglas Gregorf9201e02009-02-11 23:02:49 +00002601 // We don't perform ADL in C.
2602 if (!getLangOptions().CPlusPlus)
2603 ADL = false;
2604
Douglas Gregor17330012009-02-04 15:01:18 +00002605 if (Ovl || ADL) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002606 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2607 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00002608 NumArgs, CommaLocs, RParenLoc, ADL);
2609 if (!FDecl)
2610 return ExprError();
2611
2612 // Update Fn to refer to the actual function selected.
2613 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002614 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00002615 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregorab452ba2009-03-26 23:50:42 +00002616 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2617 QDRExpr->getLocation(),
2618 false, false,
2619 QDRExpr->getQualifierRange(),
2620 QDRExpr->getQualifier());
Douglas Gregorfa047642009-02-04 00:32:51 +00002621 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002622 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002623 Fn->getSourceRange().getBegin());
2624 Fn->Destroy(Context);
2625 Fn = NewFn;
2626 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002627 }
Chris Lattner04421082008-04-08 04:40:51 +00002628
2629 // Promote the function operand.
2630 UsualUnaryConversions(Fn);
2631
Chris Lattner925e60d2007-12-28 05:29:59 +00002632 // Make the call expr early, before semantic checks. This guarantees cleanup
2633 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002634 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2635 Args, NumArgs,
2636 Context.BoolTy,
2637 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002638
Steve Naroffdd972f22008-09-05 22:11:13 +00002639 const FunctionType *FuncT;
2640 if (!Fn->getType()->isBlockPointerType()) {
2641 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2642 // have type pointer to function".
2643 const PointerType *PT = Fn->getType()->getAsPointerType();
2644 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002645 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2646 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002647 FuncT = PT->getPointeeType()->getAsFunctionType();
2648 } else { // This is a block call.
2649 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2650 getAsFunctionType();
2651 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002652 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002653 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2654 << Fn->getType() << Fn->getSourceRange());
2655
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002656 // Check for a valid return type
2657 if (!FuncT->getResultType()->isVoidType() &&
2658 RequireCompleteType(Fn->getSourceRange().getBegin(),
2659 FuncT->getResultType(),
2660 diag::err_call_incomplete_return,
2661 TheCall->getSourceRange()))
2662 return ExprError();
2663
Chris Lattner925e60d2007-12-28 05:29:59 +00002664 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002665 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002666
Douglas Gregor72564e72009-02-26 23:50:07 +00002667 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002668 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002669 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002670 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002671 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002672 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002673
Douglas Gregor74734d52009-04-02 15:37:10 +00002674 if (FDecl) {
2675 // Check if we have too few/too many template arguments, based
2676 // on our knowledge of the function definition.
2677 const FunctionDecl *Def = 0;
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002678 if (FDecl->getBody(Context, Def) && NumArgs != Def->param_size()) {
2679 const FunctionProtoType *Proto =
2680 Def->getType()->getAsFunctionProtoType();
2681 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2682 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2683 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2684 }
2685 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002686 }
2687
Steve Naroffb291ab62007-08-28 23:30:39 +00002688 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002689 for (unsigned i = 0; i != NumArgs; i++) {
2690 Expr *Arg = Args[i];
2691 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002692 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2693 Arg->getType(),
2694 diag::err_call_incomplete_argument,
2695 Arg->getSourceRange()))
2696 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002697 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002698 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002700
Douglas Gregor88a35142008-12-22 05:46:06 +00002701 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2702 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002703 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2704 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002705
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002706 // Check for sentinels
2707 if (NDecl)
2708 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Chris Lattner59907c42007-08-10 20:18:51 +00002709 // Do special checking on direct calls to functions.
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002710 if (FDecl)
Eli Friedmand38617c2008-05-14 19:38:39 +00002711 return CheckFunctionCall(FDecl, TheCall.take());
Fariborz Jahanian725165f2009-05-18 21:05:18 +00002712 if (NDecl)
2713 return CheckBlockCall(NDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002714
Sebastian Redl0eb23302009-01-19 00:08:26 +00002715 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002716}
2717
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002718Action::OwningExprResult
2719Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2720 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002721 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002722 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002723 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002724 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002725 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002726
Eli Friedman6223c222008-05-20 05:22:08 +00002727 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002728 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002729 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2730 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00002731 } else if (!literalType->isDependentType() &&
2732 RequireCompleteType(LParenLoc, literalType,
2733 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002734 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002735 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002736
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002737 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002738 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002739 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002740
Chris Lattner371f2582008-12-04 23:50:19 +00002741 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002742 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002743 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002744 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002745 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002746 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002747 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002748 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002749}
2750
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002751Action::OwningExprResult
2752Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002753 SourceLocation RBraceLoc) {
2754 unsigned NumInit = initlist.size();
2755 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002756
Steve Naroff08d92e42007-09-15 18:49:24 +00002757 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002758 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002759
Mike Stumpeed9cac2009-02-19 03:04:26 +00002760 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002761 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002762 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002763 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002764}
2765
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002766/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002767bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002768 UsualUnaryConversions(castExpr);
2769
2770 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2771 // type needs to be scalar.
2772 if (castType->isVoidType()) {
2773 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002774 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2775 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002776 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002777 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2778 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2779 (castType->isStructureType() || castType->isUnionType())) {
2780 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00002781 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002782 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2783 << castType << castExpr->getSourceRange();
2784 } else if (castType->isUnionType()) {
2785 // GCC cast to union extension
2786 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2787 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00002788 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002789 Field != FieldEnd; ++Field) {
2790 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2791 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2792 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2793 << castExpr->getSourceRange();
2794 break;
2795 }
2796 }
2797 if (Field == FieldEnd)
2798 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2799 << castExpr->getType() << castExpr->getSourceRange();
2800 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002801 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002802 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002803 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002804 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002805 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002806 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002807 return Diag(castExpr->getLocStart(),
2808 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002809 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002810 } else if (castExpr->getType()->isVectorType()) {
2811 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2812 return true;
2813 } else if (castType->isVectorType()) {
2814 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2815 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002816 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00002817 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman41826bb2009-05-01 02:23:58 +00002818 } else if (!castType->isArithmeticType()) {
2819 QualType castExprType = castExpr->getType();
2820 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2821 return Diag(castExpr->getLocStart(),
2822 diag::err_cast_pointer_from_non_pointer_int)
2823 << castExprType << castExpr->getSourceRange();
2824 } else if (!castExpr->getType()->isArithmeticType()) {
2825 if (!castType->isIntegralType() && castType->isArithmeticType())
2826 return Diag(castExpr->getLocStart(),
2827 diag::err_cast_pointer_to_non_pointer_int)
2828 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002829 }
Fariborz Jahanianb5ff6bf2009-05-22 21:42:52 +00002830 if (isa<ObjCSelectorExpr>(castExpr))
2831 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002832 return false;
2833}
2834
Chris Lattnerfe23e212007-12-20 00:44:32 +00002835bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002836 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00002837
Anders Carlssona64db8f2007-11-27 05:51:55 +00002838 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002839 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002840 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00002841 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00002842 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002843 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002844 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002845 } else
2846 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002847 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002848 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002849
Anders Carlssona64db8f2007-11-27 05:51:55 +00002850 return false;
2851}
2852
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002853Action::OwningExprResult
2854Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2855 SourceLocation RParenLoc, ExprArg Op) {
2856 assert((Ty != 0) && (Op.get() != 0) &&
2857 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002858
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002859 Expr *castExpr = Op.takeAs<Expr>();
Steve Naroff16beff82007-07-16 23:25:18 +00002860 QualType castType = QualType::getFromOpaquePtr(Ty);
2861
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002862 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002863 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002864 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002865 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002866}
2867
Sebastian Redl28507842009-02-26 14:39:58 +00002868/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2869/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00002870/// C99 6.5.15
2871QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2872 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002873 // C++ is sufficiently different to merit its own checker.
2874 if (getLangOptions().CPlusPlus)
2875 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
2876
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002877 UsualUnaryConversions(Cond);
2878 UsualUnaryConversions(LHS);
2879 UsualUnaryConversions(RHS);
2880 QualType CondTy = Cond->getType();
2881 QualType LHSTy = LHS->getType();
2882 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002883
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002885 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2886 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2887 << CondTy;
2888 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002889 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002890
Chris Lattner70d67a92008-01-06 22:42:25 +00002891 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002892
Chris Lattner70d67a92008-01-06 22:42:25 +00002893 // If both operands have arithmetic type, do the usual arithmetic conversions
2894 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002895 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2896 UsualArithmeticConversions(LHS, RHS);
2897 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00002898 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002899
Chris Lattner70d67a92008-01-06 22:42:25 +00002900 // If both operands are the same structure or union type, the result is that
2901 // type.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002902 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2903 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002904 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00002905 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00002906 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002907 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00002908 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002910
Chris Lattner70d67a92008-01-06 22:42:25 +00002911 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002912 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002913 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2914 if (!LHSTy->isVoidType())
2915 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2916 << RHS->getSourceRange();
2917 if (!RHSTy->isVoidType())
2918 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2919 << LHS->getSourceRange();
2920 ImpCastExprToType(LHS, Context.VoidTy);
2921 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00002922 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002923 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002924 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2925 // the type of the other operand."
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002926 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2927 Context.isObjCObjectPointerType(LHSTy)) &&
2928 RHS->isNullPointerConstant(Context)) {
2929 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2930 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002931 }
Chris Lattnerefdc39d2009-02-18 04:28:32 +00002932 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2933 Context.isObjCObjectPointerType(RHSTy)) &&
2934 LHS->isNullPointerConstant(Context)) {
2935 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2936 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00002937 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002938
Mike Stumpdd3e1662009-05-07 03:14:14 +00002939 const PointerType *LHSPT = LHSTy->getAsPointerType();
2940 const PointerType *RHSPT = RHSTy->getAsPointerType();
2941 const BlockPointerType *LHSBPT = LHSTy->getAsBlockPointerType();
2942 const BlockPointerType *RHSBPT = RHSTy->getAsBlockPointerType();
2943
Chris Lattnerbd57d362008-01-06 22:50:31 +00002944 // Handle the case where both operands are pointers before we handle null
2945 // pointer constants in case both operands are null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00002946 if ((LHSPT || LHSBPT) && (RHSPT || RHSBPT)) { // C99 6.5.15p3,6
2947 // get the "pointed to" types
Mike Stumpaf199f32009-05-07 18:43:07 +00002948 QualType lhptee = (LHSPT ? LHSPT->getPointeeType()
2949 : LHSBPT->getPointeeType());
2950 QualType rhptee = (RHSPT ? RHSPT->getPointeeType()
2951 : RHSBPT->getPointeeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002952
Mike Stumpdd3e1662009-05-07 03:14:14 +00002953 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2954 if (lhptee->isVoidType()
2955 && (RHSBPT || rhptee->isIncompleteOrObjectType())) {
2956 // Figure out necessary qualifiers (C99 6.5.15p6)
2957 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2958 QualType destType = Context.getPointerType(destPointee);
2959 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2960 ImpCastExprToType(RHS, destType); // promote to void*
2961 return destType;
2962 }
2963 if (rhptee->isVoidType()
2964 && (LHSBPT || lhptee->isIncompleteOrObjectType())) {
2965 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2966 QualType destType = Context.getPointerType(destPointee);
2967 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2968 ImpCastExprToType(RHS, destType); // promote to void*
2969 return destType;
2970 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002971
Mike Stumpdd3e1662009-05-07 03:14:14 +00002972 bool sameKind = (LHSPT && RHSPT) || (LHSBPT && RHSBPT);
2973 if (sameKind
2974 && Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2975 // Two identical pointer types are always compatible.
2976 return LHSTy;
2977 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002978
Mike Stumpdd3e1662009-05-07 03:14:14 +00002979 QualType compositeType = LHSTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002980
Mike Stumpdd3e1662009-05-07 03:14:14 +00002981 // If either type is an Objective-C object type then check
2982 // compatibility according to Objective-C.
2983 if (Context.isObjCObjectPointerType(LHSTy) ||
2984 Context.isObjCObjectPointerType(RHSTy)) {
2985 // If both operands are interfaces and either operand can be
2986 // assigned to the other, use that type as the composite
2987 // type. This allows
2988 // xxx ? (A*) a : (B*) b
2989 // where B is a subclass of A.
2990 //
2991 // Additionally, as for assignment, if either type is 'id'
2992 // allow silent coercion. Finally, if the types are
2993 // incompatible then make sure to use 'id' as the composite
2994 // type so the result is acceptable for sending messages to.
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002995
Mike Stumpdd3e1662009-05-07 03:14:14 +00002996 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2997 // It could return the composite type.
2998 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2999 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
3000 if (LHSIface && RHSIface &&
3001 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
3002 compositeType = LHSTy;
3003 } else if (LHSIface && RHSIface &&
3004 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
3005 compositeType = RHSTy;
3006 } else if (Context.isObjCIdStructType(lhptee) ||
3007 Context.isObjCIdStructType(rhptee)) {
3008 compositeType = Context.getObjCIdType();
3009 } else if (LHSBPT || RHSBPT) {
3010 if (!sameKind
Eli Friedman26784c12009-06-08 05:08:54 +00003011 || !Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3012 rhptee.getUnqualifiedType()))
Mike Stumpdd3e1662009-05-07 03:14:14 +00003013 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3014 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3015 return QualType();
3016 } else {
3017 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3018 << LHSTy << RHSTy
3019 << LHS->getSourceRange() << RHS->getSourceRange();
3020 QualType incompatTy = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003021 ImpCastExprToType(LHS, incompatTy);
3022 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00003023 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00003024 }
Mike Stumpdd3e1662009-05-07 03:14:14 +00003025 } else if (!sameKind
3026 || !Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3027 rhptee.getUnqualifiedType())) {
3028 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3029 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3030 // In this situation, we assume void* type. No especially good
3031 // reason, but this is what gcc does, and we do have to pick
3032 // to get a consistent AST.
3033 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3034 ImpCastExprToType(LHS, incompatTy);
3035 ImpCastExprToType(RHS, incompatTy);
3036 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 }
Mike Stumpdd3e1662009-05-07 03:14:14 +00003038 // The pointer types are compatible.
3039 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3040 // differently qualified versions of compatible types, the result type is
3041 // a pointer to an appropriately qualified version of the *composite*
3042 // type.
3043 // FIXME: Need to calculate the composite type.
3044 // FIXME: Need to add qualifiers
3045 ImpCastExprToType(LHS, compositeType);
3046 ImpCastExprToType(RHS, compositeType);
3047 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003049
Steve Naroff91588042009-04-08 17:05:15 +00003050 // GCC compatibility: soften pointer/integer mismatch.
3051 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3052 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3053 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3054 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3055 return RHSTy;
3056 }
3057 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3058 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3059 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3060 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3061 return LHSTy;
3062 }
3063
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003064 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
3065 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stumpeed9cac2009-02-19 03:04:26 +00003066 // id with statically typed objects).
3067 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003068 // GCC allows qualified id and any Objective-C type to devolve to
3069 // id. Currently localizing to here until clear this should be
3070 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003071 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00003072 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003073 Context.isObjCObjectPointerType(RHSTy)) ||
3074 (RHSTy->isObjCQualifiedIdType() &&
3075 Context.isObjCObjectPointerType(LHSTy))) {
Mike Stump390b4cc2009-05-16 07:39:55 +00003076 // FIXME: This is not the correct composite type. This only happens to
3077 // work because id can more or less be used anywhere, however this may
3078 // change the type of method sends.
3079
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003080 // FIXME: gcc adds some type-checking of the arguments and emits
3081 // (confusing) incompatible comparison warnings in some
3082 // cases. Investigate.
3083 QualType compositeType = Context.getObjCIdType();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003084 ImpCastExprToType(LHS, compositeType);
3085 ImpCastExprToType(RHS, compositeType);
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003086 return compositeType;
3087 }
3088 }
3089
Chris Lattner70d67a92008-01-06 22:42:25 +00003090 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003091 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3092 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003093 return QualType();
3094}
3095
Steve Narofff69936d2007-09-16 03:34:24 +00003096/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003097/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003098Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3099 SourceLocation ColonLoc,
3100 ExprArg Cond, ExprArg LHS,
3101 ExprArg RHS) {
3102 Expr *CondExpr = (Expr *) Cond.get();
3103 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003104
3105 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3106 // was the condition.
3107 bool isLHSNull = LHSExpr == 0;
3108 if (isLHSNull)
3109 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003110
3111 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003112 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003113 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003114 return ExprError();
3115
3116 Cond.release();
3117 LHS.release();
3118 RHS.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003119 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003120 isLHSNull ? 0 : LHSExpr,
3121 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003122}
3123
Reid Spencer5f016e22007-07-11 17:01:13 +00003124
3125// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003126// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003127// routine is it effectively iqnores the qualifiers on the top level pointee.
3128// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3129// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003130Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003131Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3132 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003133
Reid Spencer5f016e22007-07-11 17:01:13 +00003134 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00003135 lhptee = lhsType->getAsPointerType()->getPointeeType();
3136 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003137
Reid Spencer5f016e22007-07-11 17:01:13 +00003138 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003139 lhptee = Context.getCanonicalType(lhptee);
3140 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003141
Chris Lattner5cf216b2008-01-04 18:04:52 +00003142 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003143
3144 // C99 6.5.16.1p1: This following citation is common to constraints
3145 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3146 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003147 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003148 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003149 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003150
Mike Stumpeed9cac2009-02-19 03:04:26 +00003151 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3152 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003153 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003154 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003155 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003156 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003157
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003158 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003159 assert(rhptee->isFunctionType());
3160 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003161 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003162
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003163 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003164 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003165 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003166
3167 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003168 assert(lhptee->isFunctionType());
3169 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003170 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003171 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003172 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003173 lhptee = lhptee.getUnqualifiedType();
3174 rhptee = rhptee.getUnqualifiedType();
3175 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3176 // Check if the pointee types are compatible ignoring the sign.
3177 // We explicitly check for char so that we catch "char" vs
3178 // "unsigned char" on systems where "char" is unsigned.
3179 if (lhptee->isCharType()) {
3180 lhptee = Context.UnsignedCharTy;
3181 } else if (lhptee->isSignedIntegerType()) {
3182 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3183 }
3184 if (rhptee->isCharType()) {
3185 rhptee = Context.UnsignedCharTy;
3186 } else if (rhptee->isSignedIntegerType()) {
3187 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3188 }
3189 if (lhptee == rhptee) {
3190 // Types are compatible ignoring the sign. Qualifier incompatibility
3191 // takes priority over sign incompatibility because the sign
3192 // warning can be disabled.
3193 if (ConvTy != Compatible)
3194 return ConvTy;
3195 return IncompatiblePointerSign;
3196 }
3197 // General pointer incompatibility takes priority over qualifiers.
3198 return IncompatiblePointer;
3199 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003200 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003201}
3202
Steve Naroff1c7d0672008-09-04 15:10:53 +00003203/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3204/// block pointer types are compatible or whether a block and normal pointer
3205/// are compatible. It is more restrict than comparing two function pointer
3206// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003207Sema::AssignConvertType
3208Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003209 QualType rhsType) {
3210 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003211
Steve Naroff1c7d0672008-09-04 15:10:53 +00003212 // get the "pointed to" type (ignoring qualifiers at the top level)
3213 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003214 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3215
Steve Naroff1c7d0672008-09-04 15:10:53 +00003216 // make sure we operate on the canonical type
3217 lhptee = Context.getCanonicalType(lhptee);
3218 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003219
Steve Naroff1c7d0672008-09-04 15:10:53 +00003220 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003221
Steve Naroff1c7d0672008-09-04 15:10:53 +00003222 // For blocks we enforce that qualifiers are identical.
3223 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3224 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003225
Eli Friedman26784c12009-06-08 05:08:54 +00003226 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003227 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003228 return ConvTy;
3229}
3230
Mike Stumpeed9cac2009-02-19 03:04:26 +00003231/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3232/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003233/// pointers. Here are some objectionable examples that GCC considers warnings:
3234///
3235/// int a, *pint;
3236/// short *pshort;
3237/// struct foo *pfoo;
3238///
3239/// pint = pshort; // warning: assignment from incompatible pointer type
3240/// a = pint; // warning: assignment makes integer from pointer without a cast
3241/// pint = a; // warning: assignment makes pointer from integer without a cast
3242/// pint = pfoo; // warning: assignment from incompatible pointer type
3243///
3244/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003245/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003246///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003247Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003248Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003249 // Get canonical types. We're not formatting these types, just comparing
3250 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003251 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3252 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003253
3254 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003255 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003256
Douglas Gregor9d293df2008-10-28 00:22:11 +00003257 // If the left-hand side is a reference type, then we are in a
3258 // (rare!) case where we've allowed the use of references in C,
3259 // e.g., as a parameter type in a built-in function. In this case,
3260 // just make sure that the type referenced is compatible with the
3261 // right-hand side type. The caller is responsible for adjusting
3262 // lhsType so that the resulting expression does not have reference
3263 // type.
3264 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3265 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003266 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003267 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003268 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003269
Chris Lattnereca7be62008-04-07 05:30:13 +00003270 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3271 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003272 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00003273 // Relax integer conversions like we do for pointers below.
3274 if (rhsType->isIntegerType())
3275 return IntToPointer;
3276 if (lhsType->isIntegerType())
3277 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00003278 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003279 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00003280
Nate Begemanbe2341d2008-07-14 18:02:46 +00003281 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00003282 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00003283 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
3284 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00003285 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003286
Nate Begemanbe2341d2008-07-14 18:02:46 +00003287 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003288 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003289 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003290 if (getLangOptions().LaxVectorConversions &&
3291 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003292 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003293 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003294 }
3295 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003296 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003297
Chris Lattnere8b3e962008-01-04 23:32:24 +00003298 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003299 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003300
Chris Lattner78eca282008-04-07 06:49:41 +00003301 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003302 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003303 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003304
Chris Lattner78eca282008-04-07 06:49:41 +00003305 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003306 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003307
Steve Naroffb4406862008-09-29 18:10:17 +00003308 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003309 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003310 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003311
3312 // Treat block pointers as objects.
3313 if (getLangOptions().ObjC1 &&
3314 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3315 return Compatible;
3316 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003317 return Incompatible;
3318 }
3319
3320 if (isa<BlockPointerType>(lhsType)) {
3321 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003322 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003323
Steve Naroffb4406862008-09-29 18:10:17 +00003324 // Treat block pointers as objects.
3325 if (getLangOptions().ObjC1 &&
3326 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3327 return Compatible;
3328
Steve Naroff1c7d0672008-09-04 15:10:53 +00003329 if (rhsType->isBlockPointerType())
3330 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003331
Steve Naroff1c7d0672008-09-04 15:10:53 +00003332 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3333 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003334 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003335 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003336 return Incompatible;
3337 }
3338
Chris Lattner78eca282008-04-07 06:49:41 +00003339 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003340 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003341 if (lhsType == Context.BoolTy)
3342 return Compatible;
3343
3344 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003345 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003346
Mike Stumpeed9cac2009-02-19 03:04:26 +00003347 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003348 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003349
3350 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff1c7d0672008-09-04 15:10:53 +00003351 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003352 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003353 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003354 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003355
Chris Lattnerfc144e22008-01-04 23:18:45 +00003356 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003357 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003359 }
3360 return Incompatible;
3361}
3362
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003363/// \brief Constructs a transparent union from an expression that is
3364/// used to initialize the transparent union.
3365static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3366 QualType UnionType, FieldDecl *Field) {
3367 // Build an initializer list that designates the appropriate member
3368 // of the transparent union.
3369 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3370 &E, 1,
3371 SourceLocation());
3372 Initializer->setType(UnionType);
3373 Initializer->setInitializedFieldInUnion(Field);
3374
3375 // Build a compound literal constructing a value of the transparent
3376 // union type from this initializer list.
3377 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3378 false);
3379}
3380
3381Sema::AssignConvertType
3382Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3383 QualType FromType = rExpr->getType();
3384
3385 // If the ArgType is a Union type, we want to handle a potential
3386 // transparent_union GCC extension.
3387 const RecordType *UT = ArgType->getAsUnionType();
3388 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3389 return Incompatible;
3390
3391 // The field to initialize within the transparent union.
3392 RecordDecl *UD = UT->getDecl();
3393 FieldDecl *InitField = 0;
3394 // It's compatible if the expression matches any of the fields.
3395 for (RecordDecl::field_iterator it = UD->field_begin(Context),
3396 itend = UD->field_end(Context);
3397 it != itend; ++it) {
3398 if (it->getType()->isPointerType()) {
3399 // If the transparent union contains a pointer type, we allow:
3400 // 1) void pointer
3401 // 2) null pointer constant
3402 if (FromType->isPointerType())
3403 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3404 ImpCastExprToType(rExpr, it->getType());
3405 InitField = *it;
3406 break;
3407 }
3408
3409 if (rExpr->isNullPointerConstant(Context)) {
3410 ImpCastExprToType(rExpr, it->getType());
3411 InitField = *it;
3412 break;
3413 }
3414 }
3415
3416 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3417 == Compatible) {
3418 InitField = *it;
3419 break;
3420 }
3421 }
3422
3423 if (!InitField)
3424 return Incompatible;
3425
3426 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3427 return Compatible;
3428}
3429
Chris Lattner5cf216b2008-01-04 18:04:52 +00003430Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00003431Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00003432 if (getLangOptions().CPlusPlus) {
3433 if (!lhsType->isRecordType()) {
3434 // C++ 5.17p3: If the left operand is not of class type, the
3435 // expression is implicitly converted (C++ 4) to the
3436 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00003437 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3438 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00003439 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00003440 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00003441 }
3442
3443 // FIXME: Currently, we fall through and treat C++ classes like C
3444 // structures.
3445 }
3446
Steve Naroff529a4ad2007-11-27 17:58:44 +00003447 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3448 // a null pointer constant.
Steve Narofff7f52e72009-02-21 21:17:01 +00003449 if ((lhsType->isPointerType() ||
3450 lhsType->isObjCQualifiedIdType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00003451 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00003452 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003453 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00003454 return Compatible;
3455 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003456
Chris Lattner943140e2007-10-16 02:55:40 +00003457 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00003458 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00003459 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00003460 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00003461 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00003462 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00003463 if (!lhsType->isReferenceType())
3464 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00003465
Chris Lattner5cf216b2008-01-04 18:04:52 +00003466 Sema::AssignConvertType result =
3467 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003468
Steve Narofff1120de2007-08-24 22:33:52 +00003469 // C99 6.5.16.1p2: The value of the right operand is converted to the
3470 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003471 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3472 // so that we can use references in built-in functions even in C.
3473 // The getNonReferenceType() call makes sure that the resulting expression
3474 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003475 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00003476 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00003477 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00003478}
3479
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003480QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003481 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00003482 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003483 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00003484 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003485}
3486
Mike Stumpeed9cac2009-02-19 03:04:26 +00003487inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00003488 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003489 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003490 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003491 QualType lhsType =
3492 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3493 QualType rhsType =
3494 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003495
Nate Begemanbe2341d2008-07-14 18:02:46 +00003496 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003497 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00003498 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00003499
Nate Begemanbe2341d2008-07-14 18:02:46 +00003500 // Handle the case of a vector & extvector type of the same size and element
3501 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003502 if (getLangOptions().LaxVectorConversions) {
3503 // FIXME: Should we warn here?
3504 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003505 if (const VectorType *RV = rhsType->getAsVectorType())
3506 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003507 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003508 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003509 }
3510 }
3511 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003512
Nate Begemanbe2341d2008-07-14 18:02:46 +00003513 // If the lhs is an extended vector and the rhs is a scalar of the same type
3514 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00003515 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003516 QualType eltType = V->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003517
3518 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00003519 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3520 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003521 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00003522 return lhsType;
3523 }
3524 }
3525
Nate Begemanbe2341d2008-07-14 18:02:46 +00003526 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00003527 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00003528 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003529 QualType eltType = V->getElementType();
3530
Mike Stumpeed9cac2009-02-19 03:04:26 +00003531 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanbe2341d2008-07-14 18:02:46 +00003532 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3533 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003534 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00003535 return rhsType;
3536 }
3537 }
3538
Reid Spencer5f016e22007-07-11 17:01:13 +00003539 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003540 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00003541 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003542 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003543 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00003544}
3545
Reid Spencer5f016e22007-07-11 17:01:13 +00003546inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003547 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003548{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00003549 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003550 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003551
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003552 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003553
Steve Naroffa4332e22007-07-17 00:58:39 +00003554 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003555 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003556 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003557}
3558
3559inline QualType Sema::CheckRemainderOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003560 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003561{
Daniel Dunbar523aa602009-01-05 22:55:36 +00003562 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3563 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3564 return CheckVectorOperands(Loc, lex, rex);
3565 return InvalidOperands(Loc, lex, rex);
3566 }
Steve Naroff90045e82007-07-13 23:32:42 +00003567
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003568 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003569
Steve Naroffa4332e22007-07-17 00:58:39 +00003570 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003571 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003572 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003573}
3574
3575inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedmanab3a8522009-03-28 01:22:36 +00003576 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Reid Spencer5f016e22007-07-11 17:01:13 +00003577{
Eli Friedmanab3a8522009-03-28 01:22:36 +00003578 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3579 QualType compType = CheckVectorOperands(Loc, lex, rex);
3580 if (CompLHSTy) *CompLHSTy = compType;
3581 return compType;
3582 }
Steve Naroff49b45262007-07-13 16:58:59 +00003583
Eli Friedmanab3a8522009-03-28 01:22:36 +00003584 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00003585
Reid Spencer5f016e22007-07-11 17:01:13 +00003586 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00003587 if (lex->getType()->isArithmeticType() &&
3588 rex->getType()->isArithmeticType()) {
3589 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003590 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00003591 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003592
Eli Friedmand72d16e2008-05-18 18:08:51 +00003593 // Put any potential pointer into PExp
3594 Expr* PExp = lex, *IExp = rex;
3595 if (IExp->getType()->isPointerType())
3596 std::swap(PExp, IExp);
3597
Chris Lattnerb5f15622009-04-24 23:50:08 +00003598 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00003599 if (IExp->getType()->isIntegerType()) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00003600 QualType PointeeTy = PTy->getPointeeType();
3601 // Check for arithmetic on pointers to incomplete types.
3602 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00003603 if (getLangOptions().CPlusPlus) {
3604 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003605 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003606 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00003607 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003608
3609 // GNU extension: arithmetic on pointer to void
3610 Diag(Loc, diag::ext_gnu_void_ptr)
3611 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00003612 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00003613 if (getLangOptions().CPlusPlus) {
3614 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3615 << lex->getType() << lex->getSourceRange();
3616 return QualType();
3617 }
3618
3619 // GNU extension: arithmetic on pointer to function
3620 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3621 << lex->getType() << lex->getSourceRange();
3622 } else if (!PTy->isDependentType() &&
Chris Lattnerb5f15622009-04-24 23:50:08 +00003623 RequireCompleteType(Loc, PointeeTy,
Douglas Gregore7450f52009-03-24 19:52:54 +00003624 diag::err_typecheck_arithmetic_incomplete_type,
Chris Lattnerb5f15622009-04-24 23:50:08 +00003625 PExp->getSourceRange(), SourceRange(),
3626 PExp->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003627 return QualType();
3628
Chris Lattnerb5f15622009-04-24 23:50:08 +00003629 // Diagnose bad cases where we step over interface counts.
3630 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3631 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3632 << PointeeTy << PExp->getSourceRange();
3633 return QualType();
3634 }
3635
Eli Friedmanab3a8522009-03-28 01:22:36 +00003636 if (CompLHSTy) {
3637 QualType LHSTy = lex->getType();
3638 if (LHSTy->isPromotableIntegerType())
3639 LHSTy = Context.IntTy;
Douglas Gregor2d833e32009-05-02 00:36:19 +00003640 else {
3641 QualType T = isPromotableBitField(lex, Context);
3642 if (!T.isNull())
3643 LHSTy = T;
3644 }
3645
Eli Friedmanab3a8522009-03-28 01:22:36 +00003646 *CompLHSTy = LHSTy;
3647 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00003648 return PExp->getType();
3649 }
3650 }
3651
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003652 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003653}
3654
Chris Lattnereca7be62008-04-07 05:30:13 +00003655// C99 6.5.6
3656QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00003657 SourceLocation Loc, QualType* CompLHSTy) {
3658 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3659 QualType compType = CheckVectorOperands(Loc, lex, rex);
3660 if (CompLHSTy) *CompLHSTy = compType;
3661 return compType;
3662 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003663
Eli Friedmanab3a8522009-03-28 01:22:36 +00003664 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003665
Chris Lattner6e4ab612007-12-09 21:53:25 +00003666 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003667
Chris Lattner6e4ab612007-12-09 21:53:25 +00003668 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00003669 if (lex->getType()->isArithmeticType()
3670 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00003671 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003672 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00003673 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003674
Chris Lattner6e4ab612007-12-09 21:53:25 +00003675 // Either ptr - int or ptr - ptr.
3676 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00003677 QualType lpointee = LHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003678
Douglas Gregore7450f52009-03-24 19:52:54 +00003679 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00003680
Douglas Gregore7450f52009-03-24 19:52:54 +00003681 bool ComplainAboutVoid = false;
3682 Expr *ComplainAboutFunc = 0;
3683 if (lpointee->isVoidType()) {
3684 if (getLangOptions().CPlusPlus) {
3685 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3686 << lex->getSourceRange() << rex->getSourceRange();
3687 return QualType();
3688 }
3689
3690 // GNU C extension: arithmetic on pointer to void
3691 ComplainAboutVoid = true;
3692 } else if (lpointee->isFunctionType()) {
3693 if (getLangOptions().CPlusPlus) {
3694 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003695 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003696 return QualType();
3697 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003698
3699 // GNU C extension: arithmetic on pointer to function
3700 ComplainAboutFunc = lex;
3701 } else if (!lpointee->isDependentType() &&
3702 RequireCompleteType(Loc, lpointee,
3703 diag::err_typecheck_sub_ptr_object,
3704 lex->getSourceRange(),
3705 SourceRange(),
3706 lex->getType()))
3707 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003708
Chris Lattnerb5f15622009-04-24 23:50:08 +00003709 // Diagnose bad cases where we step over interface counts.
3710 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3711 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3712 << lpointee << lex->getSourceRange();
3713 return QualType();
3714 }
3715
Chris Lattner6e4ab612007-12-09 21:53:25 +00003716 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00003717 if (rex->getType()->isIntegerType()) {
3718 if (ComplainAboutVoid)
3719 Diag(Loc, diag::ext_gnu_void_ptr)
3720 << lex->getSourceRange() << rex->getSourceRange();
3721 if (ComplainAboutFunc)
3722 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3723 << ComplainAboutFunc->getType()
3724 << ComplainAboutFunc->getSourceRange();
3725
Eli Friedmanab3a8522009-03-28 01:22:36 +00003726 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003727 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00003728 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003729
Chris Lattner6e4ab612007-12-09 21:53:25 +00003730 // Handle pointer-pointer subtractions.
3731 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00003732 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003733
Douglas Gregore7450f52009-03-24 19:52:54 +00003734 // RHS must be a completely-type object type.
3735 // Handle the GNU void* extension.
3736 if (rpointee->isVoidType()) {
3737 if (getLangOptions().CPlusPlus) {
3738 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3739 << lex->getSourceRange() << rex->getSourceRange();
3740 return QualType();
3741 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003742
Douglas Gregore7450f52009-03-24 19:52:54 +00003743 ComplainAboutVoid = true;
3744 } else if (rpointee->isFunctionType()) {
3745 if (getLangOptions().CPlusPlus) {
3746 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003747 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003748 return QualType();
3749 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003750
3751 // GNU extension: arithmetic on pointer to function
3752 if (!ComplainAboutFunc)
3753 ComplainAboutFunc = rex;
3754 } else if (!rpointee->isDependentType() &&
3755 RequireCompleteType(Loc, rpointee,
3756 diag::err_typecheck_sub_ptr_object,
3757 rex->getSourceRange(),
3758 SourceRange(),
3759 rex->getType()))
3760 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003761
Eli Friedman88d936b2009-05-16 13:54:38 +00003762 if (getLangOptions().CPlusPlus) {
3763 // Pointee types must be the same: C++ [expr.add]
3764 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
3765 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3766 << lex->getType() << rex->getType()
3767 << lex->getSourceRange() << rex->getSourceRange();
3768 return QualType();
3769 }
3770 } else {
3771 // Pointee types must be compatible C99 6.5.6p3
3772 if (!Context.typesAreCompatible(
3773 Context.getCanonicalType(lpointee).getUnqualifiedType(),
3774 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
3775 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3776 << lex->getType() << rex->getType()
3777 << lex->getSourceRange() << rex->getSourceRange();
3778 return QualType();
3779 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00003780 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003781
Douglas Gregore7450f52009-03-24 19:52:54 +00003782 if (ComplainAboutVoid)
3783 Diag(Loc, diag::ext_gnu_void_ptr)
3784 << lex->getSourceRange() << rex->getSourceRange();
3785 if (ComplainAboutFunc)
3786 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3787 << ComplainAboutFunc->getType()
3788 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00003789
3790 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00003791 return Context.getPointerDiffType();
3792 }
3793 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003794
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003795 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003796}
3797
Chris Lattnereca7be62008-04-07 05:30:13 +00003798// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003799QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00003800 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00003801 // C99 6.5.7p2: Each of the operands shall have integer type.
3802 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003803 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003804
Chris Lattnerca5eede2007-12-12 05:47:28 +00003805 // Shifts don't perform usual arithmetic conversions, they just do integer
3806 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00003807 QualType LHSTy;
3808 if (lex->getType()->isPromotableIntegerType())
3809 LHSTy = Context.IntTy;
Douglas Gregor2d833e32009-05-02 00:36:19 +00003810 else {
3811 LHSTy = isPromotableBitField(lex, Context);
3812 if (LHSTy.isNull())
3813 LHSTy = lex->getType();
3814 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00003815 if (!isCompAssign)
Eli Friedmanab3a8522009-03-28 01:22:36 +00003816 ImpCastExprToType(lex, LHSTy);
3817
Chris Lattnerca5eede2007-12-12 05:47:28 +00003818 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003819
Chris Lattnerca5eede2007-12-12 05:47:28 +00003820 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00003821 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003822}
3823
Douglas Gregor0c6db942009-05-04 06:07:12 +00003824// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003825QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00003826 unsigned OpaqueOpc, bool isRelational) {
3827 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3828
Nate Begemanbe2341d2008-07-14 18:02:46 +00003829 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003830 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003831
Chris Lattnera5937dd2007-08-26 01:18:55 +00003832 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00003833 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3834 UsualArithmeticConversions(lex, rex);
3835 else {
3836 UsualUnaryConversions(lex);
3837 UsualUnaryConversions(rex);
3838 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003839 QualType lType = lex->getType();
3840 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003841
Mike Stumpaf199f32009-05-07 18:43:07 +00003842 if (!lType->isFloatingType()
3843 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00003844 // For non-floating point types, check for self-comparisons of the form
3845 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3846 // often indicate logic errors in the program.
Ted Kremenek9ecede72009-03-20 19:57:37 +00003847 // NOTE: Don't warn about comparisons of enum constants. These can arise
3848 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00003849 Expr *LHSStripped = lex->IgnoreParens();
3850 Expr *RHSStripped = rex->IgnoreParens();
3851 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3852 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00003853 if (DRL->getDecl() == DRR->getDecl() &&
3854 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003855 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner55660a72009-03-08 19:39:53 +00003856
3857 if (isa<CastExpr>(LHSStripped))
3858 LHSStripped = LHSStripped->IgnoreParenCasts();
3859 if (isa<CastExpr>(RHSStripped))
3860 RHSStripped = RHSStripped->IgnoreParenCasts();
3861
3862 // Warn about comparisons against a string constant (unless the other
3863 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00003864 Expr *literalString = 0;
3865 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00003866 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregora86b8322009-04-06 18:45:53 +00003867 !RHSStripped->isNullPointerConstant(Context)) {
3868 literalString = lex;
3869 literalStringStripped = LHSStripped;
3870 }
Chris Lattner55660a72009-03-08 19:39:53 +00003871 else if ((isa<StringLiteral>(RHSStripped) ||
3872 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregora86b8322009-04-06 18:45:53 +00003873 !LHSStripped->isNullPointerConstant(Context)) {
3874 literalString = rex;
3875 literalStringStripped = RHSStripped;
3876 }
3877
3878 if (literalString) {
3879 std::string resultComparison;
3880 switch (Opc) {
3881 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3882 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3883 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3884 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3885 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3886 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3887 default: assert(false && "Invalid comparison operator");
3888 }
3889 Diag(Loc, diag::warn_stringcompare)
3890 << isa<ObjCEncodeExpr>(literalStringStripped)
3891 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00003892 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3893 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3894 "strcmp(")
3895 << CodeModificationHint::CreateInsertion(
3896 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00003897 resultComparison);
3898 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00003899 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003900
Douglas Gregor447b69e2008-11-19 03:25:36 +00003901 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00003902 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00003903
Chris Lattnera5937dd2007-08-26 01:18:55 +00003904 if (isRelational) {
3905 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003906 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003907 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003908 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00003909 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00003910 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003911 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00003912 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003913
Chris Lattnera5937dd2007-08-26 01:18:55 +00003914 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00003915 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00003916 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003917
Chris Lattnerd28f8152007-08-26 01:10:14 +00003918 bool LHSIsNull = lex->isNullPointerConstant(Context);
3919 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003920
Chris Lattnera5937dd2007-08-26 01:18:55 +00003921 // All of the following pointer related warnings are GCC extensions, except
3922 // when handling null pointer constants. One day, we can consider making them
3923 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00003924 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003925 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003926 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00003927 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00003928 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003929
Douglas Gregor0c6db942009-05-04 06:07:12 +00003930 // Simple check: if the pointee types are identical, we're done.
3931 if (LCanPointeeTy == RCanPointeeTy)
3932 return ResultTy;
3933
3934 if (getLangOptions().CPlusPlus) {
3935 // C++ [expr.rel]p2:
3936 // [...] Pointer conversions (4.10) and qualification
3937 // conversions (4.4) are performed on pointer operands (or on
3938 // a pointer operand and a null pointer constant) to bring
3939 // them to their composite pointer type. [...]
3940 //
3941 // C++ [expr.eq]p2 uses the same notion for (in)equality
3942 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00003943 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00003944 if (T.isNull()) {
3945 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
3946 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3947 return QualType();
3948 }
3949
3950 ImpCastExprToType(lex, T);
3951 ImpCastExprToType(rex, T);
3952 return ResultTy;
3953 }
3954
Steve Naroff66296cb2007-11-13 14:57:38 +00003955 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00003956 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3957 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00003958 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00003959 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003960 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003961 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003962 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00003963 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003964 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003965 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003966 // C++ allows comparison of pointers with null pointer constants.
3967 if (getLangOptions().CPlusPlus) {
3968 if (lType->isPointerType() && RHSIsNull) {
3969 ImpCastExprToType(rex, lType);
3970 return ResultTy;
3971 }
3972 if (rType->isPointerType() && LHSIsNull) {
3973 ImpCastExprToType(lex, rType);
3974 return ResultTy;
3975 }
3976 // And comparison of nullptr_t with itself.
3977 if (lType->isNullPtrType() && rType->isNullPtrType())
3978 return ResultTy;
3979 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003980 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003981 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003982 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3983 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003984
Steve Naroff1c7d0672008-09-04 15:10:53 +00003985 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00003986 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003987 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00003988 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00003989 }
3990 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003991 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003992 }
Steve Naroff59f53942008-09-28 01:11:11 +00003993 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003994 if (!isRelational
3995 && ((lType->isBlockPointerType() && rType->isPointerType())
3996 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00003997 if (!LHSIsNull && !RHSIsNull) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003998 if (!((rType->isPointerType() && rType->getAsPointerType()
3999 ->getPointeeType()->isVoidType())
4000 || (lType->isPointerType() && lType->getAsPointerType()
4001 ->getPointeeType()->isVoidType())))
4002 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4003 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004004 }
4005 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004006 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004007 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004008
Steve Naroff20373222008-06-03 14:04:54 +00004009 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004010 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00004011 const PointerType *LPT = lType->getAsPointerType();
4012 const PointerType *RPT = rType->getAsPointerType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004013 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004014 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004015 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004016 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004017
Steve Naroffa8069f12008-11-17 19:49:16 +00004018 if (!LPtrToVoid && !RPtrToVoid &&
4019 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004020 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004021 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004022 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004023 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00004024 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00004025 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004026 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004027 }
Steve Naroff20373222008-06-03 14:04:54 +00004028 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
4029 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004030 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00004031 } else {
4032 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004033 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004034 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00004035 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004036 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00004037 }
Steve Naroff20373222008-06-03 14:04:54 +00004038 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004039 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004040 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff20373222008-06-03 14:04:54 +00004041 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00004042 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004043 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004044 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00004045 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004046 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004047 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004048 if (lType->isIntegerType() &&
Steve Naroff20373222008-06-03 14:04:54 +00004049 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00004050 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004051 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004052 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00004053 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004054 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004055 }
Steve Naroff39218df2008-09-04 16:56:14 +00004056 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004057 if (!isRelational && RHSIsNull
4058 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff39218df2008-09-04 16:56:14 +00004059 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004060 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004061 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004062 if (!isRelational && LHSIsNull
4063 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff39218df2008-09-04 16:56:14 +00004064 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004065 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004066 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004067 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004068}
4069
Nate Begemanbe2341d2008-07-14 18:02:46 +00004070/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004071/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004072/// like a scalar comparison, a vector comparison produces a vector of integer
4073/// types.
4074QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004075 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004076 bool isRelational) {
4077 // Check to make sure we're operating on vectors of the same type and width,
4078 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004079 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004080 if (vType.isNull())
4081 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004082
Nate Begemanbe2341d2008-07-14 18:02:46 +00004083 QualType lType = lex->getType();
4084 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004085
Nate Begemanbe2341d2008-07-14 18:02:46 +00004086 // For non-floating point types, check for self-comparisons of the form
4087 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4088 // often indicate logic errors in the program.
4089 if (!lType->isFloatingType()) {
4090 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4091 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4092 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004093 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004094 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004095
Nate Begemanbe2341d2008-07-14 18:02:46 +00004096 // Check for comparisons of floating point operands using != and ==.
4097 if (!isRelational && lType->isFloatingType()) {
4098 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004099 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004100 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004101
Chris Lattnerd013aa12009-03-31 07:46:52 +00004102 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
4103 // just reject all vector comparisons for now.
4104 if (1) {
4105 Diag(Loc, diag::err_typecheck_vector_comparison)
4106 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4107 return QualType();
4108 }
4109
Nate Begemanbe2341d2008-07-14 18:02:46 +00004110 // Return the type for the comparison, which is the same as vector type for
4111 // integer vectors, or an integer type of identical size and number of
4112 // elements for floating point vectors.
4113 if (lType->isIntegerType())
4114 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004115
Nate Begemanbe2341d2008-07-14 18:02:46 +00004116 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004117 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004118 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004119 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004120 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004121 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4122
Mike Stumpeed9cac2009-02-19 03:04:26 +00004123 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004124 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004125 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4126}
4127
Reid Spencer5f016e22007-07-11 17:01:13 +00004128inline QualType Sema::CheckBitwiseOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00004129 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00004130{
Steve Naroff3e5e5562007-07-16 22:23:01 +00004131 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004132 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004133
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004134 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004135
Steve Naroffa4332e22007-07-17 00:58:39 +00004136 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004137 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004138 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004139}
4140
4141inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stumpeed9cac2009-02-19 03:04:26 +00004142 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00004143{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004144 UsualUnaryConversions(lex);
4145 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004146
Eli Friedman5773a6c2008-05-13 20:16:47 +00004147 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004148 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004149 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004150}
4151
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004152/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4153/// is a read-only property; return true if so. A readonly property expression
4154/// depends on various declarations and thus must be treated specially.
4155///
Mike Stumpeed9cac2009-02-19 03:04:26 +00004156static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004157{
4158 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4159 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4160 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4161 QualType BaseType = PropExpr->getBase()->getType();
4162 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004163 if (const ObjCInterfaceType *IFTy =
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004164 PTy->getPointeeType()->getAsObjCInterfaceType())
4165 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
4166 if (S.isPropertyReadonly(PDecl, IFace))
4167 return true;
4168 }
4169 }
4170 return false;
4171}
4172
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004173/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4174/// emit an error and return true. If so, return false.
4175static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004176 SourceLocation OrigLoc = Loc;
4177 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4178 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004179 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4180 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004181 if (IsLV == Expr::MLV_Valid)
4182 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004183
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004184 unsigned Diag = 0;
4185 bool NeedType = false;
4186 switch (IsLV) { // C99 6.5.16p2
4187 default: assert(0 && "Unknown result from isModifiableLvalue!");
4188 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004189 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004190 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4191 NeedType = true;
4192 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004193 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004194 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4195 NeedType = true;
4196 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004197 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004198 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4199 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004200 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004201 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4202 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004203 case Expr::MLV_IncompleteType:
4204 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004205 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004206 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4207 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004208 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004209 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4210 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004211 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004212 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4213 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004214 case Expr::MLV_ReadonlyProperty:
4215 Diag = diag::error_readonly_property_assignment;
4216 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004217 case Expr::MLV_NoSetterProperty:
4218 Diag = diag::error_nosetter_property_assignment;
4219 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004220 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004221
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004222 SourceRange Assign;
4223 if (Loc != OrigLoc)
4224 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004225 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004226 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004227 else
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004228 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004229 return true;
4230}
4231
4232
4233
4234// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004235QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4236 SourceLocation Loc,
4237 QualType CompoundType) {
4238 // Verify that LHS is a modifiable lvalue, and emit error if not.
4239 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004240 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004241
4242 QualType LHSType = LHS->getType();
4243 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004244
Chris Lattner5cf216b2008-01-04 18:04:52 +00004245 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004246 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00004247 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004248 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004249 // Special case of NSObject attributes on c-style pointer types.
4250 if (ConvTy == IncompatiblePointer &&
4251 ((Context.isObjCNSObjectType(LHSType) &&
4252 Context.isObjCObjectPointerType(RHSType)) ||
4253 (Context.isObjCNSObjectType(RHSType) &&
4254 Context.isObjCObjectPointerType(LHSType))))
4255 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004256
Chris Lattner2c156472008-08-21 18:04:13 +00004257 // If the RHS is a unary plus or minus, check to see if they = and + are
4258 // right next to each other. If so, the user may have typo'd "x =+ 4"
4259 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004260 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00004261 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4262 RHSCheck = ICE->getSubExpr();
4263 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4264 if ((UO->getOpcode() == UnaryOperator::Plus ||
4265 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004266 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00004267 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00004268 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4269 // And there is a space or other character before the subexpr of the
4270 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00004271 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4272 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004273 Diag(Loc, diag::warn_not_compound_assign)
4274 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4275 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00004276 }
Chris Lattner2c156472008-08-21 18:04:13 +00004277 }
4278 } else {
4279 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00004280 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00004281 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004282
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004283 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4284 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004285 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004286
Reid Spencer5f016e22007-07-11 17:01:13 +00004287 // C99 6.5.16p3: The type of an assignment expression is the type of the
4288 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00004289 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00004290 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4291 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004292 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00004293 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004294 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004295}
4296
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004297// C99 6.5.17
4298QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00004299 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004300 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004301
4302 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4303 // incomplete in C++).
4304
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004305 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004306}
4307
Steve Naroff49b45262007-07-13 16:58:59 +00004308/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4309/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004310QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4311 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004312 if (Op->isTypeDependent())
4313 return Context.DependentTy;
4314
Chris Lattner3528d352008-11-21 07:05:48 +00004315 QualType ResType = Op->getType();
4316 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004317
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004318 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4319 // Decrement of bool is not allowed.
4320 if (!isInc) {
4321 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4322 return QualType();
4323 }
4324 // Increment of bool sets it to true, but is deprecated.
4325 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4326 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00004327 // OK!
4328 } else if (const PointerType *PT = ResType->getAsPointerType()) {
4329 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00004330 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004331 if (getLangOptions().CPlusPlus) {
4332 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4333 << Op->getSourceRange();
4334 return QualType();
4335 }
4336
4337 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00004338 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004339 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004340 if (getLangOptions().CPlusPlus) {
4341 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4342 << Op->getType() << Op->getSourceRange();
4343 return QualType();
4344 }
4345
4346 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00004347 << ResType << Op->getSourceRange();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00004348 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4349 diag::err_typecheck_arithmetic_incomplete_type,
4350 Op->getSourceRange(), SourceRange(),
4351 ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004352 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00004353 } else if (ResType->isComplexType()) {
4354 // C99 does not support ++/-- on complex types, we allow as an extension.
4355 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004356 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00004357 } else {
4358 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00004359 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00004360 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004361 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004362 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00004363 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00004364 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00004365 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00004366 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004367}
4368
Anders Carlsson369dee42008-02-01 07:15:58 +00004369/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00004370/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004371/// where the declaration is needed for type checking. We only need to
4372/// handle cases when the expression references a function designator
4373/// or is an lvalue. Here are some examples:
4374/// - &(x) => x
4375/// - &*****f => f for f a function designator.
4376/// - &s.xx => s
4377/// - &s.zz[1].yy -> s, if zz is an array
4378/// - *(x + 1) -> x, if x is an array
4379/// - &"123"[2] -> 0
4380/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004381static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00004382 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004383 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00004384 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00004385 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00004386 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00004387 // If this is an arrow operator, the address is an offset from
4388 // the base's value, so the object the base refers to is
4389 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00004390 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00004391 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00004392 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00004393 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00004394 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00004395 // FIXME: This code shouldn't be necessary! We should catch the implicit
4396 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00004397 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4398 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4399 if (ICE->getSubExpr()->getType()->isArrayType())
4400 return getPrimaryDecl(ICE->getSubExpr());
4401 }
4402 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00004403 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004404 case Stmt::UnaryOperatorClass: {
4405 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004406
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004407 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004408 case UnaryOperator::Real:
4409 case UnaryOperator::Imag:
4410 case UnaryOperator::Extension:
4411 return getPrimaryDecl(UO->getSubExpr());
4412 default:
4413 return 0;
4414 }
4415 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004416 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00004417 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00004418 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00004419 // If the result of an implicit cast is an l-value, we care about
4420 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00004421 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00004422 default:
4423 return 0;
4424 }
4425}
4426
4427/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00004428/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00004429/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004430/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00004431/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004432/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00004433/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00004434QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00004435 // Make sure to ignore parentheses in subsequent checks
4436 op = op->IgnoreParens();
4437
Douglas Gregor9103bb22008-12-17 22:52:20 +00004438 if (op->isTypeDependent())
4439 return Context.DependentTy;
4440
Steve Naroff08f19672008-01-13 17:10:08 +00004441 if (getLangOptions().C99) {
4442 // Implement C99-only parts of addressof rules.
4443 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4444 if (uOp->getOpcode() == UnaryOperator::Deref)
4445 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4446 // (assuming the deref expression is valid).
4447 return uOp->getSubExpr()->getType();
4448 }
4449 // Technically, there should be a check for array subscript
4450 // expressions here, but the result of one is always an lvalue anyway.
4451 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004452 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00004453 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00004454
Eli Friedman441cf102009-05-16 23:27:50 +00004455 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4456 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00004457 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00004458 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00004459 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004460 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4461 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004462 return QualType();
4463 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004464 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00004465 // The operand cannot be a bit-field
4466 Diag(OpLoc, diag::err_typecheck_address_of)
4467 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00004468 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00004469 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4470 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00004471 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004472 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00004473 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00004474 return QualType();
4475 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00004476 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00004477 // with the register storage-class specifier.
4478 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4479 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004480 Diag(OpLoc, diag::err_typecheck_address_of)
4481 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004482 return QualType();
4483 }
Douglas Gregor29882052008-12-10 21:26:49 +00004484 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004485 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00004486 } else if (isa<FieldDecl>(dcl)) {
4487 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00004488 // Could be a pointer to member, though, if there is an explicit
4489 // scope qualifier for the class.
4490 if (isa<QualifiedDeclRefExpr>(op)) {
4491 DeclContext *Ctx = dcl->getDeclContext();
4492 if (Ctx && Ctx->isRecord())
4493 return Context.getMemberPointerType(op->getType(),
4494 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4495 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00004496 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00004497 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00004498 // As above.
Anders Carlsson196f7d02009-05-16 21:43:42 +00004499 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4500 return Context.getMemberPointerType(op->getType(),
4501 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4502 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00004503 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00004504 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00004505
Eli Friedman441cf102009-05-16 23:27:50 +00004506 if (lval == Expr::LV_IncompleteVoidType) {
4507 // Taking the address of a void variable is technically illegal, but we
4508 // allow it in cases which are otherwise valid.
4509 // Example: "extern void x; void* y = &x;".
4510 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4511 }
4512
Reid Spencer5f016e22007-07-11 17:01:13 +00004513 // If the operand has type "type", the result has type "pointer to type".
4514 return Context.getPointerType(op->getType());
4515}
4516
Chris Lattner22caddc2008-11-23 09:13:29 +00004517QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004518 if (Op->isTypeDependent())
4519 return Context.DependentTy;
4520
Chris Lattner22caddc2008-11-23 09:13:29 +00004521 UsualUnaryConversions(Op);
4522 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004523
Chris Lattner22caddc2008-11-23 09:13:29 +00004524 // Note that per both C89 and C99, this is always legal, even if ptype is an
4525 // incomplete type or void. It would be possible to warn about dereferencing
4526 // a void pointer, but it's completely well-defined, and such a warning is
4527 // unlikely to catch any mistakes.
4528 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00004529 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004530
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004531 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00004532 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004533 return QualType();
4534}
4535
4536static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4537 tok::TokenKind Kind) {
4538 BinaryOperator::Opcode Opc;
4539 switch (Kind) {
4540 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00004541 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4542 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004543 case tok::star: Opc = BinaryOperator::Mul; break;
4544 case tok::slash: Opc = BinaryOperator::Div; break;
4545 case tok::percent: Opc = BinaryOperator::Rem; break;
4546 case tok::plus: Opc = BinaryOperator::Add; break;
4547 case tok::minus: Opc = BinaryOperator::Sub; break;
4548 case tok::lessless: Opc = BinaryOperator::Shl; break;
4549 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4550 case tok::lessequal: Opc = BinaryOperator::LE; break;
4551 case tok::less: Opc = BinaryOperator::LT; break;
4552 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4553 case tok::greater: Opc = BinaryOperator::GT; break;
4554 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4555 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4556 case tok::amp: Opc = BinaryOperator::And; break;
4557 case tok::caret: Opc = BinaryOperator::Xor; break;
4558 case tok::pipe: Opc = BinaryOperator::Or; break;
4559 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4560 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4561 case tok::equal: Opc = BinaryOperator::Assign; break;
4562 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4563 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4564 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4565 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4566 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4567 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4568 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4569 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4570 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4571 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4572 case tok::comma: Opc = BinaryOperator::Comma; break;
4573 }
4574 return Opc;
4575}
4576
4577static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4578 tok::TokenKind Kind) {
4579 UnaryOperator::Opcode Opc;
4580 switch (Kind) {
4581 default: assert(0 && "Unknown unary op!");
4582 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4583 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4584 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4585 case tok::star: Opc = UnaryOperator::Deref; break;
4586 case tok::plus: Opc = UnaryOperator::Plus; break;
4587 case tok::minus: Opc = UnaryOperator::Minus; break;
4588 case tok::tilde: Opc = UnaryOperator::Not; break;
4589 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004590 case tok::kw___real: Opc = UnaryOperator::Real; break;
4591 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4592 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4593 }
4594 return Opc;
4595}
4596
Douglas Gregoreaebc752008-11-06 23:29:22 +00004597/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4598/// operator @p Opc at location @c TokLoc. This routine only supports
4599/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004600Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4601 unsigned Op,
4602 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004603 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00004604 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004605 // The following two variables are used for compound assignment operators
4606 QualType CompLHSTy; // Type of LHS after promotions for computation
4607 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00004608
4609 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00004610 case BinaryOperator::Assign:
4611 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4612 break;
Sebastian Redl22460502009-02-07 00:15:38 +00004613 case BinaryOperator::PtrMemD:
4614 case BinaryOperator::PtrMemI:
4615 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4616 Opc == BinaryOperator::PtrMemI);
4617 break;
4618 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00004619 case BinaryOperator::Div:
4620 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4621 break;
4622 case BinaryOperator::Rem:
4623 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4624 break;
4625 case BinaryOperator::Add:
4626 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4627 break;
4628 case BinaryOperator::Sub:
4629 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4630 break;
Sebastian Redl22460502009-02-07 00:15:38 +00004631 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00004632 case BinaryOperator::Shr:
4633 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4634 break;
4635 case BinaryOperator::LE:
4636 case BinaryOperator::LT:
4637 case BinaryOperator::GE:
4638 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00004639 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004640 break;
4641 case BinaryOperator::EQ:
4642 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00004643 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004644 break;
4645 case BinaryOperator::And:
4646 case BinaryOperator::Xor:
4647 case BinaryOperator::Or:
4648 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4649 break;
4650 case BinaryOperator::LAnd:
4651 case BinaryOperator::LOr:
4652 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4653 break;
4654 case BinaryOperator::MulAssign:
4655 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00004656 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4657 CompLHSTy = CompResultTy;
4658 if (!CompResultTy.isNull())
4659 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004660 break;
4661 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00004662 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4663 CompLHSTy = CompResultTy;
4664 if (!CompResultTy.isNull())
4665 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004666 break;
4667 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00004668 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4669 if (!CompResultTy.isNull())
4670 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004671 break;
4672 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00004673 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4674 if (!CompResultTy.isNull())
4675 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004676 break;
4677 case BinaryOperator::ShlAssign:
4678 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00004679 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4680 CompLHSTy = CompResultTy;
4681 if (!CompResultTy.isNull())
4682 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004683 break;
4684 case BinaryOperator::AndAssign:
4685 case BinaryOperator::XorAssign:
4686 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00004687 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4688 CompLHSTy = CompResultTy;
4689 if (!CompResultTy.isNull())
4690 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00004691 break;
4692 case BinaryOperator::Comma:
4693 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4694 break;
4695 }
4696 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004697 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004698 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00004699 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4700 else
4701 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004702 CompLHSTy, CompResultTy,
4703 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00004704}
4705
Reid Spencer5f016e22007-07-11 17:01:13 +00004706// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004707Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4708 tok::TokenKind Kind,
4709 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004710 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00004711 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00004712
Steve Narofff69936d2007-09-16 03:34:24 +00004713 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4714 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004715
Douglas Gregor063daf62009-03-13 18:40:31 +00004716 if (getLangOptions().CPlusPlus &&
4717 (lhs->getType()->isOverloadableType() ||
4718 rhs->getType()->isOverloadableType())) {
4719 // Find all of the overloaded operators visible from this
4720 // point. We perform both an operator-name lookup from the local
4721 // scope and an argument-dependent lookup based on the types of
4722 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004723 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00004724 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4725 if (OverOp != OO_None) {
4726 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4727 Functions);
4728 Expr *Args[2] = { lhs, rhs };
4729 DeclarationName OpName
4730 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4731 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004732 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004733
Douglas Gregor063daf62009-03-13 18:40:31 +00004734 // Build the (potentially-overloaded, potentially-dependent)
4735 // binary operation.
4736 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004737 }
4738
Douglas Gregoreaebc752008-11-06 23:29:22 +00004739 // Build a built-in binary operation.
4740 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00004741}
4742
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004743Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4744 unsigned OpcIn,
4745 ExprArg InputArg) {
4746 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00004747
Mike Stump390b4cc2009-05-16 07:39:55 +00004748 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004749 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00004750 QualType resultType;
4751 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004752 case UnaryOperator::PostInc:
4753 case UnaryOperator::PostDec:
4754 case UnaryOperator::OffsetOf:
4755 assert(false && "Invalid unary operator");
4756 break;
4757
Reid Spencer5f016e22007-07-11 17:01:13 +00004758 case UnaryOperator::PreInc:
4759 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004760 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4761 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004762 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004763 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00004764 resultType = CheckAddressOfOperand(Input, OpLoc);
4765 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004766 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00004767 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00004768 resultType = CheckIndirectionOperand(Input, OpLoc);
4769 break;
4770 case UnaryOperator::Plus:
4771 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004772 UsualUnaryConversions(Input);
4773 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004774 if (resultType->isDependentType())
4775 break;
Douglas Gregor74253732008-11-19 15:42:04 +00004776 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4777 break;
4778 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4779 resultType->isEnumeralType())
4780 break;
4781 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4782 Opc == UnaryOperator::Plus &&
4783 resultType->isPointerType())
4784 break;
4785
Sebastian Redl0eb23302009-01-19 00:08:26 +00004786 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4787 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004788 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004789 UsualUnaryConversions(Input);
4790 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004791 if (resultType->isDependentType())
4792 break;
Chris Lattner02a65142008-07-25 23:52:49 +00004793 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4794 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4795 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004796 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004797 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00004798 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004799 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4800 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004801 break;
4802 case UnaryOperator::LNot: // logical negation
4803 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004804 DefaultFunctionArrayConversion(Input);
4805 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00004806 if (resultType->isDependentType())
4807 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004808 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00004809 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4810 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004811 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00004812 // In C++, it's bool. C++ 5.3.1p8
4813 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004814 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00004815 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00004816 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00004817 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00004818 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004819 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00004820 resultType = Input->getType();
4821 break;
4822 }
4823 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004824 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004825
4826 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004827 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004828}
4829
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004830// Unary Operators. 'Tok' is the token for the operator.
4831Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4832 tok::TokenKind Op, ExprArg input) {
4833 Expr *Input = (Expr*)input.get();
4834 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4835
4836 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4837 // Find all of the overloaded operators visible from this
4838 // point. We perform both an operator-name lookup from the local
4839 // scope and an argument-dependent lookup based on the types of
4840 // the arguments.
4841 FunctionSet Functions;
4842 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4843 if (OverOp != OO_None) {
4844 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4845 Functions);
4846 DeclarationName OpName
4847 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4848 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4849 }
4850
4851 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4852 }
4853
4854 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4855}
4856
Steve Naroff1b273c42007-09-16 14:56:35 +00004857/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00004858Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4859 SourceLocation LabLoc,
4860 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004861 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00004862 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00004863
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004864 // If we haven't seen this label yet, create a forward reference. It
4865 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004866 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00004867 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004868
Reid Spencer5f016e22007-07-11 17:01:13 +00004869 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00004870 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4871 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00004872}
4873
Sebastian Redlf53597f2009-03-15 17:47:39 +00004874Sema::OwningExprResult
4875Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4876 SourceLocation RPLoc) { // "({..})"
4877 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004878 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4879 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4880
Eli Friedmandca2b732009-01-24 23:09:00 +00004881 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00004882 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004883 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00004884
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004885 // FIXME: there are a variety of strange constraints to enforce here, for
4886 // example, it is not possible to goto into a stmt expression apparently.
4887 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004888
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004889 // If there are sub stmts in the compound stmt, take the type of the last one
4890 // as the type of the stmtexpr.
4891 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004892
Chris Lattner611b2ec2008-07-26 19:51:01 +00004893 if (!Compound->body_empty()) {
4894 Stmt *LastStmt = Compound->body_back();
4895 // If LastStmt is a label, skip down through into the body.
4896 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4897 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004898
Chris Lattner611b2ec2008-07-26 19:51:01 +00004899 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004900 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004901 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004902
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004903 // FIXME: Check that expression type is complete/non-abstract; statement
4904 // expressions are not lvalues.
4905
Sebastian Redlf53597f2009-03-15 17:47:39 +00004906 substmt.release();
4907 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004908}
Steve Naroffd34e9152007-08-01 22:05:33 +00004909
Sebastian Redlf53597f2009-03-15 17:47:39 +00004910Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4911 SourceLocation BuiltinLoc,
4912 SourceLocation TypeLoc,
4913 TypeTy *argty,
4914 OffsetOfComponent *CompPtr,
4915 unsigned NumComponents,
4916 SourceLocation RPLoc) {
4917 // FIXME: This function leaks all expressions in the offset components on
4918 // error.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004919 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4920 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004921
Sebastian Redl28507842009-02-26 14:39:58 +00004922 bool Dependent = ArgTy->isDependentType();
4923
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004924 // We must have at least one component that refers to the type, and the first
4925 // one is known to be a field designator. Verify that the ArgTy represents
4926 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00004927 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004928 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004929
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004930 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4931 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00004932
Eli Friedman35183ac2009-02-27 06:44:11 +00004933 // Otherwise, create a null pointer as the base, and iteratively process
4934 // the offsetof designators.
4935 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4936 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004937 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00004938 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004939
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004940 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4941 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00004942 // FIXME: This diagnostic isn't actually visible because the location is in
4943 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004944 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004945 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4946 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004947
Sebastian Redl28507842009-02-26 14:39:58 +00004948 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00004949 bool DidWarnAboutNonPOD = false;
Anders Carlsson5992e4a2009-05-02 18:36:10 +00004950
Sebastian Redl28507842009-02-26 14:39:58 +00004951 // FIXME: Dependent case loses a lot of information here. And probably
4952 // leaks like a sieve.
4953 for (unsigned i = 0; i != NumComponents; ++i) {
4954 const OffsetOfComponent &OC = CompPtr[i];
4955 if (OC.isBrackets) {
4956 // Offset of an array sub-field. TODO: Should we allow vector elements?
4957 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4958 if (!AT) {
4959 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004960 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4961 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004962 }
4963
4964 // FIXME: C++: Verify that operator[] isn't overloaded.
4965
Eli Friedman35183ac2009-02-27 06:44:11 +00004966 // Promote the array so it looks more like a normal array subscript
4967 // expression.
4968 DefaultFunctionArrayConversion(Res);
4969
Sebastian Redl28507842009-02-26 14:39:58 +00004970 // C99 6.5.2.1p1
4971 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004972 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00004973 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00004974 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00004975 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00004976 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00004977
4978 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4979 OC.LocEnd);
4980 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004981 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004982
Sebastian Redl28507842009-02-26 14:39:58 +00004983 const RecordType *RC = Res->getType()->getAsRecordType();
4984 if (!RC) {
4985 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00004986 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4987 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00004988 }
Chris Lattner704fe352007-08-30 17:59:59 +00004989
Sebastian Redl28507842009-02-26 14:39:58 +00004990 // Get the decl corresponding to this.
4991 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00004992 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00004993 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00004994 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
4995 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
4996 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00004997 DidWarnAboutNonPOD = true;
4998 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00004999 }
5000
Sebastian Redl28507842009-02-26 14:39:58 +00005001 FieldDecl *MemberDecl
5002 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5003 LookupMemberName)
5004 .getAsDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +00005005 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005006 if (!MemberDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005007 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5008 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005009
Sebastian Redl28507842009-02-26 14:39:58 +00005010 // FIXME: C++: Verify that MemberDecl isn't a static field.
5011 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005012 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005013 Res = BuildAnonymousStructUnionMemberReference(
5014 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005015 } else {
5016 // MemberDecl->getType() doesn't get the right qualifiers, but it
5017 // doesn't matter here.
5018 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5019 MemberDecl->getType().getNonReferenceType());
5020 }
Sebastian Redl28507842009-02-26 14:39:58 +00005021 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005022 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005023
Sebastian Redlf53597f2009-03-15 17:47:39 +00005024 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5025 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005026}
5027
5028
Sebastian Redlf53597f2009-03-15 17:47:39 +00005029Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5030 TypeTy *arg1,TypeTy *arg2,
5031 SourceLocation RPLoc) {
Steve Naroffd34e9152007-08-01 22:05:33 +00005032 QualType argT1 = QualType::getFromOpaquePtr(arg1);
5033 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005034
Steve Naroffd34e9152007-08-01 22:05:33 +00005035 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005036
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005037 if (getLangOptions().CPlusPlus) {
5038 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5039 << SourceRange(BuiltinLoc, RPLoc);
5040 return ExprError();
5041 }
5042
Sebastian Redlf53597f2009-03-15 17:47:39 +00005043 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5044 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005045}
5046
Sebastian Redlf53597f2009-03-15 17:47:39 +00005047Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5048 ExprArg cond,
5049 ExprArg expr1, ExprArg expr2,
5050 SourceLocation RPLoc) {
5051 Expr *CondExpr = static_cast<Expr*>(cond.get());
5052 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5053 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005054
Steve Naroffd04fdd52007-08-03 21:21:27 +00005055 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5056
Sebastian Redl28507842009-02-26 14:39:58 +00005057 QualType resType;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005058 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005059 resType = Context.DependentTy;
5060 } else {
5061 // The conditional expression is required to be a constant expression.
5062 llvm::APSInt condEval(32);
5063 SourceLocation ExpLoc;
5064 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005065 return ExprError(Diag(ExpLoc,
5066 diag::err_typecheck_choose_expr_requires_constant)
5067 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005068
Sebastian Redl28507842009-02-26 14:39:58 +00005069 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5070 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5071 }
5072
Sebastian Redlf53597f2009-03-15 17:47:39 +00005073 cond.release(); expr1.release(); expr2.release();
5074 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5075 resType, RPLoc));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005076}
5077
Steve Naroff4eb206b2008-09-03 18:15:37 +00005078//===----------------------------------------------------------------------===//
5079// Clang Extensions.
5080//===----------------------------------------------------------------------===//
5081
5082/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005083void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005084 // Analyze block parameters.
5085 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005086
Steve Naroff4eb206b2008-09-03 18:15:37 +00005087 // Add BSI to CurBlock.
5088 BSI->PrevBlockInfo = CurBlock;
5089 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005090
Steve Naroff4eb206b2008-09-03 18:15:37 +00005091 BSI->ReturnType = 0;
5092 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005093 BSI->hasBlockDeclRefExprs = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005094 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5095 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005096
Steve Naroff090276f2008-10-10 01:28:17 +00005097 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005098 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005099}
5100
Mike Stump98eb8a72009-02-04 22:31:32 +00005101void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005102 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005103
5104 if (ParamInfo.getNumTypeObjects() == 0
5105 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Fariborz Jahanian3d1a7af2009-05-18 23:17:46 +00005106 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005107 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5108
Mike Stump4eeab842009-04-28 01:10:27 +00005109 if (T->isArrayType()) {
5110 Diag(ParamInfo.getSourceRange().getBegin(),
5111 diag::err_block_returns_array);
5112 return;
5113 }
5114
Mike Stump98eb8a72009-02-04 22:31:32 +00005115 // The parameter list is optional, if there was none, assume ().
5116 if (!T->isFunctionType())
5117 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5118
5119 CurBlock->hasPrototype = true;
5120 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005121 // Check for a valid sentinel attribute on this block.
5122 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5123 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005124 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005125 // FIXME: remove the attribute.
5126 }
Chris Lattner9097af12009-04-11 19:27:54 +00005127 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5128
5129 // Do not allow returning a objc interface by-value.
5130 if (RetTy->isObjCInterfaceType()) {
5131 Diag(ParamInfo.getSourceRange().getBegin(),
5132 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5133 return;
5134 }
Mike Stump98eb8a72009-02-04 22:31:32 +00005135 return;
5136 }
5137
Steve Naroff4eb206b2008-09-03 18:15:37 +00005138 // Analyze arguments to block.
5139 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5140 "Not a function declarator!");
5141 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005142
Steve Naroff090276f2008-10-10 01:28:17 +00005143 CurBlock->hasPrototype = FTI.hasPrototype;
5144 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005145
Steve Naroff4eb206b2008-09-03 18:15:37 +00005146 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5147 // no arguments, not a function that takes a single void argument.
5148 if (FTI.hasPrototype &&
5149 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00005150 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5151 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005152 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00005153 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005154 } else if (FTI.hasPrototype) {
5155 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00005156 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00005157 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005158 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00005159 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00005160 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00005161 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Fariborz Jahanian3d1a7af2009-05-18 23:17:46 +00005162 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00005163 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5164 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5165 // If this has an identifier, add it to the scope stack.
5166 if ((*AI)->getIdentifier())
5167 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00005168
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005169 // Check for a valid sentinel attribute on this block.
5170 if (!CurBlock->isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5171 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005172 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005173 // FIXME: remove the attribute.
5174 }
5175
Chris Lattner9097af12009-04-11 19:27:54 +00005176 // Analyze the return type.
5177 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5178 QualType RetTy = T->getAsFunctionType()->getResultType();
5179
5180 // Do not allow returning a objc interface by-value.
5181 if (RetTy->isObjCInterfaceType()) {
5182 Diag(ParamInfo.getSourceRange().getBegin(),
5183 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5184 } else if (!RetTy->isDependentType())
5185 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005186}
5187
5188/// ActOnBlockError - If there is an error parsing a block, this callback
5189/// is invoked to pop the information about the block from the action impl.
5190void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5191 // Ensure that CurBlock is deleted.
5192 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005193
Chris Lattner17a78302009-04-19 05:28:12 +00005194 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5195
Steve Naroff4eb206b2008-09-03 18:15:37 +00005196 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00005197 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005198 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005199 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00005200}
5201
5202/// ActOnBlockStmtExpr - This is called when the body of a block statement
5203/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00005204Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5205 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00005206 // If blocks are disabled, emit an error.
5207 if (!LangOpts.Blocks)
5208 Diag(CaretLoc, diag::err_blocks_disable);
5209
Steve Naroff4eb206b2008-09-03 18:15:37 +00005210 // Ensure that CurBlock is deleted.
5211 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005212
Steve Naroff090276f2008-10-10 01:28:17 +00005213 PopDeclContext();
5214
Steve Naroff4eb206b2008-09-03 18:15:37 +00005215 // Pop off CurBlock, handle nested blocks.
5216 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005217
Steve Naroff4eb206b2008-09-03 18:15:37 +00005218 QualType RetTy = Context.VoidTy;
5219 if (BSI->ReturnType)
5220 RetTy = QualType(BSI->ReturnType, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005221
Steve Naroff4eb206b2008-09-03 18:15:37 +00005222 llvm::SmallVector<QualType, 8> ArgTypes;
5223 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5224 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005225
Steve Naroff4eb206b2008-09-03 18:15:37 +00005226 QualType BlockTy;
5227 if (!BSI->hasPrototype)
Eli Friedman687abff2009-06-08 04:24:21 +00005228 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005229 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00005230 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005231 BSI->isVariadic, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005232
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005233 // FIXME: Check that return/parameter types are complete/non-abstract
5234
Steve Naroff4eb206b2008-09-03 18:15:37 +00005235 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005236
Chris Lattner17a78302009-04-19 05:28:12 +00005237 // If needed, diagnose invalid gotos and switches in the block.
5238 if (CurFunctionNeedsScopeChecking)
5239 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5240 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5241
Anders Carlssone9146f22009-05-01 19:49:17 +00005242 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Sebastian Redlf53597f2009-03-15 17:47:39 +00005243 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5244 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00005245}
5246
Sebastian Redlf53597f2009-03-15 17:47:39 +00005247Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5248 ExprArg expr, TypeTy *type,
5249 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005250 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00005251 Expr *E = static_cast<Expr*>(expr.get());
5252 Expr *OrigExpr = E;
5253
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005254 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005255
5256 // Get the va_list type
5257 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00005258 if (VaListType->isArrayType()) {
5259 // Deal with implicit array decay; for example, on x86-64,
5260 // va_list is an array, but it's supposed to decay to
5261 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005262 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00005263 // Make sure the input expression also decays appropriately.
5264 UsualUnaryConversions(E);
5265 } else {
5266 // Otherwise, the va_list argument must be an l-value because
5267 // it is modified by va_arg.
Douglas Gregordd027302009-05-19 23:10:31 +00005268 if (!E->isTypeDependent() &&
5269 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00005270 return ExprError();
5271 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005272
Douglas Gregordd027302009-05-19 23:10:31 +00005273 if (!E->isTypeDependent() &&
5274 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00005275 return ExprError(Diag(E->getLocStart(),
5276 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00005277 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00005278 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005279
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005280 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005281 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005282
Sebastian Redlf53597f2009-03-15 17:47:39 +00005283 expr.release();
5284 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5285 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005286}
5287
Sebastian Redlf53597f2009-03-15 17:47:39 +00005288Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00005289 // The type of __null will be int or long, depending on the size of
5290 // pointers on the target.
5291 QualType Ty;
5292 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5293 Ty = Context.IntTy;
5294 else
5295 Ty = Context.LongTy;
5296
Sebastian Redlf53597f2009-03-15 17:47:39 +00005297 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00005298}
5299
Chris Lattner5cf216b2008-01-04 18:04:52 +00005300bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5301 SourceLocation Loc,
5302 QualType DstType, QualType SrcType,
5303 Expr *SrcExpr, const char *Flavor) {
5304 // Decode the result (notice that AST's are still created for extensions).
5305 bool isInvalid = false;
5306 unsigned DiagKind;
5307 switch (ConvTy) {
5308 default: assert(0 && "Unknown conversion type");
5309 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005310 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00005311 DiagKind = diag::ext_typecheck_convert_pointer_int;
5312 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005313 case IntToPointer:
5314 DiagKind = diag::ext_typecheck_convert_int_pointer;
5315 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005316 case IncompatiblePointer:
5317 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5318 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005319 case IncompatiblePointerSign:
5320 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5321 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005322 case FunctionVoidPointer:
5323 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5324 break;
5325 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00005326 // If the qualifiers lost were because we were applying the
5327 // (deprecated) C++ conversion from a string literal to a char*
5328 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5329 // Ideally, this check would be performed in
5330 // CheckPointerTypesForAssignment. However, that would require a
5331 // bit of refactoring (so that the second argument is an
5332 // expression, rather than a type), which should be done as part
5333 // of a larger effort to fix CheckPointerTypesForAssignment for
5334 // C++ semantics.
5335 if (getLangOptions().CPlusPlus &&
5336 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5337 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005338 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5339 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005340 case IntToBlockPointer:
5341 DiagKind = diag::err_int_to_block_pointer;
5342 break;
5343 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00005344 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005345 break;
Steve Naroff39579072008-10-14 22:18:38 +00005346 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00005347 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00005348 // it can give a more specific diagnostic.
5349 DiagKind = diag::warn_incompatible_qualified_id;
5350 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005351 case IncompatibleVectors:
5352 DiagKind = diag::warn_incompatible_vectors;
5353 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005354 case Incompatible:
5355 DiagKind = diag::err_typecheck_convert_incompatible;
5356 isInvalid = true;
5357 break;
5358 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005359
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005360 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5361 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00005362 return isInvalid;
5363}
Anders Carlssone21555e2008-11-30 19:50:32 +00005364
Chris Lattner3bf68932009-04-25 21:59:05 +00005365bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005366 llvm::APSInt ICEResult;
5367 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5368 if (Result)
5369 *Result = ICEResult;
5370 return false;
5371 }
5372
Anders Carlssone21555e2008-11-30 19:50:32 +00005373 Expr::EvalResult EvalResult;
5374
Mike Stumpeed9cac2009-02-19 03:04:26 +00005375 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00005376 EvalResult.HasSideEffects) {
5377 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5378
5379 if (EvalResult.Diag) {
5380 // We only show the note if it's not the usual "invalid subexpression"
5381 // or if it's actually in a subexpression.
5382 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5383 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5384 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5385 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005386
Anders Carlssone21555e2008-11-30 19:50:32 +00005387 return true;
5388 }
5389
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005390 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5391 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00005392
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005393 if (EvalResult.Diag &&
5394 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5395 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005396
Anders Carlssone21555e2008-11-30 19:50:32 +00005397 if (Result)
5398 *Result = EvalResult.Val.getInt();
5399 return false;
5400}