blob: 7e82df44377aa555c1ae13372a8ae9b7ad5c3d8e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000042 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000051 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000052
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
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000061 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000062 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000063 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000064 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000079 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000082 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregoraa57e862009-02-18 21:56:37 +000087 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000088}
89
Fariborz Jahanian180f3412009-05-13 18:09:35 +000090/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
91/// (and other functions in future), which have been declared with sentinel
92/// attribute. It warns if call does not have the sentinel argument.
93///
94void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
95 Expr **Args, unsigned NumArgs)
96{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000097 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000098 if (!attr)
99 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000100 int sentinelPos = attr->getSentinel();
101 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000102
Mike Stumpe127ae32009-05-16 07:39:55 +0000103 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
104 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000105 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000106 bool warnNotEnoughArgs = false;
107 int isMethod = 0;
108 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
109 // skip over named parameters.
110 ObjCMethodDecl::param_iterator P, E = MD->param_end();
111 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
112 if (nullPos)
113 --nullPos;
114 else
115 ++i;
116 }
117 warnNotEnoughArgs = (P != E || i >= NumArgs);
118 isMethod = 1;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000119 }
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000120 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
130 }
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
132 // block or function pointer call.
133 QualType Ty = V->getType();
134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000136 ? Ty->getAsPointerType()->getPointeeType()->getAsFunctionType()
137 : Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139 unsigned NumArgsInProto = Proto->getNumArgs();
140 unsigned k;
141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148 }
149 if (Ty->isBlockPointerType())
150 isMethod = 2;
151 }
152 else
153 return;
154 }
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000155 else
156 return;
157
158 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000159 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000161 return;
162 }
163 int sentinel = i;
164 while (sentinelPos > 0 && i < NumArgs-1) {
165 --sentinelPos;
166 ++i;
167 }
168 if (sentinelPos > 0) {
169 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000170 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000171 return;
172 }
173 while (i < NumArgs-1) {
174 ++i;
175 ++sentinel;
176 }
177 Expr *sentinelExpr = Args[sentinel];
178 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
179 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000180 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000182 }
183 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000184}
185
Douglas Gregor3bb30002009-02-26 21:00:50 +0000186SourceRange Sema::getExprRange(ExprTy *E) const {
187 Expr *Ex = (Expr *)E;
188 return Ex? Ex->getSourceRange() : SourceRange();
189}
190
Chris Lattner299b8842008-07-25 21:10:04 +0000191//===----------------------------------------------------------------------===//
192// Standard Promotions and Conversions
193//===----------------------------------------------------------------------===//
194
Chris Lattner299b8842008-07-25 21:10:04 +0000195/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
196void Sema::DefaultFunctionArrayConversion(Expr *&E) {
197 QualType Ty = E->getType();
198 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
199
Chris Lattner299b8842008-07-25 21:10:04 +0000200 if (Ty->isFunctionType())
201 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000202 else if (Ty->isArrayType()) {
203 // In C90 mode, arrays only promote to pointers if the array expression is
204 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
205 // type 'array of type' is converted to an expression that has type 'pointer
206 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
207 // that has type 'array of type' ...". The relevant change is "an lvalue"
208 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000209 //
210 // C++ 4.2p1:
211 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
212 // T" can be converted to an rvalue of type "pointer to T".
213 //
214 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
215 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000216 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
217 }
Chris Lattner299b8842008-07-25 21:10:04 +0000218}
219
Douglas Gregor70b307e2009-05-01 20:41:21 +0000220/// \brief Whether this is a promotable bitfield reference according
221/// to C99 6.3.1.1p2, bullet 2.
222///
223/// \returns the type this bit-field will promote to, or NULL if no
224/// promotion occurs.
225static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000226 FieldDecl *Field = E->getBitField();
227 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000228 return QualType();
229
230 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
231 if (!BT)
232 return QualType();
233
234 if (BT->getKind() != BuiltinType::Bool &&
235 BT->getKind() != BuiltinType::Int &&
236 BT->getKind() != BuiltinType::UInt)
237 return QualType();
238
239 llvm::APSInt BitWidthAP;
240 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
241 return QualType();
242
243 uint64_t BitWidth = BitWidthAP.getZExtValue();
244 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
245 if (BitWidth < IntSize ||
246 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
247 return Context.IntTy;
248
249 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
250 return Context.UnsignedIntTy;
251
252 return QualType();
253}
254
Chris Lattner299b8842008-07-25 21:10:04 +0000255/// UsualUnaryConversions - Performs various conversions that are common to most
256/// operators (C99 6.3). The conversions of array and function types are
257/// sometimes surpressed. For example, the array->pointer conversion doesn't
258/// apply if the array is an argument to the sizeof or address (&) operators.
259/// In these instances, this routine should *not* be called.
260Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
261 QualType Ty = Expr->getType();
262 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
263
Douglas Gregor70b307e2009-05-01 20:41:21 +0000264 // C99 6.3.1.1p2:
265 //
266 // The following may be used in an expression wherever an int or
267 // unsigned int may be used:
268 // - an object or expression with an integer type whose integer
269 // conversion rank is less than or equal to the rank of int
270 // and unsigned int.
271 // - A bit-field of type _Bool, int, signed int, or unsigned int.
272 //
273 // If an int can represent all values of the original type, the
274 // value is converted to an int; otherwise, it is converted to an
275 // unsigned int. These are called the integer promotions. All
276 // other types are unchanged by the integer promotions.
277 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000278 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000279 return Expr;
280 } else {
281 QualType T = isPromotableBitField(Expr, Context);
282 if (!T.isNull()) {
283 ImpCastExprToType(Expr, T);
284 return Expr;
285 }
286 }
287
288 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000289 return Expr;
290}
291
Chris Lattner9305c3d2008-07-25 22:25:12 +0000292/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
293/// do not have a prototype. Arguments that have type float are promoted to
294/// double. All other argument types are converted by UsualUnaryConversions().
295void Sema::DefaultArgumentPromotion(Expr *&Expr) {
296 QualType Ty = Expr->getType();
297 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
298
299 // If this is a 'float' (CVR qualified or typedef) promote to double.
300 if (const BuiltinType *BT = Ty->getAsBuiltinType())
301 if (BT->getKind() == BuiltinType::Float)
302 return ImpCastExprToType(Expr, Context.DoubleTy);
303
304 UsualUnaryConversions(Expr);
305}
306
Chris Lattner81f00ed2009-04-12 08:11:20 +0000307/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
308/// will warn if the resulting type is not a POD type, and rejects ObjC
309/// interfaces passed by value. This returns true if the argument type is
310/// completely illegal.
311bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000312 DefaultArgumentPromotion(Expr);
313
Chris Lattner81f00ed2009-04-12 08:11:20 +0000314 if (Expr->getType()->isObjCInterfaceType()) {
315 Diag(Expr->getLocStart(),
316 diag::err_cannot_pass_objc_interface_to_vararg)
317 << Expr->getType() << CT;
318 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000319 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000320
321 if (!Expr->getType()->isPODType())
322 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
323 << Expr->getType() << CT;
324
325 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000326}
327
328
Chris Lattner299b8842008-07-25 21:10:04 +0000329/// UsualArithmeticConversions - Performs various conversions that are common to
330/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
331/// routine returns the first non-arithmetic type found. The client is
332/// responsible for emitting appropriate error diagnostics.
333/// FIXME: verify the conversion rules for "complex int" are consistent with
334/// GCC.
335QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
336 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000337 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000338 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000339
340 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000341
Chris Lattner299b8842008-07-25 21:10:04 +0000342 // For conversion purposes, we ignore any qualifiers.
343 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000344 QualType lhs =
345 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
346 QualType rhs =
347 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000348
349 // If both types are identical, no conversion is needed.
350 if (lhs == rhs)
351 return lhs;
352
353 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
354 // The caller can deal with this (e.g. pointer + int).
355 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
356 return lhs;
357
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000358 // Perform bitfield promotions.
359 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
360 if (!LHSBitfieldPromoteTy.isNull())
361 lhs = LHSBitfieldPromoteTy;
362 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
363 if (!RHSBitfieldPromoteTy.isNull())
364 rhs = RHSBitfieldPromoteTy;
365
Douglas Gregor70d26122008-11-12 17:17:38 +0000366 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000367 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000368 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000369 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000370 return destType;
371}
372
373QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
374 // Perform the usual unary conversions. We do this early so that
375 // integral promotions to "int" can allow us to exit early, in the
376 // lhs == rhs check. Also, for conversion purposes, we ignore any
377 // qualifiers. For example, "const float" and "float" are
378 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000379 if (lhs->isPromotableIntegerType())
380 lhs = Context.IntTy;
381 else
382 lhs = lhs.getUnqualifiedType();
383 if (rhs->isPromotableIntegerType())
384 rhs = Context.IntTy;
385 else
386 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000387
Chris Lattner299b8842008-07-25 21:10:04 +0000388 // If both types are identical, no conversion is needed.
389 if (lhs == rhs)
390 return lhs;
391
392 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
393 // The caller can deal with this (e.g. pointer + int).
394 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
395 return lhs;
396
397 // At this point, we have two different arithmetic types.
398
399 // Handle complex types first (C99 6.3.1.8p1).
400 if (lhs->isComplexType() || rhs->isComplexType()) {
401 // if we have an integer operand, the result is the complex type.
402 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
403 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000404 return lhs;
405 }
406 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
407 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000408 return rhs;
409 }
410 // This handles complex/complex, complex/float, or float/complex.
411 // When both operands are complex, the shorter operand is converted to the
412 // type of the longer, and that is the type of the result. This corresponds
413 // to what is done when combining two real floating-point operands.
414 // The fun begins when size promotion occur across type domains.
415 // From H&S 6.3.4: When one operand is complex and the other is a real
416 // floating-point type, the less precise type is converted, within it's
417 // real or complex domain, to the precision of the other type. For example,
418 // when combining a "long double" with a "double _Complex", the
419 // "double _Complex" is promoted to "long double _Complex".
420 int result = Context.getFloatingTypeOrder(lhs, rhs);
421
422 if (result > 0) { // The left side is bigger, convert rhs.
423 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000424 } else if (result < 0) { // The right side is bigger, convert lhs.
425 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000426 }
427 // At this point, lhs and rhs have the same rank/size. Now, make sure the
428 // domains match. This is a requirement for our implementation, C99
429 // does not require this promotion.
430 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
431 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000432 return rhs;
433 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000434 return lhs;
435 }
436 }
437 return lhs; // The domain/size match exactly.
438 }
439 // Now handle "real" floating types (i.e. float, double, long double).
440 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
441 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000442 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000443 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000444 return lhs;
445 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000446 if (rhs->isComplexIntegerType()) {
447 // convert rhs to the complex floating point type.
448 return Context.getComplexType(lhs);
449 }
450 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000451 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000452 return rhs;
453 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000454 if (lhs->isComplexIntegerType()) {
455 // convert lhs to the complex floating point type.
456 return Context.getComplexType(rhs);
457 }
Chris Lattner299b8842008-07-25 21:10:04 +0000458 // We have two real floating types, float/complex combos were handled above.
459 // Convert the smaller operand to the bigger result.
460 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000461 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000462 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000463 assert(result < 0 && "illegal float comparison");
464 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000465 }
466 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
467 // Handle GCC complex int extension.
468 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
469 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
470
471 if (lhsComplexInt && rhsComplexInt) {
472 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000473 rhsComplexInt->getElementType()) >= 0)
474 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000475 return rhs;
476 } else if (lhsComplexInt && rhs->isIntegerType()) {
477 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000478 return lhs;
479 } else if (rhsComplexInt && lhs->isIntegerType()) {
480 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000481 return rhs;
482 }
483 }
484 // Finally, we have two differing integer types.
485 // The rules for this case are in C99 6.3.1.8
486 int compare = Context.getIntegerTypeOrder(lhs, rhs);
487 bool lhsSigned = lhs->isSignedIntegerType(),
488 rhsSigned = rhs->isSignedIntegerType();
489 QualType destType;
490 if (lhsSigned == rhsSigned) {
491 // Same signedness; use the higher-ranked type
492 destType = compare >= 0 ? lhs : rhs;
493 } else if (compare != (lhsSigned ? 1 : -1)) {
494 // The unsigned type has greater than or equal rank to the
495 // signed type, so use the unsigned type
496 destType = lhsSigned ? rhs : lhs;
497 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
498 // The two types are different widths; if we are here, that
499 // means the signed type is larger than the unsigned type, so
500 // use the signed type.
501 destType = lhsSigned ? lhs : rhs;
502 } else {
503 // The signed type is higher-ranked than the unsigned type,
504 // but isn't actually any bigger (like unsigned int and long
505 // on most 32-bit systems). Use the unsigned type corresponding
506 // to the signed type.
507 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
508 }
Chris Lattner299b8842008-07-25 21:10:04 +0000509 return destType;
510}
511
512//===----------------------------------------------------------------------===//
513// Semantic Analysis for various Expression Types
514//===----------------------------------------------------------------------===//
515
516
Steve Naroff87d58b42007-09-16 03:34:24 +0000517/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000518/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
519/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
520/// multiple tokens. However, the common case is that StringToks points to one
521/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000522///
523Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000524Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000525 assert(NumStringToks && "Must have at least one string!");
526
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000527 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000528 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000529 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000530
531 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
532 for (unsigned i = 0; i != NumStringToks; ++i)
533 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000534
Chris Lattnera6dcce32008-02-11 00:02:17 +0000535 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000536 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000537 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000538
539 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
540 if (getLangOptions().CPlusPlus)
541 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000542
Chris Lattnera6dcce32008-02-11 00:02:17 +0000543 // Get an array type for the string, according to C99 6.4.5. This includes
544 // the nul terminator character as well as the string length for pascal
545 // strings.
546 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000547 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000548 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000549
Chris Lattner4b009652007-07-25 00:24:17 +0000550 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000551 return Owned(StringLiteral::Create(Context, Literal.GetString(),
552 Literal.GetStringLength(),
553 Literal.AnyWide, StrTy,
554 &StringTokLocs[0],
555 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000556}
557
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000558/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
559/// CurBlock to VD should cause it to be snapshotted (as we do for auto
560/// variables defined outside the block) or false if this is not needed (e.g.
561/// for values inside the block or for globals).
562///
Chris Lattner0b464252009-04-21 22:26:47 +0000563/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
564/// up-to-date.
565///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000566static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
567 ValueDecl *VD) {
568 // If the value is defined inside the block, we couldn't snapshot it even if
569 // we wanted to.
570 if (CurBlock->TheDecl == VD->getDeclContext())
571 return false;
572
573 // If this is an enum constant or function, it is constant, don't snapshot.
574 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
575 return false;
576
577 // If this is a reference to an extern, static, or global variable, no need to
578 // snapshot it.
579 // FIXME: What about 'const' variables in C++?
580 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000581 if (!Var->hasLocalStorage())
582 return false;
583
584 // Blocks that have these can't be constant.
585 CurBlock->hasBlockDeclRefExprs = true;
586
587 // If we have nested blocks, the decl may be declared in an outer block (in
588 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
589 // be defined outside all of the current blocks (in which case the blocks do
590 // all get the bit). Walk the nesting chain.
591 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
592 NextBlock = NextBlock->PrevBlockInfo) {
593 // If we found the defining block for the variable, don't mark the block as
594 // having a reference outside it.
595 if (NextBlock->TheDecl == VD->getDeclContext())
596 break;
597
598 // Otherwise, the DeclRef from the inner block causes the outer one to need
599 // a snapshot as well.
600 NextBlock->hasBlockDeclRefExprs = true;
601 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000602
603 return true;
604}
605
606
607
Steve Naroff0acc9c92007-09-15 18:49:24 +0000608/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000609/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000610/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000612/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000613Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
614 IdentifierInfo &II,
615 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000616 const CXXScopeSpec *SS,
617 bool isAddressOfOperand) {
618 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000619 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000620}
621
Douglas Gregor566782a2009-01-06 05:10:23 +0000622/// BuildDeclRefExpr - Build either a DeclRefExpr or a
623/// QualifiedDeclRefExpr based on whether or not SS is a
624/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000625Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000626Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
627 bool TypeDependent, bool ValueDependent,
628 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000629 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
630 Diag(Loc,
631 diag::err_auto_variable_cannot_appear_in_own_initializer)
632 << D->getDeclName();
633 return ExprError();
634 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000635
636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
637 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
638 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
639 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
640 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
641 << D->getIdentifier() << FD->getDeclName();
642 Diag(D->getLocation(), diag::note_local_variable_declared_here)
643 << D->getIdentifier();
644 return ExprError();
645 }
646 }
647 }
648 }
649
Douglas Gregor98189262009-06-19 23:52:42 +0000650 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000651
652 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000653 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000654 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
655 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000656 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000657 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000658 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
659
660 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000661}
662
Douglas Gregor723d3332009-01-07 00:43:41 +0000663/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
664/// variable corresponding to the anonymous union or struct whose type
665/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000666static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
667 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000668 assert(Record->isAnonymousStructOrUnion() &&
669 "Record must be an anonymous struct or union!");
670
Mike Stumpe127ae32009-05-16 07:39:55 +0000671 // FIXME: Once Decls are directly linked together, this will be an O(1)
672 // operation rather than a slow walk through DeclContext's vector (which
673 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000674 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000675 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
676 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000677 D != DEnd; ++D) {
678 if (*D == Record) {
679 // The object for the anonymous struct/union directly
680 // follows its type in the list of declarations.
681 ++D;
682 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000683 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000684 return *D;
685 }
686 }
687
688 assert(false && "Missing object for anonymous record");
689 return 0;
690}
691
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000692/// \brief Given a field that represents a member of an anonymous
693/// struct/union, build the path from that field's context to the
694/// actual member.
695///
696/// Construct the sequence of field member references we'll have to
697/// perform to get to the field in the anonymous union/struct. The
698/// list of members is built from the field outward, so traverse it
699/// backwards to go from an object in the current context to the field
700/// we found.
701///
702/// \returns The variable from which the field access should begin,
703/// for an anonymous struct/union that is not a member of another
704/// class. Otherwise, returns NULL.
705VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
706 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000707 assert(Field->getDeclContext()->isRecord() &&
708 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
709 && "Field must be stored inside an anonymous struct or union");
710
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000711 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000712 VarDecl *BaseObject = 0;
713 DeclContext *Ctx = Field->getDeclContext();
714 do {
715 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000716 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000717 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000718 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000719 else {
720 BaseObject = cast<VarDecl>(AnonObject);
721 break;
722 }
723 Ctx = Ctx->getParent();
724 } while (Ctx->isRecord() &&
725 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000726
727 return BaseObject;
728}
729
730Sema::OwningExprResult
731Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
732 FieldDecl *Field,
733 Expr *BaseObjectExpr,
734 SourceLocation OpLoc) {
735 llvm::SmallVector<FieldDecl *, 4> AnonFields;
736 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
737 AnonFields);
738
Douglas Gregor723d3332009-01-07 00:43:41 +0000739 // Build the expression that refers to the base object, from
740 // which we will build a sequence of member references to each
741 // of the anonymous union objects and, eventually, the field we
742 // found via name lookup.
743 bool BaseObjectIsPointer = false;
744 unsigned ExtraQuals = 0;
745 if (BaseObject) {
746 // BaseObject is an anonymous struct/union variable (and is,
747 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000748 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000749 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000750 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000751 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000752 ExtraQuals
753 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
754 } else if (BaseObjectExpr) {
755 // The caller provided the base object expression. Determine
756 // whether its a pointer and whether it adds any qualifiers to the
757 // anonymous struct/union fields we're looking into.
758 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000759 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000760 BaseObjectIsPointer = true;
761 ObjectType = ObjectPtr->getPointeeType();
762 }
763 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
764 } else {
765 // We've found a member of an anonymous struct/union that is
766 // inside a non-anonymous struct/union, so in a well-formed
767 // program our base object expression is "this".
768 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
769 if (!MD->isStatic()) {
770 QualType AnonFieldType
771 = Context.getTagDeclType(
772 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
773 QualType ThisType = Context.getTagDeclType(MD->getParent());
774 if ((Context.getCanonicalType(AnonFieldType)
775 == Context.getCanonicalType(ThisType)) ||
776 IsDerivedFrom(ThisType, AnonFieldType)) {
777 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000778 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000779 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000780 BaseObjectIsPointer = true;
781 }
782 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000783 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
784 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000785 }
786 ExtraQuals = MD->getTypeQualifiers();
787 }
788
789 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000790 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
791 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000792 }
793
794 // Build the implicit member references to the field of the
795 // anonymous struct/union.
796 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000797 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000798 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
799 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
800 FI != FIEnd; ++FI) {
801 QualType MemberType = (*FI)->getType();
802 if (!(*FI)->isMutable()) {
803 unsigned combinedQualifiers
804 = MemberType.getCVRQualifiers() | ExtraQuals;
805 MemberType = MemberType.getQualifiedType(combinedQualifiers);
806 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000807 if (BaseAddrSpace != MemberType.getAddressSpace())
808 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000809 MarkDeclarationReferenced(Loc, *FI);
Steve Naroff774e4152009-01-21 00:14:39 +0000810 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
811 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000812 BaseObjectIsPointer = false;
813 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000814 }
815
Sebastian Redlcd883f72009-01-18 18:53:16 +0000816 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000817}
818
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000819/// ActOnDeclarationNameExpr - The parser has read some kind of name
820/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
821/// performs lookup on that name and returns an expression that refers
822/// to that name. This routine isn't directly called from the parser,
823/// because the parser doesn't know about DeclarationName. Rather,
824/// this routine is called by ActOnIdentifierExpr,
825/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
826/// which form the DeclarationName from the corresponding syntactic
827/// forms.
828///
829/// HasTrailingLParen indicates whether this identifier is used in a
830/// function call context. LookupCtx is only used for a C++
831/// qualified-id (foo::bar) to indicate the class or namespace that
832/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000833///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000834/// isAddressOfOperand means that this expression is the direct operand
835/// of an address-of operator. This matters because this is the only
836/// situation where a qualified name referencing a non-static member may
837/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000838Sema::OwningExprResult
839Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
840 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000841 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000842 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000843 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000844 if (SS && SS->isInvalid())
845 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000846
847 // C++ [temp.dep.expr]p3:
848 // An id-expression is type-dependent if it contains:
849 // -- a nested-name-specifier that contains a class-name that
850 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000851 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000852 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000853 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
854 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000855 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
856 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000857 }
858
Douglas Gregor411889e2009-02-13 23:20:09 +0000859 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
860 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000861
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862 if (Lookup.isAmbiguous()) {
863 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
864 SS && SS->isSet() ? SS->getRange()
865 : SourceRange());
866 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000867 }
868
869 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000870
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000871 // If this reference is in an Objective-C method, then ivar lookup happens as
872 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000873 IdentifierInfo *II = Name.getAsIdentifierInfo();
874 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000875 // There are two cases to handle here. 1) scoped lookup could have failed,
876 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000877 // found a decl, but that decl is outside the current instance method (i.e.
878 // a global variable). In these two cases, we do a lookup for an ivar with
879 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000880 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000881 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000882 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000883 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000884 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000885 if (DiagnoseUseOfDecl(IV, Loc))
886 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000887
888 // If we're referencing an invalid decl, just return this as a silent
889 // error node. The error diagnostic was already emitted on the decl.
890 if (IV->isInvalidDecl())
891 return ExprError();
892
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000893 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
894 // If a class method attemps to use a free standing ivar, this is
895 // an error.
896 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
897 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
898 << IV->getDeclName());
899 // If a class method uses a global variable, even if an ivar with
900 // same name exists, use the global.
901 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000902 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
903 ClassDeclared != IFace)
904 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000905 // FIXME: This should use a new expr for a direct reference, don't
906 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000907 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000908 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
909 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000910 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000911 return Owned(new (Context)
912 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000913 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000914 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000915 }
916 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000917 else if (getCurMethodDecl()->isInstanceMethod()) {
918 // We should warn if a local variable hides an ivar.
919 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000920 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000921 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000922 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
923 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000924 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000925 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000926 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000927 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000928 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000929 QualType T;
930
931 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000932 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
933 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000934 else
935 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000936 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000937 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000938 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000939
Douglas Gregoraa57e862009-02-18 21:56:37 +0000940 // Determine whether this name might be a candidate for
941 // argument-dependent lookup.
942 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
943 HasTrailingLParen;
944
945 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000946 // We've seen something of the form
947 //
948 // identifier(
949 //
950 // and we did not find any entity by the name
951 // "identifier". However, this identifier is still subject to
952 // argument-dependent lookup, so keep track of the name.
953 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
954 Context.OverloadTy,
955 Loc));
956 }
957
Chris Lattner4b009652007-07-25 00:24:17 +0000958 if (D == 0) {
959 // Otherwise, this could be an implicitly declared function reference (legal
960 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000961 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000962 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000963 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000964 else {
965 // If this name wasn't predeclared and if this is not a function call,
966 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000967 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000968 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
969 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000970 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
971 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000972 return ExprError(Diag(Loc, diag::err_undeclared_use)
973 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000974 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000975 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000976 }
977 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000978
979 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
980 // Warn about constructs like:
981 // if (void *X = foo()) { ... } else { X }.
982 // In the else block, the pointer is always false.
983
984 // FIXME: In a template instantiation, we don't have scope
985 // information to check this property.
986 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
987 Scope *CheckS = S;
988 while (CheckS) {
989 if (CheckS->isWithinElse() &&
990 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
991 if (Var->getType()->isBooleanType())
992 ExprError(Diag(Loc, diag::warn_value_always_false)
993 << Var->getDeclName());
994 else
995 ExprError(Diag(Loc, diag::warn_value_always_zero)
996 << Var->getDeclName());
997 break;
998 }
999
1000 // Move up one more control parent to check again.
1001 CheckS = CheckS->getControlParent();
1002 if (CheckS)
1003 CheckS = CheckS->getParent();
1004 }
1005 }
1006 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1007 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1008 // C99 DR 316 says that, if a function type comes from a
1009 // function definition (without a prototype), that type is only
1010 // used for checking compatibility. Therefore, when referencing
1011 // the function, we pretend that we don't have the full function
1012 // type.
1013 if (DiagnoseUseOfDecl(Func, Loc))
1014 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +00001015
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001016 QualType T = Func->getType();
1017 QualType NoProtoType = T;
1018 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1019 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
1020 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
1021 }
1022 }
1023
1024 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
1025}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001026/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001027bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001028Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1029 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
1030 if (CXXRecordDecl *RD =
1031 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
1032 QualType DestType =
1033 Context.getCanonicalType(Context.getTypeDeclType(RD));
1034 if (!DestType->isDependentType() &&
1035 !From->getType()->isDependentType()) {
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001036 QualType FromRecordType = From->getType();
1037 QualType DestRecordType = DestType;
1038 if (FromRecordType->getAsPointerType()) {
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001039 DestType = Context.getPointerType(DestType);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001040 FromRecordType = FromRecordType->getPointeeType();
1041 }
1042 if (IsDerivedFrom(FromRecordType, DestRecordType) &&
1043 CheckDerivedToBaseConversion(FromRecordType,
1044 DestRecordType,
1045 From->getSourceRange().getBegin(),
1046 From->getSourceRange()))
1047 return true;
1048
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001049 ImpCastExprToType(From, DestType, /*isLvalue=*/true);
1050 }
1051 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001052 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001053}
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001054
1055/// \brief Complete semantic analysis for a reference to the given declaration.
1056Sema::OwningExprResult
1057Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
1058 bool HasTrailingLParen,
1059 const CXXScopeSpec *SS,
1060 bool isAddressOfOperand) {
1061 assert(D && "Cannot refer to a NULL declaration");
1062 DeclarationName Name = D->getDeclName();
1063
Sebastian Redl0c9da212009-02-03 20:19:35 +00001064 // If this is an expression of the form &Class::member, don't build an
1065 // implicit member ref, because we want a pointer to the member in general,
1066 // not any specific instance's member.
1067 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001068 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +00001069 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +00001070 QualType DType;
1071 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1072 DType = FD->getType().getNonReferenceType();
1073 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1074 DType = Method->getType();
1075 } else if (isa<OverloadedFunctionDecl>(D)) {
1076 DType = Context.OverloadTy;
1077 }
1078 // Could be an inner type. That's diagnosed below, so ignore it here.
1079 if (!DType.isNull()) {
1080 // The pointer is type- and value-dependent if it points into something
1081 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +00001082 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +00001083 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +00001084 }
1085 }
1086 }
1087
Douglas Gregor723d3332009-01-07 00:43:41 +00001088 // We may have found a field within an anonymous union or struct
1089 // (C++ [class.union]).
1090 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
1091 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1092 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001093
Douglas Gregor3257fb52008-12-22 05:46:06 +00001094 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1095 if (!MD->isStatic()) {
1096 // C++ [class.mfct.nonstatic]p2:
1097 // [...] if name lookup (3.4.1) resolves the name in the
1098 // id-expression to a nonstatic nontype member of class X or of
1099 // a base class of X, the id-expression is transformed into a
1100 // class member access expression (5.2.5) using (*this) (9.3.2)
1101 // as the postfix-expression to the left of the '.' operator.
1102 DeclContext *Ctx = 0;
1103 QualType MemberType;
1104 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1105 Ctx = FD->getDeclContext();
1106 MemberType = FD->getType();
1107
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001108 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
Douglas Gregor3257fb52008-12-22 05:46:06 +00001109 MemberType = RefType->getPointeeType();
1110 else if (!FD->isMutable()) {
1111 unsigned combinedQualifiers
1112 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
1113 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1114 }
1115 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1116 if (!Method->isStatic()) {
1117 Ctx = Method->getParent();
1118 MemberType = Method->getType();
1119 }
1120 } else if (OverloadedFunctionDecl *Ovl
1121 = dyn_cast<OverloadedFunctionDecl>(D)) {
1122 for (OverloadedFunctionDecl::function_iterator
1123 Func = Ovl->function_begin(),
1124 FuncEnd = Ovl->function_end();
1125 Func != FuncEnd; ++Func) {
1126 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1127 if (!DMethod->isStatic()) {
1128 Ctx = Ovl->getDeclContext();
1129 MemberType = Context.OverloadTy;
1130 break;
1131 }
1132 }
1133 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001134
1135 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001136 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1137 QualType ThisType = Context.getTagDeclType(MD->getParent());
1138 if ((Context.getCanonicalType(CtxType)
1139 == Context.getCanonicalType(ThisType)) ||
1140 IsDerivedFrom(ThisType, CtxType)) {
1141 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001142 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001143 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001144 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001145 if (PerformObjectMemberConversion(This, D))
1146 return ExprError();
Douglas Gregor09be81b2009-02-04 17:27:36 +00001147 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001148 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001149 }
1150 }
1151 }
1152 }
1153
Douglas Gregor8acb7272008-12-11 16:49:14 +00001154 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001155 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1156 if (MD->isStatic())
1157 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001158 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1159 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001160 }
1161
Douglas Gregor3257fb52008-12-22 05:46:06 +00001162 // Any other ways we could have found the field in a well-formed
1163 // program would have been turned into implicit member expressions
1164 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001165 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1166 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001167 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001168
Chris Lattner4b009652007-07-25 00:24:17 +00001169 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001170 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001171 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001173 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001174 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001175
Steve Naroffd6163f32008-09-05 22:11:13 +00001176 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001177 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001178 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1179 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001180 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001181 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1182 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001183 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001184
Douglas Gregoraa57e862009-02-18 21:56:37 +00001185 // Check whether this declaration can be used. Note that we suppress
1186 // this check when we're going to perform argument-dependent lookup
1187 // on this function name, because this might not be the function
1188 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001189 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1190 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001191 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1192 return ExprError();
1193
Steve Naroffd6163f32008-09-05 22:11:13 +00001194 // Only create DeclRefExpr's for valid Decl's.
1195 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001196 return ExprError();
1197
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001198 // If the identifier reference is inside a block, and it refers to a value
1199 // that is outside the block, create a BlockDeclRefExpr instead of a
1200 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1201 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001202 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001203 // We do not do this for things like enum constants, global variables, etc,
1204 // as they do not get snapshotted.
1205 //
1206 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001207 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001208 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001209 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001210 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001211 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001212 // This is to record that a 'const' was actually synthesize and added.
1213 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001214 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001215
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001216 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001217 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1218 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001219 }
1220 // If this reference is not in a block or if the referenced variable is
1221 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001222
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001223 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001224 bool ValueDependent = false;
1225 if (getLangOptions().CPlusPlus) {
1226 // C++ [temp.dep.expr]p3:
1227 // An id-expression is type-dependent if it contains:
1228 // - an identifier that was declared with a dependent type,
1229 if (VD->getType()->isDependentType())
1230 TypeDependent = true;
1231 // - FIXME: a template-id that is dependent,
1232 // - a conversion-function-id that specifies a dependent type,
1233 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1234 Name.getCXXNameType()->isDependentType())
1235 TypeDependent = true;
1236 // - a nested-name-specifier that contains a class-name that
1237 // names a dependent type.
1238 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001239 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001240 DC; DC = DC->getParent()) {
1241 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001242 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001243 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1244 if (Context.getTypeDeclType(Record)->isDependentType()) {
1245 TypeDependent = true;
1246 break;
1247 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001248 }
1249 }
1250 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001251
Douglas Gregora5d84612008-12-10 20:57:37 +00001252 // C++ [temp.dep.constexpr]p2:
1253 //
1254 // An identifier is value-dependent if it is:
1255 // - a name declared with a dependent type,
1256 if (TypeDependent)
1257 ValueDependent = true;
1258 // - the name of a non-type template parameter,
1259 else if (isa<NonTypeTemplateParmDecl>(VD))
1260 ValueDependent = true;
1261 // - a constant with integral or enumeration type and is
1262 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001263 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1264 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1265 Dcl->getInit()) {
1266 ValueDependent = Dcl->getInit()->isValueDependent();
1267 }
1268 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001269 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001270
Anders Carlsson4571d812009-06-24 00:10:43 +00001271 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1272 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001273}
1274
Sebastian Redlcd883f72009-01-18 18:53:16 +00001275Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1276 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001277 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001278
Chris Lattner4b009652007-07-25 00:24:17 +00001279 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001280 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001281 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1282 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1283 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001284 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001285
Chris Lattner7e637512008-01-12 08:14:25 +00001286 // Pre-defined identifiers are of type char[x], where x is the length of the
1287 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001288 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001289 if (FunctionDecl *FD = getCurFunctionDecl())
1290 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001291 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1292 Length = MD->getSynthesizedMethodSize();
1293 else {
1294 Diag(Loc, diag::ext_predef_outside_function);
1295 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1296 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1297 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001298
1299
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001300 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001301 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001302 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001303 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001304}
1305
Sebastian Redlcd883f72009-01-18 18:53:16 +00001306Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001307 llvm::SmallString<16> CharBuffer;
1308 CharBuffer.resize(Tok.getLength());
1309 const char *ThisTokBegin = &CharBuffer[0];
1310 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001311
Chris Lattner4b009652007-07-25 00:24:17 +00001312 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1313 Tok.getLocation(), PP);
1314 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001315 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001316
1317 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1318
Sebastian Redl75324932009-01-20 22:23:13 +00001319 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1320 Literal.isWide(),
1321 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001322}
1323
Sebastian Redlcd883f72009-01-18 18:53:16 +00001324Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1325 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001326 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1327 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001328 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001329 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001330 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001331 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001332 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001333
Chris Lattner4b009652007-07-25 00:24:17 +00001334 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001335 // Add padding so that NumericLiteralParser can overread by one character.
1336 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001337 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001338
Chris Lattner4b009652007-07-25 00:24:17 +00001339 // Get the spelling of the token, which eliminates trigraphs, etc.
1340 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001341
Chris Lattner4b009652007-07-25 00:24:17 +00001342 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1343 Tok.getLocation(), PP);
1344 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001345 return ExprError();
1346
Chris Lattner1de66eb2007-08-26 03:42:43 +00001347 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001348
Chris Lattner1de66eb2007-08-26 03:42:43 +00001349 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001350 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001351 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001352 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001353 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001354 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001355 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001356 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001357
1358 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1359
Ted Kremenekddedbe22007-11-29 00:56:49 +00001360 // isExact will be set by GetFloatValue().
1361 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001362 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1363 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001364
Chris Lattner1de66eb2007-08-26 03:42:43 +00001365 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001366 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001367 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001368 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001369
Neil Booth7421e9c2007-08-29 22:00:19 +00001370 // long long is a C99 feature.
1371 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001372 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001373 Diag(Tok.getLocation(), diag::ext_longlong);
1374
Chris Lattner4b009652007-07-25 00:24:17 +00001375 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001376 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001377
Chris Lattner4b009652007-07-25 00:24:17 +00001378 if (Literal.GetIntegerValue(ResultVal)) {
1379 // If this value didn't fit into uintmax_t, warn and force to ull.
1380 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001381 Ty = Context.UnsignedLongLongTy;
1382 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001383 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001384 } else {
1385 // If this value fits into a ULL, try to figure out what else it fits into
1386 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001387
Chris Lattner4b009652007-07-25 00:24:17 +00001388 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1389 // be an unsigned int.
1390 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1391
1392 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001393 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001394 if (!Literal.isLong && !Literal.isLongLong) {
1395 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001396 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001397
Chris Lattner4b009652007-07-25 00:24:17 +00001398 // Does it fit in a unsigned int?
1399 if (ResultVal.isIntN(IntSize)) {
1400 // Does it fit in a signed int?
1401 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001402 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001403 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001404 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001405 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001406 }
Chris Lattner4b009652007-07-25 00:24:17 +00001407 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001408
Chris Lattner4b009652007-07-25 00:24:17 +00001409 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001410 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001411 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001412
Chris Lattner4b009652007-07-25 00:24:17 +00001413 // Does it fit in a unsigned long?
1414 if (ResultVal.isIntN(LongSize)) {
1415 // Does it fit in a signed long?
1416 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001417 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001418 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001419 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001420 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001421 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001422 }
1423
Chris Lattner4b009652007-07-25 00:24:17 +00001424 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001425 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001426 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001427
Chris Lattner4b009652007-07-25 00:24:17 +00001428 // Does it fit in a unsigned long long?
1429 if (ResultVal.isIntN(LongLongSize)) {
1430 // Does it fit in a signed long long?
1431 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001432 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001433 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001434 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001435 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001436 }
1437 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001438
Chris Lattner4b009652007-07-25 00:24:17 +00001439 // If we still couldn't decide a type, we probably have something that
1440 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001441 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001442 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001443 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001444 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001445 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001446
Chris Lattnere4068872008-05-09 05:59:00 +00001447 if (ResultVal.getBitWidth() != Width)
1448 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001449 }
Sebastian Redl75324932009-01-20 22:23:13 +00001450 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001451 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001452
Chris Lattner1de66eb2007-08-26 03:42:43 +00001453 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1454 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001455 Res = new (Context) ImaginaryLiteral(Res,
1456 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001457
1458 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001459}
1460
Sebastian Redlcd883f72009-01-18 18:53:16 +00001461Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1462 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001463 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001464 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001465 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001466}
1467
1468/// The UsualUnaryConversions() function is *not* called by this routine.
1469/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001470bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001471 SourceLocation OpLoc,
1472 const SourceRange &ExprRange,
1473 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001474 if (exprType->isDependentType())
1475 return false;
1476
Chris Lattner4b009652007-07-25 00:24:17 +00001477 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001478 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001479 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001480 if (isSizeof)
1481 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1482 return false;
1483 }
1484
Chris Lattner95933c12009-04-24 00:30:45 +00001485 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001486 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001487 Diag(OpLoc, diag::ext_sizeof_void_type)
1488 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001489 return false;
1490 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001491
Chris Lattner95933c12009-04-24 00:30:45 +00001492 if (RequireCompleteType(OpLoc, exprType,
1493 isSizeof ? diag::err_sizeof_incomplete_type :
1494 diag::err_alignof_incomplete_type,
1495 ExprRange))
1496 return true;
1497
1498 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001499 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001500 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001501 << exprType << isSizeof << ExprRange;
1502 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001503 }
1504
Chris Lattner95933c12009-04-24 00:30:45 +00001505 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001506}
1507
Chris Lattner8d9f7962009-01-24 20:17:12 +00001508bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1509 const SourceRange &ExprRange) {
1510 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001511
Chris Lattner8d9f7962009-01-24 20:17:12 +00001512 // alignof decl is always ok.
1513 if (isa<DeclRefExpr>(E))
1514 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001515
1516 // Cannot know anything else if the expression is dependent.
1517 if (E->isTypeDependent())
1518 return false;
1519
Douglas Gregor531434b2009-05-02 02:18:30 +00001520 if (E->getBitField()) {
1521 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1522 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001523 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001524
1525 // Alignment of a field access is always okay, so long as it isn't a
1526 // bit-field.
1527 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001528 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001529 return false;
1530
Chris Lattner8d9f7962009-01-24 20:17:12 +00001531 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1532}
1533
Douglas Gregor396f1142009-03-13 21:01:28 +00001534/// \brief Build a sizeof or alignof expression given a type operand.
1535Action::OwningExprResult
1536Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1537 bool isSizeOf, SourceRange R) {
1538 if (T.isNull())
1539 return ExprError();
1540
1541 if (!T->isDependentType() &&
1542 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1543 return ExprError();
1544
1545 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1546 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1547 Context.getSizeType(), OpLoc,
1548 R.getEnd()));
1549}
1550
1551/// \brief Build a sizeof or alignof expression given an expression
1552/// operand.
1553Action::OwningExprResult
1554Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1555 bool isSizeOf, SourceRange R) {
1556 // Verify that the operand is valid.
1557 bool isInvalid = false;
1558 if (E->isTypeDependent()) {
1559 // Delay type-checking for type-dependent expressions.
1560 } else if (!isSizeOf) {
1561 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001562 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001563 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1564 isInvalid = true;
1565 } else {
1566 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1567 }
1568
1569 if (isInvalid)
1570 return ExprError();
1571
1572 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1573 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1574 Context.getSizeType(), OpLoc,
1575 R.getEnd()));
1576}
1577
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001578/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1579/// the same for @c alignof and @c __alignof
1580/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001581Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001582Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1583 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001584 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001585 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001586
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001587 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001588 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1589 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1590 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001591
Douglas Gregor396f1142009-03-13 21:01:28 +00001592 // Get the end location.
1593 Expr *ArgEx = (Expr *)TyOrEx;
1594 Action::OwningExprResult Result
1595 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1596
1597 if (Result.isInvalid())
1598 DeleteExpr(ArgEx);
1599
1600 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001601}
1602
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001603QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001604 if (V->isTypeDependent())
1605 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001606
Chris Lattnera16e42d2007-08-26 05:39:26 +00001607 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001608 if (const ComplexType *CT = V->getType()->getAsComplexType())
1609 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001610
1611 // Otherwise they pass through real integer and floating point types here.
1612 if (V->getType()->isArithmeticType())
1613 return V->getType();
1614
1615 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001616 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1617 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001618 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001619}
1620
1621
Chris Lattner4b009652007-07-25 00:24:17 +00001622
Sebastian Redl8b769972009-01-19 00:08:26 +00001623Action::OwningExprResult
1624Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1625 tok::TokenKind Kind, ExprArg Input) {
1626 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001627
Chris Lattner4b009652007-07-25 00:24:17 +00001628 UnaryOperator::Opcode Opc;
1629 switch (Kind) {
1630 default: assert(0 && "Unknown unary op!");
1631 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1632 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1633 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001634
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001635 if (getLangOptions().CPlusPlus &&
1636 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1637 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001638 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001639 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1640
1641 // C++ [over.inc]p1:
1642 //
1643 // [...] If the function is a member function with one
1644 // parameter (which shall be of type int) or a non-member
1645 // function with two parameters (the second of which shall be
1646 // of type int), it defines the postfix increment operator ++
1647 // for objects of that type. When the postfix increment is
1648 // called as a result of using the ++ operator, the int
1649 // argument will have value zero.
1650 Expr *Args[2] = {
1651 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001652 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1653 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001654 };
1655
1656 // Build the candidate set for overloading
1657 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001658 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001659
1660 // Perform overload resolution.
1661 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001662 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001663 case OR_Success: {
1664 // We found a built-in operator or an overloaded operator.
1665 FunctionDecl *FnDecl = Best->Function;
1666
1667 if (FnDecl) {
1668 // We matched an overloaded operator. Build a call to that
1669 // operator.
1670
1671 // Convert the arguments.
1672 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1673 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001675 } else {
1676 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001677 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001678 FnDecl->getParamDecl(0)->getType(),
1679 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001680 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001681 }
1682
1683 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001685 = FnDecl->getType()->getAsFunctionType()->getResultType();
1686 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001687
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001688 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001689 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001690 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001691 UsualUnaryConversions(FnExpr);
1692
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001694 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001695 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1696 Args, 2, ResultTy,
1697 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001698 } else {
1699 // We matched a built-in operator. Convert the arguments, then
1700 // break out so that we will build the appropriate built-in
1701 // operator node.
1702 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1703 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001704 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001705
1706 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001707 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001708 }
1709
1710 case OR_No_Viable_Function:
1711 // No viable function; fall through to handling this as a
1712 // built-in operator, which will produce an error message for us.
1713 break;
1714
1715 case OR_Ambiguous:
1716 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1717 << UnaryOperator::getOpcodeStr(Opc)
1718 << Arg->getSourceRange();
1719 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001720 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001721
1722 case OR_Deleted:
1723 Diag(OpLoc, diag::err_ovl_deleted_oper)
1724 << Best->Function->isDeleted()
1725 << UnaryOperator::getOpcodeStr(Opc)
1726 << Arg->getSourceRange();
1727 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1728 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001729 }
1730
1731 // Either we found no viable overloaded operator or we matched a
1732 // built-in operator. In either case, fall through to trying to
1733 // build a built-in operation.
1734 }
1735
Eli Friedman94d30952009-07-22 23:24:42 +00001736 Input.release();
1737 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001738 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001739}
1740
Sebastian Redl8b769972009-01-19 00:08:26 +00001741Action::OwningExprResult
1742Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1743 ExprArg Idx, SourceLocation RLoc) {
1744 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1745 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001746
Douglas Gregor80723c52008-11-19 17:17:41 +00001747 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001748 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1749 Base.release();
1750 Idx.release();
1751 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1752 Context.DependentTy, RLoc));
1753 }
1754
1755 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001756 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001757 LHSExp->getType()->isEnumeralType() ||
1758 RHSExp->getType()->isRecordType() ||
1759 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001760 // Add the appropriate overloaded operators (C++ [over.match.oper])
1761 // to the candidate set.
1762 OverloadCandidateSet CandidateSet;
1763 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001764 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1765 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001766
Douglas Gregor80723c52008-11-19 17:17:41 +00001767 // Perform overload resolution.
1768 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001769 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001770 case OR_Success: {
1771 // We found a built-in operator or an overloaded operator.
1772 FunctionDecl *FnDecl = Best->Function;
1773
1774 if (FnDecl) {
1775 // We matched an overloaded operator. Build a call to that
1776 // operator.
1777
1778 // Convert the arguments.
1779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1780 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1781 PerformCopyInitialization(RHSExp,
1782 FnDecl->getParamDecl(0)->getType(),
1783 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001784 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001785 } else {
1786 // Convert the arguments.
1787 if (PerformCopyInitialization(LHSExp,
1788 FnDecl->getParamDecl(0)->getType(),
1789 "passing") ||
1790 PerformCopyInitialization(RHSExp,
1791 FnDecl->getParamDecl(1)->getType(),
1792 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001793 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001794 }
1795
1796 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001798 = FnDecl->getType()->getAsFunctionType()->getResultType();
1799 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001800
Douglas Gregor80723c52008-11-19 17:17:41 +00001801 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001802 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1803 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001804 UsualUnaryConversions(FnExpr);
1805
Sebastian Redl8b769972009-01-19 00:08:26 +00001806 Base.release();
1807 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001808 Args[0] = LHSExp;
1809 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001810 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1811 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001812 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001813 } else {
1814 // We matched a built-in operator. Convert the arguments, then
1815 // break out so that we will build the appropriate built-in
1816 // operator node.
1817 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1818 "passing") ||
1819 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1820 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001822
1823 break;
1824 }
1825 }
1826
1827 case OR_No_Viable_Function:
1828 // No viable function; fall through to handling this as a
1829 // built-in operator, which will produce an error message for us.
1830 break;
1831
1832 case OR_Ambiguous:
1833 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1834 << "[]"
1835 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1836 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001837 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001838
1839 case OR_Deleted:
1840 Diag(LLoc, diag::err_ovl_deleted_oper)
1841 << Best->Function->isDeleted()
1842 << "[]"
1843 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1844 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1845 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001846 }
1847
1848 // Either we found no viable overloaded operator or we matched a
1849 // built-in operator. In either case, fall through to trying to
1850 // build a built-in operation.
1851 }
1852
Chris Lattner4b009652007-07-25 00:24:17 +00001853 // Perform default conversions.
1854 DefaultFunctionArrayConversion(LHSExp);
1855 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001856
Chris Lattner4b009652007-07-25 00:24:17 +00001857 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1858
1859 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001860 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001861 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001862 // and index from the expression types.
1863 Expr *BaseExpr, *IndexExpr;
1864 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001865 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1866 BaseExpr = LHSExp;
1867 IndexExpr = RHSExp;
1868 ResultType = Context.DependentTy;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001869 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001870 BaseExpr = LHSExp;
1871 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001872 ResultType = PTy->getPointeeType();
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001873 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001874 // Handle the uncommon case of "123[Ptr]".
1875 BaseExpr = RHSExp;
1876 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001877 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001878 } else if (const ObjCObjectPointerType *PTy =
1879 LHSTy->getAsObjCObjectPointerType()) {
1880 BaseExpr = LHSExp;
1881 IndexExpr = RHSExp;
1882 ResultType = PTy->getPointeeType();
1883 } else if (const ObjCObjectPointerType *PTy =
1884 RHSTy->getAsObjCObjectPointerType()) {
1885 // Handle the uncommon case of "123[Ptr]".
1886 BaseExpr = RHSExp;
1887 IndexExpr = LHSExp;
1888 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001889 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1890 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001891 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001892
Chris Lattner4b009652007-07-25 00:24:17 +00001893 // FIXME: need to deal with const...
1894 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001895 } else if (LHSTy->isArrayType()) {
1896 // If we see an array that wasn't promoted by
1897 // DefaultFunctionArrayConversion, it must be an array that
1898 // wasn't promoted because of the C90 rule that doesn't
1899 // allow promoting non-lvalue arrays. Warn, then
1900 // force the promotion here.
1901 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1902 LHSExp->getSourceRange();
1903 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1904 LHSTy = LHSExp->getType();
1905
1906 BaseExpr = LHSExp;
1907 IndexExpr = RHSExp;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001908 ResultType = LHSTy->getAsPointerType()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001909 } else if (RHSTy->isArrayType()) {
1910 // Same as previous, except for 123[f().a] case
1911 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1912 RHSExp->getSourceRange();
1913 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1914 RHSTy = RHSExp->getType();
1915
1916 BaseExpr = RHSExp;
1917 IndexExpr = LHSExp;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001918 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001919 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001920 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1921 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001922 }
Chris Lattner4b009652007-07-25 00:24:17 +00001923 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001924 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001925 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1926 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001927
Douglas Gregor05e28f62009-03-24 19:52:54 +00001928 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1929 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1930 // type. Note that Functions are not objects, and that (in C99 parlance)
1931 // incomplete types are not object types.
1932 if (ResultType->isFunctionType()) {
1933 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1934 << ResultType << BaseExpr->getSourceRange();
1935 return ExprError();
1936 }
Chris Lattner95933c12009-04-24 00:30:45 +00001937
Douglas Gregor05e28f62009-03-24 19:52:54 +00001938 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001939 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001940 BaseExpr->getSourceRange()))
1941 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001942
1943 // Diagnose bad cases where we step over interface counts.
1944 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1945 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1946 << ResultType << BaseExpr->getSourceRange();
1947 return ExprError();
1948 }
1949
Sebastian Redl8b769972009-01-19 00:08:26 +00001950 Base.release();
1951 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001952 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001953 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001954}
1955
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001956QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001957CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001958 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001959 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001960
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001961 // The vector accessor can't exceed the number of elements.
1962 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001963
Mike Stump9afab102009-02-19 03:04:26 +00001964 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001965 // special names that indicate a subset of exactly half the elements are
1966 // to be selected.
1967 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001968
Nate Begeman1486b502009-01-18 01:47:54 +00001969 // This flag determines whether or not CompName has an 's' char prefix,
1970 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001971 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001972
1973 // Check that we've found one of the special components, or that the component
1974 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001975 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001976 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1977 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001978 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001979 do
1980 compStr++;
1981 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001982 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001983 do
1984 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001985 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001986 }
Nate Begeman1486b502009-01-18 01:47:54 +00001987
Mike Stump9afab102009-02-19 03:04:26 +00001988 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001989 // We didn't get to the end of the string. This means the component names
1990 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001991 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1992 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001993 return QualType();
1994 }
Mike Stump9afab102009-02-19 03:04:26 +00001995
Nate Begeman1486b502009-01-18 01:47:54 +00001996 // Ensure no component accessor exceeds the width of the vector type it
1997 // operates on.
1998 if (!HalvingSwizzle) {
1999 compStr = CompName.getName();
2000
2001 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002002 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00002003
2004 while (*compStr) {
2005 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2006 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2007 << baseType << SourceRange(CompLoc);
2008 return QualType();
2009 }
2010 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002011 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00002012
Nate Begeman1486b502009-01-18 01:47:54 +00002013 // If this is a halving swizzle, verify that the base type has an even
2014 // number of elements.
2015 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002016 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002017 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00002018 return QualType();
2019 }
Mike Stump9afab102009-02-19 03:04:26 +00002020
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002021 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00002022 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002023 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00002024 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00002025 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00002026 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
2027 : CompName.getLength();
2028 if (HexSwizzle)
2029 CompSize--;
2030
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002031 if (CompSize == 1)
2032 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002033
Nate Begemanaf6ed502008-04-18 23:10:10 +00002034 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00002035 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002036 // diagostics look bad. We want extended vector types to appear built-in.
2037 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2038 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2039 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00002040 }
2041 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002042}
2043
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002044static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2045 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002046 const Selector &Sel,
2047 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002048
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002049 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002050 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002051 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002052 return OMD;
2053
2054 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2055 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002056 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2057 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002058 return D;
2059 }
2060 return 0;
2061}
2062
Steve Naroffc75c1a82009-06-17 22:40:22 +00002063static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002064 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002065 const Selector &Sel,
2066 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002067 // Check protocols on qualified interfaces.
2068 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00002069 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002070 E = QIdTy->qual_end(); I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002071 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002072 GDecl = PD;
2073 break;
2074 }
2075 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002076 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002077 GDecl = OMD;
2078 break;
2079 }
2080 }
2081 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00002082 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002083 E = QIdTy->qual_end(); I != E; ++I) {
2084 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002085 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002086 if (GDecl)
2087 return GDecl;
2088 }
2089 }
2090 return GDecl;
2091}
Chris Lattner2cb744b2009-02-15 22:43:40 +00002092
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002093/// FindMethodInNestedImplementations - Look up a method in current and
2094/// all base class implementations.
2095///
2096ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2097 const ObjCInterfaceDecl *IFace,
2098 const Selector &Sel) {
2099 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00002100 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002101 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002102
2103 if (!Method && IFace->getSuperClass())
2104 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2105 return Method;
2106}
2107
Sebastian Redl8b769972009-01-19 00:08:26 +00002108Action::OwningExprResult
2109Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2110 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002111 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00002112 DeclPtrTy ObjCImpDecl) {
Anders Carlssonc154a722009-05-01 19:30:39 +00002113 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002114 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00002115
2116 // Perform default conversions.
2117 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002118
Steve Naroff2cb66382007-07-26 03:11:44 +00002119 QualType BaseType = BaseExpr->getType();
2120 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002121
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002122 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2123 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002124 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002125 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002126 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2127 BaseExpr, true,
2128 OpLoc,
2129 DeclarationName(&Member),
2130 MemberLoc));
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002131 else if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00002132 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002133 else if (BaseType->isObjCObjectPointerType())
2134 ;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00002135 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00002136 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
2137 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00002138 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002139 return ExprError(Diag(MemberLoc,
2140 diag::err_typecheck_member_reference_arrow)
2141 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002142 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002143 if (BaseType->isDependentType()) {
2144 // Require that the base type isn't a pointer type
2145 // (so we'll report an error for)
2146 // T* t;
2147 // t.f;
2148 //
2149 // In Obj-C++, however, the above expression is valid, since it could be
2150 // accessing the 'f' property if T is an Obj-C interface. The extra check
2151 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002152 const PointerType *PT = BaseType->getAsPointerType();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002153
2154 if (!PT || (getLangOptions().ObjC1 &&
2155 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002156 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2157 BaseExpr, false,
2158 OpLoc,
2159 DeclarationName(&Member),
2160 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002161 }
Chris Lattner4b009652007-07-25 00:24:17 +00002162 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002163
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002164 // Handle field access to simple records. This also handles access to fields
2165 // of the ObjC 'id' struct.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002166 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002167 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002168 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002169 diag::err_typecheck_incomplete_tag,
2170 BaseExpr->getSourceRange()))
2171 return ExprError();
2172
Steve Naroff2cb66382007-07-26 03:11:44 +00002173 // The record definition is complete, now make sure the member is valid.
Mike Stumpe127ae32009-05-16 07:39:55 +00002174 // FIXME: Qualified name lookup for C++ is a bit more complicated than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00002175 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00002176 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002177 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002178
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002179 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002180 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2181 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002182 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002183 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2184 MemberLoc, BaseExpr->getSourceRange());
2185 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002186 }
2187
2188 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002189
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002190 // If the decl being referenced had an error, return an error for this
2191 // sub-expr without emitting another error, in order to avoid cascading
2192 // error cases.
2193 if (MemberDecl->isInvalidDecl())
2194 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002195
Douglas Gregoraa57e862009-02-18 21:56:37 +00002196 // Check the use of this field
2197 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2198 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002199
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002200 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002201 // We may have found a field within an anonymous union or struct
2202 // (C++ [class.union]).
2203 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002204 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002205 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002206
Douglas Gregor82d44772008-12-20 23:49:58 +00002207 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002208 QualType MemberType = FD->getType();
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002209 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
Douglas Gregor82d44772008-12-20 23:49:58 +00002210 MemberType = Ref->getPointeeType();
2211 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002212 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002213 unsigned combinedQualifiers =
2214 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002215 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002216 combinedQualifiers &= ~QualType::Const;
2217 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002218 if (BaseAddrSpace != MemberType.getAddressSpace())
2219 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002220 }
Eli Friedman76b49832008-02-06 22:48:16 +00002221
Douglas Gregorcad27f62009-06-22 23:06:13 +00002222 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002223 if (PerformObjectMemberConversion(BaseExpr, FD))
2224 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002225 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2226 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002227 }
2228
Douglas Gregorcad27f62009-06-22 23:06:13 +00002229 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2230 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Steve Naroff774e4152009-01-21 00:14:39 +00002231 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002232 Var, MemberLoc,
2233 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002234 }
2235 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2236 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002237 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002238 MemberFn, MemberLoc,
2239 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002240 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002241 if (OverloadedFunctionDecl *Ovl
2242 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002243 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002244 MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002245 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2246 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002247 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2248 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002249 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002250 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002251 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2252 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002253
Douglas Gregor82d44772008-12-20 23:49:58 +00002254 // We found a declaration kind that we didn't expect. This is a
2255 // generic error message that tells the user that she can't refer
2256 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002257 return ExprError(Diag(MemberLoc,
2258 diag::err_typecheck_member_reference_unknown)
2259 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002260 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002261
Steve Naroff329ec222009-07-10 23:34:53 +00002262 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002263 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002264 // Also must look for a getter name which uses property syntax.
2265 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2266 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2267 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2268 ObjCMethodDecl *Getter;
2269 // FIXME: need to also look locally in the implementation.
2270 if ((Getter = IFace->lookupClassMethod(Sel))) {
2271 // Check the use of this method.
2272 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2273 return ExprError();
2274 }
2275 // If we found a getter then this may be a valid dot-reference, we
2276 // will look for the matching setter, in case it is needed.
2277 Selector SetterSel =
2278 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2279 PP.getSelectorTable(), &Member);
2280 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2281 if (!Setter) {
2282 // If this reference is in an @implementation, also check for 'private'
2283 // methods.
2284 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2285 }
2286 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002287 if (!Setter)
2288 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002289
2290 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2291 return ExprError();
2292
2293 if (Getter || Setter) {
2294 QualType PType;
2295
2296 if (Getter)
2297 PType = Getter->getResultType();
2298 else {
2299 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2300 E = Setter->param_end(); PI != E; ++PI)
2301 PType = (*PI)->getType();
2302 }
2303 // FIXME: we must check that the setter has property type.
2304 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2305 Setter, MemberLoc, BaseExpr));
2306 }
2307 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2308 << &Member << BaseType);
2309 }
2310 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002311 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2312 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002313 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2314 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2315 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2316 const ObjCInterfaceType *IFaceT =
2317 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002318 if (IFaceT) {
2319 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2320 ObjCInterfaceDecl *ClassDeclared;
2321 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(&Member, ClassDeclared);
2322
2323 if (IV) {
2324 // If the decl being referenced had an error, return an error for this
2325 // sub-expr without emitting another error, in order to avoid cascading
2326 // error cases.
2327 if (IV->isInvalidDecl())
2328 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002329
Steve Naroff4e743962009-07-16 00:25:06 +00002330 // Check whether we can reference this field.
2331 if (DiagnoseUseOfDecl(IV, MemberLoc))
2332 return ExprError();
2333 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2334 IV->getAccessControl() != ObjCIvarDecl::Package) {
2335 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2336 if (ObjCMethodDecl *MD = getCurMethodDecl())
2337 ClassOfMethodDecl = MD->getClassInterface();
2338 else if (ObjCImpDecl && getCurFunctionDecl()) {
2339 // Case of a c-function declared inside an objc implementation.
2340 // FIXME: For a c-style function nested inside an objc implementation
2341 // class, there is no implementation context available, so we pass
2342 // down the context as argument to this routine. Ideally, this context
2343 // need be passed down in the AST node and somehow calculated from the
2344 // AST for a function decl.
2345 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2346 if (ObjCImplementationDecl *IMPD =
2347 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2348 ClassOfMethodDecl = IMPD->getClassInterface();
2349 else if (ObjCCategoryImplDecl* CatImplClass =
2350 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2351 ClassOfMethodDecl = CatImplClass->getClassInterface();
2352 }
2353
2354 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2355 if (ClassDeclared != IDecl ||
2356 ClassOfMethodDecl != ClassDeclared)
2357 Diag(MemberLoc, diag::error_private_ivar_access)
2358 << IV->getDeclName();
2359 }
2360 // @protected
2361 else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2362 Diag(MemberLoc, diag::error_protected_ivar_access)
2363 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002364 }
Steve Naroff4e743962009-07-16 00:25:06 +00002365
2366 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2367 MemberLoc, BaseExpr,
2368 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002369 }
Steve Naroff4e743962009-07-16 00:25:06 +00002370 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2371 << IDecl->getDeclName() << &Member
2372 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002373 }
Steve Naroff29d293b2009-07-24 17:54:45 +00002374 // We have an 'id' type. Rather than fall through, we check if this
2375 // is a reference to 'isa'.
Steve Naroffbbe4f962009-07-29 14:06:03 +00002376 if (Member.isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002377 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2378 Context.getObjCIdType()));
Chris Lattnera57cf472008-07-21 04:28:12 +00002379 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002380 // Handle properties on 'id' and qualified "id".
2381 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2382 BaseType->isObjCQualifiedIdType())) {
2383 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2384
Steve Naroff329ec222009-07-10 23:34:53 +00002385 // Check protocols on qualified interfaces.
2386 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2387 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2388 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2389 // Check the use of this declaration
2390 if (DiagnoseUseOfDecl(PD, MemberLoc))
2391 return ExprError();
2392
2393 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2394 MemberLoc, BaseExpr));
2395 }
2396 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2397 // Check the use of this method.
2398 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2399 return ExprError();
2400
2401 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2402 OMD->getResultType(),
2403 OMD, OpLoc, MemberLoc,
2404 NULL, 0));
2405 }
2406 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002407
Steve Naroff329ec222009-07-10 23:34:53 +00002408 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2409 << &Member << BaseType);
2410 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002411 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2412 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002413 const ObjCObjectPointerType *OPT;
2414 if (OpKind == tok::period &&
2415 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2416 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2417 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2418
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002419 // Search for a declared property first.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002420 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002421 // Check whether we can reference this property.
2422 if (DiagnoseUseOfDecl(PD, MemberLoc))
2423 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002424 QualType ResTy = PD->getType();
2425 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002426 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002427 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2428 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002429 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002430 MemberLoc, BaseExpr));
2431 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002432 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002433 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2434 E = OPT->qual_end(); I != E; ++I)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002435 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002436 // Check whether we can reference this property.
2437 if (DiagnoseUseOfDecl(PD, MemberLoc))
2438 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002439
Steve Naroff774e4152009-01-21 00:14:39 +00002440 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002441 MemberLoc, BaseExpr));
2442 }
Steve Naroff329ec222009-07-10 23:34:53 +00002443 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2444 E = OPT->qual_end(); I != E; ++I)
2445 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2446 // Check whether we can reference this property.
2447 if (DiagnoseUseOfDecl(PD, MemberLoc))
2448 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002449
Steve Naroff329ec222009-07-10 23:34:53 +00002450 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2451 MemberLoc, BaseExpr));
2452 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002453 // If that failed, look for an "implicit" property by seeing if the nullary
2454 // selector is implemented.
2455
2456 // FIXME: The logic for looking up nullary and unary selectors should be
2457 // shared with the code in ActOnInstanceMessage.
2458
2459 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002460 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002461
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002462 // If this reference is in an @implementation, check for 'private' methods.
2463 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002464 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002465
Steve Naroff04151f32008-10-22 19:16:27 +00002466 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002467 if (!Getter)
2468 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002469 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002470 // Check if we can reference this property.
2471 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2472 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002473 }
2474 // If we found a getter then this may be a valid dot-reference, we
2475 // will look for the matching setter, in case it is needed.
2476 Selector SetterSel =
2477 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2478 PP.getSelectorTable(), &Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002479 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002480 if (!Setter) {
2481 // If this reference is in an @implementation, also check for 'private'
2482 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002483 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002484 }
2485 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002486 if (!Setter)
2487 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002488
Steve Naroffdede0c92009-03-11 13:48:17 +00002489 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2490 return ExprError();
2491
2492 if (Getter || Setter) {
2493 QualType PType;
2494
2495 if (Getter)
2496 PType = Getter->getResultType();
2497 else {
2498 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2499 E = Setter->param_end(); PI != E; ++PI)
2500 PType = (*PI)->getType();
2501 }
2502 // FIXME: we must check that the setter has property type.
2503 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2504 Setter, MemberLoc, BaseExpr));
2505 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002506 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2507 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002508 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002509
Steve Naroff29d293b2009-07-24 17:54:45 +00002510 // Handle the following exceptional case (*Obj).isa.
2511 if (OpKind == tok::period &&
2512 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Steve Naroffbbe4f962009-07-29 14:06:03 +00002513 Member.isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002514 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2515 Context.getObjCIdType()));
2516
Chris Lattnera57cf472008-07-21 04:28:12 +00002517 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002518 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002519 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2520 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002521 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002522 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002523 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002524 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002525
Douglas Gregor762da552009-03-27 06:00:30 +00002526 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2527 << BaseType << BaseExpr->getSourceRange();
2528
2529 // If the user is trying to apply -> or . to a function or function
2530 // pointer, it's probably because they forgot parentheses to call
2531 // the function. Suggest the addition of those parentheses.
2532 if (BaseType == Context.OverloadTy ||
2533 BaseType->isFunctionType() ||
2534 (BaseType->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002535 BaseType->getAsPointerType()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002536 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2537 Diag(Loc, diag::note_member_reference_needs_call)
2538 << CodeModificationHint::CreateInsertion(Loc, "()");
2539 }
2540
2541 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002542}
2543
Douglas Gregor3257fb52008-12-22 05:46:06 +00002544/// ConvertArgumentsForCall - Converts the arguments specified in
2545/// Args/NumArgs to the parameter types of the function FDecl with
2546/// function prototype Proto. Call is the call expression itself, and
2547/// Fn is the function expression. For a C++ member function, this
2548/// routine does not attempt to convert the object argument. Returns
2549/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002550bool
2551Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002552 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002553 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002554 Expr **Args, unsigned NumArgs,
2555 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002556 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002557 // assignment, to the types of the corresponding parameter, ...
2558 unsigned NumArgsInProto = Proto->getNumArgs();
2559 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002560 bool Invalid = false;
2561
Douglas Gregor3257fb52008-12-22 05:46:06 +00002562 // If too few arguments are available (and we don't have default
2563 // arguments for the remaining parameters), don't make the call.
2564 if (NumArgs < NumArgsInProto) {
2565 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2566 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2567 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2568 // Use default arguments for missing arguments
2569 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002570 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002571 }
2572
2573 // If too many are passed and not variadic, error on the extras and drop
2574 // them.
2575 if (NumArgs > NumArgsInProto) {
2576 if (!Proto->isVariadic()) {
2577 Diag(Args[NumArgsInProto]->getLocStart(),
2578 diag::err_typecheck_call_too_many_args)
2579 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2580 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2581 Args[NumArgs-1]->getLocEnd());
2582 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002583 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002584 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002585 }
2586 NumArgsToCheck = NumArgsInProto;
2587 }
Mike Stump9afab102009-02-19 03:04:26 +00002588
Douglas Gregor3257fb52008-12-22 05:46:06 +00002589 // Continue to check argument types (even if we have too few/many args).
2590 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2591 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002592
Douglas Gregor3257fb52008-12-22 05:46:06 +00002593 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002594 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002595 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002596
Eli Friedman83dec9e2009-03-22 22:00:50 +00002597 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2598 ProtoArgType,
2599 diag::err_call_incomplete_argument,
2600 Arg->getSourceRange()))
2601 return true;
2602
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002603 // Pass the argument.
2604 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2605 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002606 } else {
2607 if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2608 Diag (Call->getSourceRange().getBegin(),
2609 diag::err_use_of_default_argument_to_function_declared_later) <<
2610 FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2611 Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2612 diag::note_default_argument_declared_here);
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002613 } else {
2614 Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2615
2616 // If the default expression creates temporaries, we need to
2617 // push them to the current stack of expression temporaries so they'll
2618 // be properly destroyed.
2619 if (CXXExprWithTemporaries *E
2620 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2621 assert(!E->shouldDestroyTemporaries() &&
2622 "Can't destroy temporaries in a default argument expr!");
2623 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2624 ExprTemporaries.push_back(E->getTemporary(I));
2625 }
Anders Carlssona116e6e2009-06-12 16:51:40 +00002626 }
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002627
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002628 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002629 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Anders Carlssona116e6e2009-06-12 16:51:40 +00002630 }
2631
Douglas Gregor3257fb52008-12-22 05:46:06 +00002632 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002633
Douglas Gregor3257fb52008-12-22 05:46:06 +00002634 Call->setArg(i, Arg);
2635 }
Mike Stump9afab102009-02-19 03:04:26 +00002636
Douglas Gregor3257fb52008-12-22 05:46:06 +00002637 // If this is a variadic call, handle args passed through "...".
2638 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002639 VariadicCallType CallType = VariadicFunction;
2640 if (Fn->getType()->isBlockPointerType())
2641 CallType = VariadicBlock; // Block
2642 else if (isa<MemberExpr>(Fn))
2643 CallType = VariadicMethod;
2644
Douglas Gregor3257fb52008-12-22 05:46:06 +00002645 // Promote the arguments (C99 6.5.2.2p7).
2646 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2647 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002648 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002649 Call->setArg(i, Arg);
2650 }
2651 }
2652
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002653 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002654}
2655
Steve Naroff87d58b42007-09-16 03:34:24 +00002656/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002657/// This provides the location of the left/right parens and a list of comma
2658/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002659Action::OwningExprResult
2660Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2661 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002662 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002663 unsigned NumArgs = args.size();
Anders Carlssonc154a722009-05-01 19:30:39 +00002664 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002665 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002666 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002667 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002668 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002669 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002670
Douglas Gregor3257fb52008-12-22 05:46:06 +00002671 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002672 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002673 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002674 // FIXME: Will need to cache the results of name lookup (including ADL) in
2675 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002676 bool Dependent = false;
2677 if (Fn->isTypeDependent())
2678 Dependent = true;
2679 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2680 Dependent = true;
2681
2682 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002683 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002684 Context.DependentTy, RParenLoc));
2685
2686 // Determine whether this is a call to an object (C++ [over.call.object]).
2687 if (Fn->getType()->isRecordType())
2688 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2689 CommaLocs, RParenLoc));
2690
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002691 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002692 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2693 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2694 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2695 isa<CXXMethodDecl>(MemDecl) ||
2696 (isa<FunctionTemplateDecl>(MemDecl) &&
2697 isa<CXXMethodDecl>(
2698 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002699 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2700 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002701 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002702 }
2703
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002704 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002705 // Also, in C++, keep track of whether we should perform argument-dependent
2706 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002707 Expr *FnExpr = Fn;
2708 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002709 bool HasExplicitTemplateArgs = 0;
2710 const TemplateArgument *ExplicitTemplateArgs = 0;
2711 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002712 while (true) {
2713 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2714 FnExpr = IcExpr->getSubExpr();
2715 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002716 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002717 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002718 ADL = false;
2719 FnExpr = PExpr->getSubExpr();
2720 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002721 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002722 == UnaryOperator::AddrOf) {
2723 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002724 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002725 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2726 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002727 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002728 break;
Mike Stump9afab102009-02-19 03:04:26 +00002729 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002730 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2731 UnqualifiedName = DepName->getName();
2732 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002733 } else if (TemplateIdRefExpr *TemplateIdRef
2734 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2735 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002736 if (!NDecl)
2737 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002738 HasExplicitTemplateArgs = true;
2739 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2740 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2741
2742 // C++ [temp.arg.explicit]p6:
2743 // [Note: For simple function names, argument dependent lookup (3.4.2)
2744 // applies even when the function name is not visible within the
2745 // scope of the call. This is because the call still has the syntactic
2746 // form of a function call (3.4.1). But when a function template with
2747 // explicit template arguments is used, the call does not have the
2748 // correct syntactic form unless there is a function template with
2749 // that name visible at the point of the call. If no such name is
2750 // visible, the call is not syntactically well-formed and
2751 // argument-dependent lookup does not apply. If some such name is
2752 // visible, argument dependent lookup applies and additional function
2753 // templates may be found in other namespaces.
2754 //
2755 // The summary of this paragraph is that, if we get to this point and the
2756 // template-id was not a qualified name, then argument-dependent lookup
2757 // is still possible.
2758 if (TemplateIdRef->getQualifier())
2759 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002760 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002761 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002762 // Any kind of name that does not refer to a declaration (or
2763 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2764 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002765 break;
2766 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002767 }
Mike Stump9afab102009-02-19 03:04:26 +00002768
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002769 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002770 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002771 if (NDecl) {
2772 FDecl = dyn_cast<FunctionDecl>(NDecl);
2773 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002774 FDecl = FunctionTemplate->getTemplatedDecl();
2775 else
Douglas Gregor28857752009-06-30 22:34:41 +00002776 FDecl = dyn_cast<FunctionDecl>(NDecl);
2777 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002778 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002779
Douglas Gregorb60eb752009-06-25 22:08:12 +00002780 if (Ovl || FunctionTemplate ||
2781 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002782 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002783 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002784 ADL = false;
2785
Douglas Gregorfcb19192009-02-11 23:02:49 +00002786 // We don't perform ADL in C.
2787 if (!getLangOptions().CPlusPlus)
2788 ADL = false;
2789
Douglas Gregorb60eb752009-06-25 22:08:12 +00002790 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002791 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2792 HasExplicitTemplateArgs,
2793 ExplicitTemplateArgs,
2794 NumExplicitTemplateArgs,
2795 LParenLoc, Args, NumArgs, CommaLocs,
2796 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002797 if (!FDecl)
2798 return ExprError();
2799
2800 // Update Fn to refer to the actual function selected.
2801 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002802 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002803 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002804 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2805 QDRExpr->getLocation(),
2806 false, false,
2807 QDRExpr->getQualifierRange(),
2808 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002809 else
Mike Stump9afab102009-02-19 03:04:26 +00002810 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002811 Fn->getSourceRange().getBegin());
2812 Fn->Destroy(Context);
2813 Fn = NewFn;
2814 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002815 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002816
2817 // Promote the function operand.
2818 UsualUnaryConversions(Fn);
2819
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002820 // Make the call expr early, before semantic checks. This guarantees cleanup
2821 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002822 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2823 Args, NumArgs,
2824 Context.BoolTy,
2825 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002826
Steve Naroffd6163f32008-09-05 22:11:13 +00002827 const FunctionType *FuncT;
2828 if (!Fn->getType()->isBlockPointerType()) {
2829 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2830 // have type pointer to function".
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002831 const PointerType *PT = Fn->getType()->getAsPointerType();
Steve Naroffd6163f32008-09-05 22:11:13 +00002832 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002833 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2834 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002835 FuncT = PT->getPointeeType()->getAsFunctionType();
2836 } else { // This is a block call.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002837 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002838 getAsFunctionType();
2839 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002840 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002841 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2842 << Fn->getType() << Fn->getSourceRange());
2843
Eli Friedman83dec9e2009-03-22 22:00:50 +00002844 // Check for a valid return type
2845 if (!FuncT->getResultType()->isVoidType() &&
2846 RequireCompleteType(Fn->getSourceRange().getBegin(),
2847 FuncT->getResultType(),
2848 diag::err_call_incomplete_return,
2849 TheCall->getSourceRange()))
2850 return ExprError();
2851
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002852 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002853 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002854
Douglas Gregor4fa58902009-02-26 23:50:07 +00002855 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002856 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002857 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002858 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002859 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002860 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002861
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002862 if (FDecl) {
2863 // Check if we have too few/too many template arguments, based
2864 // on our knowledge of the function definition.
2865 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002866 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002867 const FunctionProtoType *Proto =
2868 Def->getType()->getAsFunctionProtoType();
2869 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2870 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2871 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2872 }
2873 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002874 }
2875
Steve Naroffdb65e052007-08-28 23:30:39 +00002876 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002877 for (unsigned i = 0; i != NumArgs; i++) {
2878 Expr *Arg = Args[i];
2879 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002880 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2881 Arg->getType(),
2882 diag::err_call_incomplete_argument,
2883 Arg->getSourceRange()))
2884 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002885 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002886 }
Chris Lattner4b009652007-07-25 00:24:17 +00002887 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002888
Douglas Gregor3257fb52008-12-22 05:46:06 +00002889 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2890 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002891 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2892 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002893
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002894 // Check for sentinels
2895 if (NDecl)
2896 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Chris Lattner2e64c072007-08-10 20:18:51 +00002897 // Do special checking on direct calls to functions.
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002898 if (FDecl)
Eli Friedmand0e9d092008-05-14 19:38:39 +00002899 return CheckFunctionCall(FDecl, TheCall.take());
Fariborz Jahanianf83c85f2009-05-18 21:05:18 +00002900 if (NDecl)
2901 return CheckBlockCall(NDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002902
Sebastian Redl8b769972009-01-19 00:08:26 +00002903 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002904}
2905
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002906Action::OwningExprResult
2907Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2908 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002909 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002910 QualType literalType = QualType::getFromOpaquePtr(Ty);
2911 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002912 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002913 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002914
Eli Friedman8c2173d2008-05-20 05:22:08 +00002915 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002916 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002917 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2918 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002919 } else if (!literalType->isDependentType() &&
2920 RequireCompleteType(LParenLoc, literalType,
2921 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002922 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002923 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002924
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002925 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002926 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002927 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002928
Chris Lattnere5cb5862008-12-04 23:50:19 +00002929 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002930 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002931 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002932 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002933 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002934 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002935 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002936 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002937}
2938
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002939Action::OwningExprResult
2940Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002941 SourceLocation RBraceLoc) {
2942 unsigned NumInit = initlist.size();
2943 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002944
Steve Naroff0acc9c92007-09-15 18:49:24 +00002945 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002946 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002947
Mike Stump9afab102009-02-19 03:04:26 +00002948 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002949 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002950 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002951 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002952}
2953
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002954/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002955bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
2956 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002957 if (getLangOptions().CPlusPlus)
Sebastian Redlc358b622009-07-29 13:50:23 +00002958 return CXXCheckCStyleCast(TyR, castType, castExpr, FunctionalStyle);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002959
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002960 UsualUnaryConversions(castExpr);
2961
2962 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2963 // type needs to be scalar.
2964 if (castType->isVoidType()) {
2965 // Cast to void allows any expr type.
2966 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002967 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2968 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2969 (castType->isStructureType() || castType->isUnionType())) {
2970 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002971 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002972 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2973 << castType << castExpr->getSourceRange();
2974 } else if (castType->isUnionType()) {
2975 // GCC cast to union extension
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00002976 RecordDecl *RD = castType->getAsRecordType()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002977 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002978 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002979 Field != FieldEnd; ++Field) {
2980 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2981 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2982 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2983 << castExpr->getSourceRange();
2984 break;
2985 }
2986 }
2987 if (Field == FieldEnd)
2988 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2989 << castExpr->getType() << castExpr->getSourceRange();
2990 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002991 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002992 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002993 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002994 }
Mike Stump9afab102009-02-19 03:04:26 +00002995 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002996 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002997 return Diag(castExpr->getLocStart(),
2998 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002999 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003000 } else if (castType->isExtVectorType()) {
3001 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003002 return true;
3003 } else if (castType->isVectorType()) {
3004 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3005 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003006 } else if (castExpr->getType()->isVectorType()) {
3007 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3008 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003009 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003010 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003011 } else if (!castType->isArithmeticType()) {
3012 QualType castExprType = castExpr->getType();
3013 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3014 return Diag(castExpr->getLocStart(),
3015 diag::err_cast_pointer_from_non_pointer_int)
3016 << castExprType << castExpr->getSourceRange();
3017 } else if (!castExpr->getType()->isArithmeticType()) {
3018 if (!castType->isIntegralType() && castType->isArithmeticType())
3019 return Diag(castExpr->getLocStart(),
3020 diag::err_cast_pointer_to_non_pointer_int)
3021 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003022 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003023 if (isa<ObjCSelectorExpr>(castExpr))
3024 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003025 return false;
3026}
3027
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003028bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003029 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003030
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003031 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003032 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003033 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003034 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003035 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003036 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003037 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003038 } else
3039 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003040 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003041 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003042
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003043 return false;
3044}
3045
Nate Begemanbd42e022009-06-26 00:50:28 +00003046bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3047 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3048
Nate Begeman9e063702009-06-27 22:05:55 +00003049 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3050 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003051 if (SrcTy->isVectorType()) {
3052 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3053 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3054 << DestTy << SrcTy << R;
3055 return false;
3056 }
3057
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003058 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003059 // conversion will take place first from scalar to elt type, and then
3060 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003061 if (SrcTy->isPointerType())
3062 return Diag(R.getBegin(),
3063 diag::err_invalid_conversion_between_vector_and_scalar)
3064 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003065 return false;
3066}
3067
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003068Action::OwningExprResult
3069Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
3070 SourceLocation RParenLoc, ExprArg Op) {
3071 assert((Ty != 0) && (Op.get() != 0) &&
3072 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003073
Anders Carlssonc154a722009-05-01 19:30:39 +00003074 Expr *castExpr = Op.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00003075 QualType castType = QualType::getFromOpaquePtr(Ty);
3076
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003077 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003078 return ExprError();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003079 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3080 castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00003081 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003082}
3083
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003084/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3085/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003086/// C99 6.5.15
3087QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3088 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003089 // C++ is sufficiently different to merit its own checker.
3090 if (getLangOptions().CPlusPlus)
3091 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3092
Chris Lattnere2897262009-02-18 04:28:32 +00003093 UsualUnaryConversions(Cond);
3094 UsualUnaryConversions(LHS);
3095 UsualUnaryConversions(RHS);
3096 QualType CondTy = Cond->getType();
3097 QualType LHSTy = LHS->getType();
3098 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003099
3100 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003101 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3102 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3103 << CondTy;
3104 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003105 }
Mike Stump9afab102009-02-19 03:04:26 +00003106
Chris Lattner992ae932008-01-06 22:42:25 +00003107 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003108
Chris Lattner992ae932008-01-06 22:42:25 +00003109 // If both operands have arithmetic type, do the usual arithmetic conversions
3110 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003111 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3112 UsualArithmeticConversions(LHS, RHS);
3113 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003114 }
Mike Stump9afab102009-02-19 03:04:26 +00003115
Chris Lattner992ae932008-01-06 22:42:25 +00003116 // If both operands are the same structure or union type, the result is that
3117 // type.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003118 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
3119 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00003120 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003121 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003122 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003123 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003124 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003125 }
Mike Stump9afab102009-02-19 03:04:26 +00003126
Chris Lattner992ae932008-01-06 22:42:25 +00003127 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003128 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003129 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3130 if (!LHSTy->isVoidType())
3131 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3132 << RHS->getSourceRange();
3133 if (!RHSTy->isVoidType())
3134 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3135 << LHS->getSourceRange();
3136 ImpCastExprToType(LHS, Context.VoidTy);
3137 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003138 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003139 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003140 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3141 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003142 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003143 RHS->isNullPointerConstant(Context)) {
3144 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3145 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003146 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003147 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003148 LHS->isNullPointerConstant(Context)) {
3149 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3150 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003151 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003152 // Handle block pointer types.
3153 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3154 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3155 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3156 QualType destType = Context.getPointerType(Context.VoidTy);
3157 ImpCastExprToType(LHS, destType);
3158 ImpCastExprToType(RHS, destType);
3159 return destType;
3160 }
3161 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3162 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3163 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003164 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003165 // We have 2 block pointer types.
3166 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3167 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003168 return LHSTy;
3169 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003170 // The block pointer types aren't identical, continue checking.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003171 QualType lhptee = LHSTy->getAsBlockPointerType()->getPointeeType();
3172 QualType rhptee = RHSTy->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003173
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003174 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3175 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003176 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3177 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3178 // In this situation, we assume void* type. No especially good
3179 // reason, but this is what gcc does, and we do have to pick
3180 // to get a consistent AST.
3181 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3182 ImpCastExprToType(LHS, incompatTy);
3183 ImpCastExprToType(RHS, incompatTy);
3184 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003185 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003186 // The block pointer types are compatible.
3187 ImpCastExprToType(LHS, LHSTy);
3188 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003189 return LHSTy;
3190 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003191 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003192 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003193
3194 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3195 // Two identical object pointer types are always compatible.
3196 return LHSTy;
3197 }
Steve Naroff329ec222009-07-10 23:34:53 +00003198 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3199 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003200 QualType compositeType = LHSTy;
3201
3202 // If both operands are interfaces and either operand can be
3203 // assigned to the other, use that type as the composite
3204 // type. This allows
3205 // xxx ? (A*) a : (B*) b
3206 // where B is a subclass of A.
3207 //
3208 // Additionally, as for assignment, if either type is 'id'
3209 // allow silent coercion. Finally, if the types are
3210 // incompatible then make sure to use 'id' as the composite
3211 // type so the result is acceptable for sending messages to.
3212
3213 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3214 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003215 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003216 compositeType = LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003217 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003218 compositeType = RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003219 } else if ((LHSTy->isObjCQualifiedIdType() ||
3220 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003221 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003222 // Need to handle "id<xx>" explicitly.
3223 // GCC allows qualified id and any Objective-C type to devolve to
3224 // id. Currently localizing to here until clear this should be
3225 // part of ObjCQualifiedIdTypesAreCompatible.
3226 compositeType = Context.getObjCIdType();
3227 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003228 compositeType = Context.getObjCIdType();
3229 } else {
3230 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3231 << LHSTy << RHSTy
3232 << LHS->getSourceRange() << RHS->getSourceRange();
3233 QualType incompatTy = Context.getObjCIdType();
3234 ImpCastExprToType(LHS, incompatTy);
3235 ImpCastExprToType(RHS, incompatTy);
3236 return incompatTy;
3237 }
3238 // The object pointer types are compatible.
3239 ImpCastExprToType(LHS, compositeType);
3240 ImpCastExprToType(RHS, compositeType);
3241 return compositeType;
3242 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003243 // Check Objective-C object pointer types and 'void *'
3244 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3245 QualType lhptee = LHSTy->getAsPointerType()->getPointeeType();
3246 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3247 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3248 QualType destType = Context.getPointerType(destPointee);
3249 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3250 ImpCastExprToType(RHS, destType); // promote to void*
3251 return destType;
3252 }
3253 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3254 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
3255 QualType rhptee = RHSTy->getAsPointerType()->getPointeeType();
3256 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3257 QualType destType = Context.getPointerType(destPointee);
3258 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3259 ImpCastExprToType(LHS, destType); // promote to void*
3260 return destType;
3261 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003262 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3263 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3264 // get the "pointed to" types
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003265 QualType lhptee = LHSTy->getAsPointerType()->getPointeeType();
3266 QualType rhptee = RHSTy->getAsPointerType()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003267
3268 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3269 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3270 // Figure out necessary qualifiers (C99 6.5.15p6)
3271 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3272 QualType destType = Context.getPointerType(destPointee);
3273 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3274 ImpCastExprToType(RHS, destType); // promote to void*
3275 return destType;
3276 }
3277 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3278 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3279 QualType destType = Context.getPointerType(destPointee);
3280 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3281 ImpCastExprToType(RHS, destType); // promote to void*
3282 return destType;
3283 }
3284
3285 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3286 // Two identical pointer types are always compatible.
3287 return LHSTy;
3288 }
3289 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3290 rhptee.getUnqualifiedType())) {
3291 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3292 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3293 // In this situation, we assume void* type. No especially good
3294 // reason, but this is what gcc does, and we do have to pick
3295 // to get a consistent AST.
3296 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3297 ImpCastExprToType(LHS, incompatTy);
3298 ImpCastExprToType(RHS, incompatTy);
3299 return incompatTy;
3300 }
3301 // The pointer types are compatible.
3302 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3303 // differently qualified versions of compatible types, the result type is
3304 // a pointer to an appropriately qualified version of the *composite*
3305 // type.
3306 // FIXME: Need to calculate the composite type.
3307 // FIXME: Need to add qualifiers
3308 ImpCastExprToType(LHS, LHSTy);
3309 ImpCastExprToType(RHS, LHSTy);
3310 return LHSTy;
3311 }
3312
3313 // GCC compatibility: soften pointer/integer mismatch.
3314 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3315 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3316 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3317 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3318 return RHSTy;
3319 }
3320 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3321 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3322 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3323 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3324 return LHSTy;
3325 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003326
Chris Lattner992ae932008-01-06 22:42:25 +00003327 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003328 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3329 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003330 return QualType();
3331}
3332
Steve Naroff87d58b42007-09-16 03:34:24 +00003333/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003334/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003335Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3336 SourceLocation ColonLoc,
3337 ExprArg Cond, ExprArg LHS,
3338 ExprArg RHS) {
3339 Expr *CondExpr = (Expr *) Cond.get();
3340 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003341
3342 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3343 // was the condition.
3344 bool isLHSNull = LHSExpr == 0;
3345 if (isLHSNull)
3346 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003347
3348 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003349 RHSExpr, QuestionLoc);
3350 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003351 return ExprError();
3352
3353 Cond.release();
3354 LHS.release();
3355 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003356 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003357 isLHSNull ? 0 : LHSExpr,
3358 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003359}
3360
Chris Lattner4b009652007-07-25 00:24:17 +00003361// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003362// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003363// routine is it effectively iqnores the qualifiers on the top level pointee.
3364// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3365// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003366Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003367Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3368 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003369
Chris Lattner4b009652007-07-25 00:24:17 +00003370 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003371 lhptee = lhsType->getAsPointerType()->getPointeeType();
3372 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003373
Chris Lattner4b009652007-07-25 00:24:17 +00003374 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003375 lhptee = Context.getCanonicalType(lhptee);
3376 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003377
Chris Lattner005ed752008-01-04 18:04:52 +00003378 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003379
3380 // C99 6.5.16.1p1: This following citation is common to constraints
3381 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3382 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003383 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003384 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003385 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003386
Mike Stump9afab102009-02-19 03:04:26 +00003387 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3388 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003389 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003390 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003391 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003392 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003393
Chris Lattner4ca3d772008-01-03 22:56:36 +00003394 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003395 assert(rhptee->isFunctionType());
3396 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003397 }
Mike Stump9afab102009-02-19 03:04:26 +00003398
Chris Lattner4ca3d772008-01-03 22:56:36 +00003399 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003400 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003401 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003402
3403 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003404 assert(lhptee->isFunctionType());
3405 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003406 }
Mike Stump9afab102009-02-19 03:04:26 +00003407 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003408 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003409 lhptee = lhptee.getUnqualifiedType();
3410 rhptee = rhptee.getUnqualifiedType();
3411 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3412 // Check if the pointee types are compatible ignoring the sign.
3413 // We explicitly check for char so that we catch "char" vs
3414 // "unsigned char" on systems where "char" is unsigned.
3415 if (lhptee->isCharType()) {
3416 lhptee = Context.UnsignedCharTy;
3417 } else if (lhptee->isSignedIntegerType()) {
3418 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3419 }
3420 if (rhptee->isCharType()) {
3421 rhptee = Context.UnsignedCharTy;
3422 } else if (rhptee->isSignedIntegerType()) {
3423 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3424 }
3425 if (lhptee == rhptee) {
3426 // Types are compatible ignoring the sign. Qualifier incompatibility
3427 // takes priority over sign incompatibility because the sign
3428 // warning can be disabled.
3429 if (ConvTy != Compatible)
3430 return ConvTy;
3431 return IncompatiblePointerSign;
3432 }
3433 // General pointer incompatibility takes priority over qualifiers.
3434 return IncompatiblePointer;
3435 }
Chris Lattner005ed752008-01-04 18:04:52 +00003436 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003437}
3438
Steve Naroff3454b6c2008-09-04 15:10:53 +00003439/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3440/// block pointer types are compatible or whether a block and normal pointer
3441/// are compatible. It is more restrict than comparing two function pointer
3442// types.
Mike Stump9afab102009-02-19 03:04:26 +00003443Sema::AssignConvertType
3444Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003445 QualType rhsType) {
3446 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003447
Steve Naroff3454b6c2008-09-04 15:10:53 +00003448 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003449 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
3450 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003451
Steve Naroff3454b6c2008-09-04 15:10:53 +00003452 // make sure we operate on the canonical type
3453 lhptee = Context.getCanonicalType(lhptee);
3454 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003455
Steve Naroff3454b6c2008-09-04 15:10:53 +00003456 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003457
Steve Naroff3454b6c2008-09-04 15:10:53 +00003458 // For blocks we enforce that qualifiers are identical.
3459 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3460 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003461
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003462 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003463 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003464 return ConvTy;
3465}
3466
Mike Stump9afab102009-02-19 03:04:26 +00003467/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3468/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003469/// pointers. Here are some objectionable examples that GCC considers warnings:
3470///
3471/// int a, *pint;
3472/// short *pshort;
3473/// struct foo *pfoo;
3474///
3475/// pint = pshort; // warning: assignment from incompatible pointer type
3476/// a = pint; // warning: assignment makes integer from pointer without a cast
3477/// pint = a; // warning: assignment makes pointer from integer without a cast
3478/// pint = pfoo; // warning: assignment from incompatible pointer type
3479///
3480/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003481/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003482///
Chris Lattner005ed752008-01-04 18:04:52 +00003483Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003484Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003485 // Get canonical types. We're not formatting these types, just comparing
3486 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003487 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3488 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003489
3490 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003491 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003492
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003493 // If the left-hand side is a reference type, then we are in a
3494 // (rare!) case where we've allowed the use of references in C,
3495 // e.g., as a parameter type in a built-in function. In this case,
3496 // just make sure that the type referenced is compatible with the
3497 // right-hand side type. The caller is responsible for adjusting
3498 // lhsType so that the resulting expression does not have reference
3499 // type.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003500 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003501 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003502 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003503 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003504 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003505 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3506 // to the same ExtVector type.
3507 if (lhsType->isExtVectorType()) {
3508 if (rhsType->isExtVectorType())
3509 return lhsType == rhsType ? Compatible : Incompatible;
3510 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3511 return Compatible;
3512 }
3513
Nate Begemanc5f0f652008-07-14 18:02:46 +00003514 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003515 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003516 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003517 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003518 if (getLangOptions().LaxVectorConversions &&
3519 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003520 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003521 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003522 }
3523 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003524 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003525
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003526 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003527 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003528
Chris Lattner390564e2008-04-07 06:49:41 +00003529 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003530 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003531 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003532
Chris Lattner390564e2008-04-07 06:49:41 +00003533 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003534 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003535
Steve Naroff8194a542009-07-20 17:56:53 +00003536 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003537 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003538 if (lhsType->isVoidPointerType()) // an exception to the rule.
3539 return Compatible;
3540 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003541 }
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003542 if (rhsType->getAsBlockPointerType()) {
3543 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003544 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003545
3546 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003547 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003548 return Compatible;
3549 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003550 return Incompatible;
3551 }
3552
3553 if (isa<BlockPointerType>(lhsType)) {
3554 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003555 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003556
Steve Naroffa982c712008-09-29 18:10:17 +00003557 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003558 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003559 return Compatible;
3560
Steve Naroff3454b6c2008-09-04 15:10:53 +00003561 if (rhsType->isBlockPointerType())
3562 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003563
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003564 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003565 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003566 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003567 }
Chris Lattner1853da22008-01-04 23:18:45 +00003568 return Incompatible;
3569 }
3570
Steve Naroff329ec222009-07-10 23:34:53 +00003571 if (isa<ObjCObjectPointerType>(lhsType)) {
3572 if (rhsType->isIntegerType())
3573 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003574
3575 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003576 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003577 if (rhsType->isVoidPointerType()) // an exception to the rule.
3578 return Compatible;
3579 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003580 }
3581 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003582 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3583 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003584 if (Context.typesAreCompatible(lhsType, rhsType))
3585 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003586 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3587 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003588 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003589 }
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003590 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003591 if (RHSPT->getPointeeType()->isVoidType())
3592 return Compatible;
3593 }
3594 // Treat block pointers as objects.
3595 if (rhsType->isBlockPointerType())
3596 return Compatible;
3597 return Incompatible;
3598 }
Chris Lattner390564e2008-04-07 06:49:41 +00003599 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003600 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003601 if (lhsType == Context.BoolTy)
3602 return Compatible;
3603
3604 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003605 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003606
Mike Stump9afab102009-02-19 03:04:26 +00003607 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003608 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003609
3610 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003611 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003612 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003613 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003614 }
Steve Naroff329ec222009-07-10 23:34:53 +00003615 if (isa<ObjCObjectPointerType>(rhsType)) {
3616 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3617 if (lhsType == Context.BoolTy)
3618 return Compatible;
3619
3620 if (lhsType->isIntegerType())
3621 return PointerToInt;
3622
Steve Naroff8194a542009-07-20 17:56:53 +00003623 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003624 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003625 if (lhsType->isVoidPointerType()) // an exception to the rule.
3626 return Compatible;
3627 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003628 }
3629 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003630 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003631 return Compatible;
3632 return Incompatible;
3633 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003634
Chris Lattner1853da22008-01-04 23:18:45 +00003635 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003636 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003637 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003638 }
3639 return Incompatible;
3640}
3641
Douglas Gregor144b06c2009-04-29 22:16:16 +00003642/// \brief Constructs a transparent union from an expression that is
3643/// used to initialize the transparent union.
3644static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3645 QualType UnionType, FieldDecl *Field) {
3646 // Build an initializer list that designates the appropriate member
3647 // of the transparent union.
3648 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3649 &E, 1,
3650 SourceLocation());
3651 Initializer->setType(UnionType);
3652 Initializer->setInitializedFieldInUnion(Field);
3653
3654 // Build a compound literal constructing a value of the transparent
3655 // union type from this initializer list.
3656 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3657 false);
3658}
3659
3660Sema::AssignConvertType
3661Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3662 QualType FromType = rExpr->getType();
3663
3664 // If the ArgType is a Union type, we want to handle a potential
3665 // transparent_union GCC extension.
3666 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003667 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003668 return Incompatible;
3669
3670 // The field to initialize within the transparent union.
3671 RecordDecl *UD = UT->getDecl();
3672 FieldDecl *InitField = 0;
3673 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003674 for (RecordDecl::field_iterator it = UD->field_begin(),
3675 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003676 it != itend; ++it) {
3677 if (it->getType()->isPointerType()) {
3678 // If the transparent union contains a pointer type, we allow:
3679 // 1) void pointer
3680 // 2) null pointer constant
3681 if (FromType->isPointerType())
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00003682 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003683 ImpCastExprToType(rExpr, it->getType());
3684 InitField = *it;
3685 break;
3686 }
3687
3688 if (rExpr->isNullPointerConstant(Context)) {
3689 ImpCastExprToType(rExpr, it->getType());
3690 InitField = *it;
3691 break;
3692 }
3693 }
3694
3695 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3696 == Compatible) {
3697 InitField = *it;
3698 break;
3699 }
3700 }
3701
3702 if (!InitField)
3703 return Incompatible;
3704
3705 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3706 return Compatible;
3707}
3708
Chris Lattner005ed752008-01-04 18:04:52 +00003709Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003710Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003711 if (getLangOptions().CPlusPlus) {
3712 if (!lhsType->isRecordType()) {
3713 // C++ 5.17p3: If the left operand is not of class type, the
3714 // expression is implicitly converted (C++ 4) to the
3715 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003716 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3717 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003718 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003719 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003720 }
3721
3722 // FIXME: Currently, we fall through and treat C++ classes like C
3723 // structures.
3724 }
3725
Steve Naroffcdee22d2007-11-27 17:58:44 +00003726 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3727 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003728 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003729 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003730 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003731 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003732 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003733 return Compatible;
3734 }
Mike Stump9afab102009-02-19 03:04:26 +00003735
Chris Lattner5f505bf2007-10-16 02:55:40 +00003736 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003737 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003738 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003739 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003740 //
Mike Stump9afab102009-02-19 03:04:26 +00003741 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003742 if (!lhsType->isReferenceType())
3743 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003744
Chris Lattner005ed752008-01-04 18:04:52 +00003745 Sema::AssignConvertType result =
3746 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003747
Steve Naroff0f32f432007-08-24 22:33:52 +00003748 // C99 6.5.16.1p2: The value of the right operand is converted to the
3749 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003750 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3751 // so that we can use references in built-in functions even in C.
3752 // The getNonReferenceType() call makes sure that the resulting expression
3753 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003754 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003755 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003756 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003757}
3758
Chris Lattner1eafdea2008-11-18 01:30:42 +00003759QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003760 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003761 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003762 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003763 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003764}
3765
Mike Stump9afab102009-02-19 03:04:26 +00003766inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003767 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003768 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003769 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003770 QualType lhsType =
3771 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3772 QualType rhsType =
3773 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003774
Nate Begemanc5f0f652008-07-14 18:02:46 +00003775 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003776 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003777 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003778
Nate Begemanc5f0f652008-07-14 18:02:46 +00003779 // Handle the case of a vector & extvector type of the same size and element
3780 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003781 if (getLangOptions().LaxVectorConversions) {
3782 // FIXME: Should we warn here?
3783 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003784 if (const VectorType *RV = rhsType->getAsVectorType())
3785 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003786 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003787 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003788 }
3789 }
3790 }
Mike Stump9afab102009-02-19 03:04:26 +00003791
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003792 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3793 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3794 bool swapped = false;
3795 if (rhsType->isExtVectorType()) {
3796 swapped = true;
3797 std::swap(rex, lex);
3798 std::swap(rhsType, lhsType);
3799 }
3800
Nate Begemanf1695892009-06-28 19:12:57 +00003801 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003802 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3803 QualType EltTy = LV->getElementType();
3804 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3805 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003806 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003807 if (swapped) std::swap(rex, lex);
3808 return lhsType;
3809 }
3810 }
3811 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3812 rhsType->isRealFloatingType()) {
3813 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003814 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003815 if (swapped) std::swap(rex, lex);
3816 return lhsType;
3817 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003818 }
3819 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003820
Nate Begemanf1695892009-06-28 19:12:57 +00003821 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003822 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003823 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003824 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003825 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003826}
3827
Chris Lattner4b009652007-07-25 00:24:17 +00003828inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003829 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003830{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003831 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003832 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003833
Steve Naroff8f708362007-08-24 19:07:16 +00003834 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003835
Chris Lattner4b009652007-07-25 00:24:17 +00003836 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003837 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003838 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003839}
3840
3841inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003842 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003843{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003844 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3845 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3846 return CheckVectorOperands(Loc, lex, rex);
3847 return InvalidOperands(Loc, lex, rex);
3848 }
Chris Lattner4b009652007-07-25 00:24:17 +00003849
Steve Naroff8f708362007-08-24 19:07:16 +00003850 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003851
Chris Lattner4b009652007-07-25 00:24:17 +00003852 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003853 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003854 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003855}
3856
3857inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003858 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003859{
Eli Friedman3cd92882009-03-28 01:22:36 +00003860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3861 QualType compType = CheckVectorOperands(Loc, lex, rex);
3862 if (CompLHSTy) *CompLHSTy = compType;
3863 return compType;
3864 }
Chris Lattner4b009652007-07-25 00:24:17 +00003865
Eli Friedman3cd92882009-03-28 01:22:36 +00003866 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003867
Chris Lattner4b009652007-07-25 00:24:17 +00003868 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003869 if (lex->getType()->isArithmeticType() &&
3870 rex->getType()->isArithmeticType()) {
3871 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003872 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003873 }
Chris Lattner4b009652007-07-25 00:24:17 +00003874
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003875 // Put any potential pointer into PExp
3876 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003877 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003878 std::swap(PExp, IExp);
3879
Steve Naroff79ae19a2009-07-14 18:25:06 +00003880 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003881
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003882 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003883 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003884
Chris Lattner184f92d2009-04-24 23:50:08 +00003885 // Check for arithmetic on pointers to incomplete types.
3886 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003887 if (getLangOptions().CPlusPlus) {
3888 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003889 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003890 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003891 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003892
3893 // GNU extension: arithmetic on pointer to void
3894 Diag(Loc, diag::ext_gnu_void_ptr)
3895 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003896 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003897 if (getLangOptions().CPlusPlus) {
3898 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3899 << lex->getType() << lex->getSourceRange();
3900 return QualType();
3901 }
3902
3903 // GNU extension: arithmetic on pointer to function
3904 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3905 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00003906 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00003907 // Check if we require a complete type.
3908 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00003909 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00003910 PExp->getType()->isObjCObjectPointerType()) &&
3911 RequireCompleteType(Loc, PointeeTy,
3912 diag::err_typecheck_arithmetic_incomplete_type,
3913 PExp->getSourceRange(), SourceRange(),
3914 PExp->getType()))
3915 return QualType();
3916 }
Chris Lattner184f92d2009-04-24 23:50:08 +00003917 // Diagnose bad cases where we step over interface counts.
3918 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3919 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3920 << PointeeTy << PExp->getSourceRange();
3921 return QualType();
3922 }
3923
Eli Friedman3cd92882009-03-28 01:22:36 +00003924 if (CompLHSTy) {
3925 QualType LHSTy = lex->getType();
3926 if (LHSTy->isPromotableIntegerType())
3927 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003928 else {
3929 QualType T = isPromotableBitField(lex, Context);
3930 if (!T.isNull())
3931 LHSTy = T;
3932 }
3933
Eli Friedman3cd92882009-03-28 01:22:36 +00003934 *CompLHSTy = LHSTy;
3935 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003936 return PExp->getType();
3937 }
3938 }
3939
Chris Lattner1eafdea2008-11-18 01:30:42 +00003940 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003941}
3942
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003943// C99 6.5.6
3944QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003945 SourceLocation Loc, QualType* CompLHSTy) {
3946 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3947 QualType compType = CheckVectorOperands(Loc, lex, rex);
3948 if (CompLHSTy) *CompLHSTy = compType;
3949 return compType;
3950 }
Mike Stump9afab102009-02-19 03:04:26 +00003951
Eli Friedman3cd92882009-03-28 01:22:36 +00003952 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003953
Chris Lattnerf6da2912007-12-09 21:53:25 +00003954 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003955
Chris Lattnerf6da2912007-12-09 21:53:25 +00003956 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00003957 if (lex->getType()->isArithmeticType()
3958 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00003959 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003960 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003961 }
Steve Naroff329ec222009-07-10 23:34:53 +00003962
Chris Lattnerf6da2912007-12-09 21:53:25 +00003963 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00003964 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00003965 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003966
Douglas Gregor05e28f62009-03-24 19:52:54 +00003967 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003968
Douglas Gregor05e28f62009-03-24 19:52:54 +00003969 bool ComplainAboutVoid = false;
3970 Expr *ComplainAboutFunc = 0;
3971 if (lpointee->isVoidType()) {
3972 if (getLangOptions().CPlusPlus) {
3973 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3974 << lex->getSourceRange() << rex->getSourceRange();
3975 return QualType();
3976 }
3977
3978 // GNU C extension: arithmetic on pointer to void
3979 ComplainAboutVoid = true;
3980 } else if (lpointee->isFunctionType()) {
3981 if (getLangOptions().CPlusPlus) {
3982 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003983 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003984 return QualType();
3985 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003986
3987 // GNU C extension: arithmetic on pointer to function
3988 ComplainAboutFunc = lex;
3989 } else if (!lpointee->isDependentType() &&
3990 RequireCompleteType(Loc, lpointee,
3991 diag::err_typecheck_sub_ptr_object,
3992 lex->getSourceRange(),
3993 SourceRange(),
3994 lex->getType()))
3995 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003996
Chris Lattner184f92d2009-04-24 23:50:08 +00003997 // Diagnose bad cases where we step over interface counts.
3998 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3999 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4000 << lpointee << lex->getSourceRange();
4001 return QualType();
4002 }
4003
Chris Lattnerf6da2912007-12-09 21:53:25 +00004004 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004005 if (rex->getType()->isIntegerType()) {
4006 if (ComplainAboutVoid)
4007 Diag(Loc, diag::ext_gnu_void_ptr)
4008 << lex->getSourceRange() << rex->getSourceRange();
4009 if (ComplainAboutFunc)
4010 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4011 << ComplainAboutFunc->getType()
4012 << ComplainAboutFunc->getSourceRange();
4013
Eli Friedman3cd92882009-03-28 01:22:36 +00004014 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004015 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004016 }
Mike Stump9afab102009-02-19 03:04:26 +00004017
Chris Lattnerf6da2912007-12-09 21:53:25 +00004018 // Handle pointer-pointer subtractions.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004019 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00004020 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004021
Douglas Gregor05e28f62009-03-24 19:52:54 +00004022 // RHS must be a completely-type object type.
4023 // Handle the GNU void* extension.
4024 if (rpointee->isVoidType()) {
4025 if (getLangOptions().CPlusPlus) {
4026 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4027 << lex->getSourceRange() << rex->getSourceRange();
4028 return QualType();
4029 }
Mike Stump9afab102009-02-19 03:04:26 +00004030
Douglas Gregor05e28f62009-03-24 19:52:54 +00004031 ComplainAboutVoid = true;
4032 } else if (rpointee->isFunctionType()) {
4033 if (getLangOptions().CPlusPlus) {
4034 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004035 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004036 return QualType();
4037 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004038
4039 // GNU extension: arithmetic on pointer to function
4040 if (!ComplainAboutFunc)
4041 ComplainAboutFunc = rex;
4042 } else if (!rpointee->isDependentType() &&
4043 RequireCompleteType(Loc, rpointee,
4044 diag::err_typecheck_sub_ptr_object,
4045 rex->getSourceRange(),
4046 SourceRange(),
4047 rex->getType()))
4048 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004049
Eli Friedman143ddc92009-05-16 13:54:38 +00004050 if (getLangOptions().CPlusPlus) {
4051 // Pointee types must be the same: C++ [expr.add]
4052 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4053 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4054 << lex->getType() << rex->getType()
4055 << lex->getSourceRange() << rex->getSourceRange();
4056 return QualType();
4057 }
4058 } else {
4059 // Pointee types must be compatible C99 6.5.6p3
4060 if (!Context.typesAreCompatible(
4061 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4062 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4063 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4064 << lex->getType() << rex->getType()
4065 << lex->getSourceRange() << rex->getSourceRange();
4066 return QualType();
4067 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004068 }
Mike Stump9afab102009-02-19 03:04:26 +00004069
Douglas Gregor05e28f62009-03-24 19:52:54 +00004070 if (ComplainAboutVoid)
4071 Diag(Loc, diag::ext_gnu_void_ptr)
4072 << lex->getSourceRange() << rex->getSourceRange();
4073 if (ComplainAboutFunc)
4074 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4075 << ComplainAboutFunc->getType()
4076 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004077
4078 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004079 return Context.getPointerDiffType();
4080 }
4081 }
Mike Stump9afab102009-02-19 03:04:26 +00004082
Chris Lattner1eafdea2008-11-18 01:30:42 +00004083 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004084}
4085
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004086// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004087QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004088 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004089 // C99 6.5.7p2: Each of the operands shall have integer type.
4090 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004091 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004092
Chris Lattner2c8bff72007-12-12 05:47:28 +00004093 // Shifts don't perform usual arithmetic conversions, they just do integer
4094 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00004095 QualType LHSTy;
4096 if (lex->getType()->isPromotableIntegerType())
4097 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004098 else {
4099 LHSTy = isPromotableBitField(lex, Context);
4100 if (LHSTy.isNull())
4101 LHSTy = lex->getType();
4102 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004103 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004104 ImpCastExprToType(lex, LHSTy);
4105
Chris Lattner2c8bff72007-12-12 05:47:28 +00004106 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004107
Chris Lattner2c8bff72007-12-12 05:47:28 +00004108 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004109 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004110}
4111
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004112// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004113QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004114 unsigned OpaqueOpc, bool isRelational) {
4115 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4116
Nate Begemanc5f0f652008-07-14 18:02:46 +00004117 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004118 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004119
Chris Lattner254f3bc2007-08-26 01:18:55 +00004120 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004121 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4122 UsualArithmeticConversions(lex, rex);
4123 else {
4124 UsualUnaryConversions(lex);
4125 UsualUnaryConversions(rex);
4126 }
Chris Lattner4b009652007-07-25 00:24:17 +00004127 QualType lType = lex->getType();
4128 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004129
Mike Stumpea3d74e2009-05-07 18:43:07 +00004130 if (!lType->isFloatingType()
4131 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004132 // For non-floating point types, check for self-comparisons of the form
4133 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4134 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004135 // NOTE: Don't warn about comparisons of enum constants. These can arise
4136 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004137 Expr *LHSStripped = lex->IgnoreParens();
4138 Expr *RHSStripped = rex->IgnoreParens();
4139 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4140 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004141 if (DRL->getDecl() == DRR->getDecl() &&
4142 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004143 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004144
4145 if (isa<CastExpr>(LHSStripped))
4146 LHSStripped = LHSStripped->IgnoreParenCasts();
4147 if (isa<CastExpr>(RHSStripped))
4148 RHSStripped = RHSStripped->IgnoreParenCasts();
4149
4150 // Warn about comparisons against a string constant (unless the other
4151 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004152 Expr *literalString = 0;
4153 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004154 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004155 !RHSStripped->isNullPointerConstant(Context)) {
4156 literalString = lex;
4157 literalStringStripped = LHSStripped;
4158 }
Chris Lattner4e479f92009-03-08 19:39:53 +00004159 else if ((isa<StringLiteral>(RHSStripped) ||
4160 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004161 !LHSStripped->isNullPointerConstant(Context)) {
4162 literalString = rex;
4163 literalStringStripped = RHSStripped;
4164 }
4165
4166 if (literalString) {
4167 std::string resultComparison;
4168 switch (Opc) {
4169 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4170 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4171 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4172 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4173 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4174 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4175 default: assert(false && "Invalid comparison operator");
4176 }
4177 Diag(Loc, diag::warn_stringcompare)
4178 << isa<ObjCEncodeExpr>(literalStringStripped)
4179 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004180 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4181 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4182 "strcmp(")
4183 << CodeModificationHint::CreateInsertion(
4184 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004185 resultComparison);
4186 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004187 }
Mike Stump9afab102009-02-19 03:04:26 +00004188
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004189 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004190 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004191
Chris Lattner254f3bc2007-08-26 01:18:55 +00004192 if (isRelational) {
4193 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004194 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004195 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004196 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004197 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004198 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004199 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004200 }
Mike Stump9afab102009-02-19 03:04:26 +00004201
Chris Lattner254f3bc2007-08-26 01:18:55 +00004202 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004203 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004204 }
Mike Stump9afab102009-02-19 03:04:26 +00004205
Chris Lattner22be8422007-08-26 01:10:14 +00004206 bool LHSIsNull = lex->isNullPointerConstant(Context);
4207 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004208
Chris Lattner254f3bc2007-08-26 01:18:55 +00004209 // All of the following pointer related warnings are GCC extensions, except
4210 // when handling null pointer constants. One day, we can consider making them
4211 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004212 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004213 QualType LCanPointeeTy =
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004214 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004215 QualType RCanPointeeTy =
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004216 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004217
Douglas Gregor4da47382009-07-06 20:14:23 +00004218 if (isRelational) {
4219 if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004220 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4221 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4222 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004223 if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) {
4224 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4225 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4226 }
4227 } else {
4228 if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) {
4229 if (!LHSIsNull && !RHSIsNull)
4230 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4231 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4232 }
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004233 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004234
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004235 // Simple check: if the pointee types are identical, we're done.
4236 if (LCanPointeeTy == RCanPointeeTy)
4237 return ResultTy;
4238
4239 if (getLangOptions().CPlusPlus) {
4240 // C++ [expr.rel]p2:
4241 // [...] Pointer conversions (4.10) and qualification
4242 // conversions (4.4) are performed on pointer operands (or on
4243 // a pointer operand and a null pointer constant) to bring
4244 // them to their composite pointer type. [...]
4245 //
4246 // C++ [expr.eq]p2 uses the same notion for (in)equality
4247 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004248 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004249 if (T.isNull()) {
4250 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4251 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4252 return QualType();
4253 }
4254
4255 ImpCastExprToType(lex, T);
4256 ImpCastExprToType(rex, T);
4257 return ResultTy;
4258 }
4259
Steve Naroff3b435622007-11-13 14:57:38 +00004260 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004261 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4262 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Steve Naroff329ec222009-07-10 23:34:53 +00004263 RCanPointeeTy.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004264 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004265 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004266 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004267 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004268 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004269 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004270 // C++ allows comparison of pointers with null pointer constants.
4271 if (getLangOptions().CPlusPlus) {
4272 if (lType->isPointerType() && RHSIsNull) {
4273 ImpCastExprToType(rex, lType);
4274 return ResultTy;
4275 }
4276 if (rType->isPointerType() && LHSIsNull) {
4277 ImpCastExprToType(lex, rType);
4278 return ResultTy;
4279 }
4280 // And comparison of nullptr_t with itself.
4281 if (lType->isNullPtrType() && rType->isNullPtrType())
4282 return ResultTy;
4283 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004284 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004285 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004286 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
4287 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004288
Steve Naroff3454b6c2008-09-04 15:10:53 +00004289 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004290 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004291 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004292 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004293 }
4294 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004295 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004296 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004297 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004298 if (!isRelational
4299 && ((lType->isBlockPointerType() && rType->isPointerType())
4300 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004301 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004302 if (!((rType->isPointerType() && rType->getAsPointerType()
Mike Stumpe97a8542009-05-07 03:14:14 +00004303 ->getPointeeType()->isVoidType())
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004304 || (lType->isPointerType() && lType->getAsPointerType()
Mike Stumpe97a8542009-05-07 03:14:14 +00004305 ->getPointeeType()->isVoidType())))
4306 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4307 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004308 }
4309 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004310 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004311 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004312
Steve Naroff329ec222009-07-10 23:34:53 +00004313 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004314 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004315 const PointerType *LPT = lType->getAsPointerType();
4316 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00004317 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004318 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004319 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004320 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004321
Steve Naroff030fcda2008-11-17 19:49:16 +00004322 if (!LPtrToVoid && !RPtrToVoid &&
4323 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004324 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004325 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004326 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004327 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004328 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004329 }
Steve Naroff329ec222009-07-10 23:34:53 +00004330 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4331 if (!Context.areComparableObjCPointerTypes(lType, rType)) {
4332 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4333 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4334 }
Steve Naroff936c4362008-06-03 14:04:54 +00004335 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004336 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004337 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004338 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004339 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004340 if (isRelational)
4341 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4342 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4343 else if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004344 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004345 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004346 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004347 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004348 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004349 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004350 if (isRelational)
4351 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4352 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4353 else if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004354 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004355 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004356 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004357 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004358 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004359 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004360 if (!isRelational && RHSIsNull
4361 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004362 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004363 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004364 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004365 if (!isRelational && LHSIsNull
4366 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004367 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004368 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004369 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004370 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004371}
4372
Nate Begemanc5f0f652008-07-14 18:02:46 +00004373/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004374/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004375/// like a scalar comparison, a vector comparison produces a vector of integer
4376/// types.
4377QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004378 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004379 bool isRelational) {
4380 // Check to make sure we're operating on vectors of the same type and width,
4381 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004382 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004383 if (vType.isNull())
4384 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004385
Nate Begemanc5f0f652008-07-14 18:02:46 +00004386 QualType lType = lex->getType();
4387 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004388
Nate Begemanc5f0f652008-07-14 18:02:46 +00004389 // For non-floating point types, check for self-comparisons of the form
4390 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4391 // often indicate logic errors in the program.
4392 if (!lType->isFloatingType()) {
4393 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4394 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4395 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004396 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004397 }
Mike Stump9afab102009-02-19 03:04:26 +00004398
Nate Begemanc5f0f652008-07-14 18:02:46 +00004399 // Check for comparisons of floating point operands using != and ==.
4400 if (!isRelational && lType->isFloatingType()) {
4401 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004402 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004403 }
Mike Stump9afab102009-02-19 03:04:26 +00004404
Nate Begemanc5f0f652008-07-14 18:02:46 +00004405 // Return the type for the comparison, which is the same as vector type for
4406 // integer vectors, or an integer type of identical size and number of
4407 // elements for floating point vectors.
4408 if (lType->isIntegerType())
4409 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004410
Nate Begemanc5f0f652008-07-14 18:02:46 +00004411 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004412 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004413 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004414 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004415 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004416 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4417
Mike Stump9afab102009-02-19 03:04:26 +00004418 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004419 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004420 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4421}
4422
Chris Lattner4b009652007-07-25 00:24:17 +00004423inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004424 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004425{
4426 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004427 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004428
Steve Naroff8f708362007-08-24 19:07:16 +00004429 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004430
Chris Lattner4b009652007-07-25 00:24:17 +00004431 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004432 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004433 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004434}
4435
4436inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004437 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004438{
4439 UsualUnaryConversions(lex);
4440 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004441
Eli Friedmanbea3f842008-05-13 20:16:47 +00004442 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004443 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004444 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004445}
4446
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004447/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4448/// is a read-only property; return true if so. A readonly property expression
4449/// depends on various declarations and thus must be treated specially.
4450///
Mike Stump9afab102009-02-19 03:04:26 +00004451static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004452{
4453 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4454 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4455 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4456 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004457 if (const ObjCObjectPointerType *OPT =
4458 BaseType->getAsObjCInterfacePointerType())
4459 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4460 if (S.isPropertyReadonly(PDecl, IFace))
4461 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004462 }
4463 }
4464 return false;
4465}
4466
Chris Lattner4c2642c2008-11-18 01:22:49 +00004467/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4468/// emit an error and return true. If so, return false.
4469static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004470 SourceLocation OrigLoc = Loc;
4471 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4472 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004473 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4474 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004475 if (IsLV == Expr::MLV_Valid)
4476 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004477
Chris Lattner4c2642c2008-11-18 01:22:49 +00004478 unsigned Diag = 0;
4479 bool NeedType = false;
4480 switch (IsLV) { // C99 6.5.16p2
4481 default: assert(0 && "Unknown result from isModifiableLvalue!");
4482 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004483 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004484 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4485 NeedType = true;
4486 break;
Mike Stump9afab102009-02-19 03:04:26 +00004487 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004488 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4489 NeedType = true;
4490 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004491 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004492 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4493 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004494 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004495 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4496 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004497 case Expr::MLV_IncompleteType:
4498 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004499 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004500 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4501 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004502 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004503 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4504 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004505 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004506 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4507 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004508 case Expr::MLV_ReadonlyProperty:
4509 Diag = diag::error_readonly_property_assignment;
4510 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004511 case Expr::MLV_NoSetterProperty:
4512 Diag = diag::error_nosetter_property_assignment;
4513 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004514 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004515
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004516 SourceRange Assign;
4517 if (Loc != OrigLoc)
4518 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004519 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004520 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004521 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004522 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004523 return true;
4524}
4525
4526
4527
4528// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004529QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4530 SourceLocation Loc,
4531 QualType CompoundType) {
4532 // Verify that LHS is a modifiable lvalue, and emit error if not.
4533 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004534 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004535
4536 QualType LHSType = LHS->getType();
4537 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004538
Chris Lattner005ed752008-01-04 18:04:52 +00004539 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004540 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004541 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004542 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004543 // Special case of NSObject attributes on c-style pointer types.
4544 if (ConvTy == IncompatiblePointer &&
4545 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004546 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004547 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004548 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004549 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004550
Chris Lattner34c85082008-08-21 18:04:13 +00004551 // If the RHS is a unary plus or minus, check to see if they = and + are
4552 // right next to each other. If so, the user may have typo'd "x =+ 4"
4553 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004554 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4556 RHSCheck = ICE->getSubExpr();
4557 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4558 if ((UO->getOpcode() == UnaryOperator::Plus ||
4559 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004560 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004561 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004562 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4563 // And there is a space or other character before the subexpr of the
4564 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004565 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4566 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004567 Diag(Loc, diag::warn_not_compound_assign)
4568 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4569 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004570 }
Chris Lattner34c85082008-08-21 18:04:13 +00004571 }
4572 } else {
4573 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004574 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004575 }
Chris Lattner005ed752008-01-04 18:04:52 +00004576
Chris Lattner1eafdea2008-11-18 01:30:42 +00004577 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4578 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004579 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004580
Chris Lattner4b009652007-07-25 00:24:17 +00004581 // C99 6.5.16p3: The type of an assignment expression is the type of the
4582 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004583 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004584 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4585 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004586 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004587 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004588 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004589}
4590
Chris Lattner1eafdea2008-11-18 01:30:42 +00004591// C99 6.5.17
4592QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004593 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004594 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004595
4596 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4597 // incomplete in C++).
4598
Chris Lattner1eafdea2008-11-18 01:30:42 +00004599 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004600}
4601
4602/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4603/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004604QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4605 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004606 if (Op->isTypeDependent())
4607 return Context.DependentTy;
4608
Chris Lattnere65182c2008-11-21 07:05:48 +00004609 QualType ResType = Op->getType();
4610 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004611
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004612 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4613 // Decrement of bool is not allowed.
4614 if (!isInc) {
4615 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4616 return QualType();
4617 }
4618 // Increment of bool sets it to true, but is deprecated.
4619 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4620 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004621 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004622 } else if (ResType->isAnyPointerType()) {
4623 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004624
Chris Lattnere65182c2008-11-21 07:05:48 +00004625 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004626 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004627 if (getLangOptions().CPlusPlus) {
4628 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4629 << Op->getSourceRange();
4630 return QualType();
4631 }
4632
4633 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004634 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004635 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004636 if (getLangOptions().CPlusPlus) {
4637 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4638 << Op->getType() << Op->getSourceRange();
4639 return QualType();
4640 }
4641
4642 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004643 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004644 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004645 diag::err_typecheck_arithmetic_incomplete_type,
4646 Op->getSourceRange(), SourceRange(),
4647 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004648 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004649 // Diagnose bad cases where we step over interface counts.
4650 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4651 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4652 << PointeeTy << Op->getSourceRange();
4653 return QualType();
4654 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004655 } else if (ResType->isComplexType()) {
4656 // C99 does not support ++/-- on complex types, we allow as an extension.
4657 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004658 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004659 } else {
4660 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004661 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004662 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004663 }
Mike Stump9afab102009-02-19 03:04:26 +00004664 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004665 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004666 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004667 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004668 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004669}
4670
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004671/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004672/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004673/// where the declaration is needed for type checking. We only need to
4674/// handle cases when the expression references a function designator
4675/// or is an lvalue. Here are some examples:
4676/// - &(x) => x
4677/// - &*****f => f for f a function designator.
4678/// - &s.xx => s
4679/// - &s.zz[1].yy -> s, if zz is an array
4680/// - *(x + 1) -> x, if x is an array
4681/// - &"123"[2] -> 0
4682/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004683static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004684 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004685 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004686 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004687 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004688 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004689 // If this is an arrow operator, the address is an offset from
4690 // the base's value, so the object the base refers to is
4691 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004692 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004693 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004694 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004695 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004696 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004697 // FIXME: This code shouldn't be necessary! We should catch the implicit
4698 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004699 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4700 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4701 if (ICE->getSubExpr()->getType()->isArrayType())
4702 return getPrimaryDecl(ICE->getSubExpr());
4703 }
4704 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004705 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004706 case Stmt::UnaryOperatorClass: {
4707 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004708
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004709 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004710 case UnaryOperator::Real:
4711 case UnaryOperator::Imag:
4712 case UnaryOperator::Extension:
4713 return getPrimaryDecl(UO->getSubExpr());
4714 default:
4715 return 0;
4716 }
4717 }
Chris Lattner4b009652007-07-25 00:24:17 +00004718 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004719 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004720 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004721 // If the result of an implicit cast is an l-value, we care about
4722 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004723 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004724 default:
4725 return 0;
4726 }
4727}
4728
4729/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004730/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004731/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004732/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004733/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004734/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004735/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004736QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004737 // Make sure to ignore parentheses in subsequent checks
4738 op = op->IgnoreParens();
4739
Douglas Gregore6be68a2008-12-17 22:52:20 +00004740 if (op->isTypeDependent())
4741 return Context.DependentTy;
4742
Steve Naroff9c6c3592008-01-13 17:10:08 +00004743 if (getLangOptions().C99) {
4744 // Implement C99-only parts of addressof rules.
4745 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4746 if (uOp->getOpcode() == UnaryOperator::Deref)
4747 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4748 // (assuming the deref expression is valid).
4749 return uOp->getSubExpr()->getType();
4750 }
4751 // Technically, there should be a check for array subscript
4752 // expressions here, but the result of one is always an lvalue anyway.
4753 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004754 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004755 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004756
Eli Friedman14ab4c42009-05-16 23:27:50 +00004757 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4758 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004759 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004760 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004761 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004762 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4763 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004764 return QualType();
4765 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004766 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004767 // The operand cannot be a bit-field
4768 Diag(OpLoc, diag::err_typecheck_address_of)
4769 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004770 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004771 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4772 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004773 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004774 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004775 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004776 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004777 } else if (isa<ObjCPropertyRefExpr>(op)) {
4778 // cannot take address of a property expression.
4779 Diag(OpLoc, diag::err_typecheck_address_of)
4780 << "property expression" << op->getSourceRange();
4781 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004782 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004783 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004784 // with the register storage-class specifier.
4785 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4786 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004787 Diag(OpLoc, diag::err_typecheck_address_of)
4788 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004789 return QualType();
4790 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004791 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4792 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004793 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004794 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004795 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004796 // Could be a pointer to member, though, if there is an explicit
4797 // scope qualifier for the class.
4798 if (isa<QualifiedDeclRefExpr>(op)) {
4799 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004800 if (Ctx && Ctx->isRecord()) {
4801 if (FD->getType()->isReferenceType()) {
4802 Diag(OpLoc,
4803 diag::err_cannot_form_pointer_to_member_of_reference_type)
4804 << FD->getDeclName() << FD->getType();
4805 return QualType();
4806 }
4807
Sebastian Redl0c9da212009-02-03 20:19:35 +00004808 return Context.getMemberPointerType(op->getType(),
4809 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004810 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004811 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004812 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004813 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004814 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004815 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4816 return Context.getMemberPointerType(op->getType(),
4817 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4818 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004819 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004820 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004821
Eli Friedman14ab4c42009-05-16 23:27:50 +00004822 if (lval == Expr::LV_IncompleteVoidType) {
4823 // Taking the address of a void variable is technically illegal, but we
4824 // allow it in cases which are otherwise valid.
4825 // Example: "extern void x; void* y = &x;".
4826 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4827 }
4828
Chris Lattner4b009652007-07-25 00:24:17 +00004829 // If the operand has type "type", the result has type "pointer to type".
4830 return Context.getPointerType(op->getType());
4831}
4832
Chris Lattnerda5c0872008-11-23 09:13:29 +00004833QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004834 if (Op->isTypeDependent())
4835 return Context.DependentTy;
4836
Chris Lattnerda5c0872008-11-23 09:13:29 +00004837 UsualUnaryConversions(Op);
4838 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004839
Chris Lattnerda5c0872008-11-23 09:13:29 +00004840 // Note that per both C89 and C99, this is always legal, even if ptype is an
4841 // incomplete type or void. It would be possible to warn about dereferencing
4842 // a void pointer, but it's completely well-defined, and such a warning is
4843 // unlikely to catch any mistakes.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00004844 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004845 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004846
Steve Naroff329ec222009-07-10 23:34:53 +00004847 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4848 return OPT->getPointeeType();
4849
Chris Lattner77d52da2008-11-20 06:06:08 +00004850 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004851 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004852 return QualType();
4853}
4854
4855static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4856 tok::TokenKind Kind) {
4857 BinaryOperator::Opcode Opc;
4858 switch (Kind) {
4859 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004860 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4861 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004862 case tok::star: Opc = BinaryOperator::Mul; break;
4863 case tok::slash: Opc = BinaryOperator::Div; break;
4864 case tok::percent: Opc = BinaryOperator::Rem; break;
4865 case tok::plus: Opc = BinaryOperator::Add; break;
4866 case tok::minus: Opc = BinaryOperator::Sub; break;
4867 case tok::lessless: Opc = BinaryOperator::Shl; break;
4868 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4869 case tok::lessequal: Opc = BinaryOperator::LE; break;
4870 case tok::less: Opc = BinaryOperator::LT; break;
4871 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4872 case tok::greater: Opc = BinaryOperator::GT; break;
4873 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4874 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4875 case tok::amp: Opc = BinaryOperator::And; break;
4876 case tok::caret: Opc = BinaryOperator::Xor; break;
4877 case tok::pipe: Opc = BinaryOperator::Or; break;
4878 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4879 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4880 case tok::equal: Opc = BinaryOperator::Assign; break;
4881 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4882 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4883 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4884 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4885 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4886 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4887 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4888 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4889 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4890 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4891 case tok::comma: Opc = BinaryOperator::Comma; break;
4892 }
4893 return Opc;
4894}
4895
4896static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4897 tok::TokenKind Kind) {
4898 UnaryOperator::Opcode Opc;
4899 switch (Kind) {
4900 default: assert(0 && "Unknown unary op!");
4901 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4902 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4903 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4904 case tok::star: Opc = UnaryOperator::Deref; break;
4905 case tok::plus: Opc = UnaryOperator::Plus; break;
4906 case tok::minus: Opc = UnaryOperator::Minus; break;
4907 case tok::tilde: Opc = UnaryOperator::Not; break;
4908 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004909 case tok::kw___real: Opc = UnaryOperator::Real; break;
4910 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4911 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4912 }
4913 return Opc;
4914}
4915
Douglas Gregord7f915e2008-11-06 23:29:22 +00004916/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4917/// operator @p Opc at location @c TokLoc. This routine only supports
4918/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004919Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4920 unsigned Op,
4921 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004922 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004923 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004924 // The following two variables are used for compound assignment operators
4925 QualType CompLHSTy; // Type of LHS after promotions for computation
4926 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004927
4928 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004929 case BinaryOperator::Assign:
4930 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4931 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004932 case BinaryOperator::PtrMemD:
4933 case BinaryOperator::PtrMemI:
4934 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4935 Opc == BinaryOperator::PtrMemI);
4936 break;
4937 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004938 case BinaryOperator::Div:
4939 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4940 break;
4941 case BinaryOperator::Rem:
4942 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4943 break;
4944 case BinaryOperator::Add:
4945 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4946 break;
4947 case BinaryOperator::Sub:
4948 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4949 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004950 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004951 case BinaryOperator::Shr:
4952 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4953 break;
4954 case BinaryOperator::LE:
4955 case BinaryOperator::LT:
4956 case BinaryOperator::GE:
4957 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004958 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004959 break;
4960 case BinaryOperator::EQ:
4961 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004962 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004963 break;
4964 case BinaryOperator::And:
4965 case BinaryOperator::Xor:
4966 case BinaryOperator::Or:
4967 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4968 break;
4969 case BinaryOperator::LAnd:
4970 case BinaryOperator::LOr:
4971 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4972 break;
4973 case BinaryOperator::MulAssign:
4974 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004975 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4976 CompLHSTy = CompResultTy;
4977 if (!CompResultTy.isNull())
4978 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004979 break;
4980 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004981 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4982 CompLHSTy = CompResultTy;
4983 if (!CompResultTy.isNull())
4984 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004985 break;
4986 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004987 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4988 if (!CompResultTy.isNull())
4989 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004990 break;
4991 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004992 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4993 if (!CompResultTy.isNull())
4994 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004995 break;
4996 case BinaryOperator::ShlAssign:
4997 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004998 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4999 CompLHSTy = CompResultTy;
5000 if (!CompResultTy.isNull())
5001 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005002 break;
5003 case BinaryOperator::AndAssign:
5004 case BinaryOperator::XorAssign:
5005 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005006 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5007 CompLHSTy = CompResultTy;
5008 if (!CompResultTy.isNull())
5009 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005010 break;
5011 case BinaryOperator::Comma:
5012 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5013 break;
5014 }
5015 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005016 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005017 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005018 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5019 else
5020 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005021 CompLHSTy, CompResultTy,
5022 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005023}
5024
Chris Lattner4b009652007-07-25 00:24:17 +00005025// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005026Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5027 tok::TokenKind Kind,
5028 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005029 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005030 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005031
Steve Naroff87d58b42007-09-16 03:34:24 +00005032 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5033 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005034
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005035 if (getLangOptions().CPlusPlus &&
5036 (lhs->getType()->isOverloadableType() ||
5037 rhs->getType()->isOverloadableType())) {
5038 // Find all of the overloaded operators visible from this
5039 // point. We perform both an operator-name lookup from the local
5040 // scope and an argument-dependent lookup based on the types of
5041 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005042 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005043 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5044 if (OverOp != OO_None) {
5045 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5046 Functions);
5047 Expr *Args[2] = { lhs, rhs };
5048 DeclarationName OpName
5049 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5050 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005051 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005052
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005053 // Build the (potentially-overloaded, potentially-dependent)
5054 // binary operation.
5055 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005056 }
5057
Douglas Gregord7f915e2008-11-06 23:29:22 +00005058 // Build a built-in binary operation.
5059 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005060}
5061
Douglas Gregorc78182d2009-03-13 23:49:33 +00005062Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5063 unsigned OpcIn,
5064 ExprArg InputArg) {
5065 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005066
Mike Stumpe127ae32009-05-16 07:39:55 +00005067 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005068 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005069 QualType resultType;
5070 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005071 case UnaryOperator::OffsetOf:
5072 assert(false && "Invalid unary operator");
5073 break;
5074
Chris Lattner4b009652007-07-25 00:24:17 +00005075 case UnaryOperator::PreInc:
5076 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005077 case UnaryOperator::PostInc:
5078 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005079 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005080 Opc == UnaryOperator::PreInc ||
5081 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005082 break;
Mike Stump9afab102009-02-19 03:04:26 +00005083 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005084 resultType = CheckAddressOfOperand(Input, OpLoc);
5085 break;
Mike Stump9afab102009-02-19 03:04:26 +00005086 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005087 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005088 resultType = CheckIndirectionOperand(Input, OpLoc);
5089 break;
5090 case UnaryOperator::Plus:
5091 case UnaryOperator::Minus:
5092 UsualUnaryConversions(Input);
5093 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005094 if (resultType->isDependentType())
5095 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005096 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5097 break;
5098 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5099 resultType->isEnumeralType())
5100 break;
5101 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5102 Opc == UnaryOperator::Plus &&
5103 resultType->isPointerType())
5104 break;
5105
Sebastian Redl8b769972009-01-19 00:08:26 +00005106 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5107 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005108 case UnaryOperator::Not: // bitwise complement
5109 UsualUnaryConversions(Input);
5110 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005111 if (resultType->isDependentType())
5112 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005113 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5114 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5115 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005116 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005117 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005118 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005119 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5120 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005121 break;
5122 case UnaryOperator::LNot: // logical negation
5123 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5124 DefaultFunctionArrayConversion(Input);
5125 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005126 if (resultType->isDependentType())
5127 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005128 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005129 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5130 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005131 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005132 // In C++, it's bool. C++ 5.3.1p8
5133 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005134 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005135 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005136 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005137 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005138 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005139 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005140 resultType = Input->getType();
5141 break;
5142 }
5143 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005144 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005145
5146 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005147 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005148}
5149
Douglas Gregorc78182d2009-03-13 23:49:33 +00005150// Unary Operators. 'Tok' is the token for the operator.
5151Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5152 tok::TokenKind Op, ExprArg input) {
5153 Expr *Input = (Expr*)input.get();
5154 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5155
5156 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5157 // Find all of the overloaded operators visible from this
5158 // point. We perform both an operator-name lookup from the local
5159 // scope and an argument-dependent lookup based on the types of
5160 // the arguments.
5161 FunctionSet Functions;
5162 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5163 if (OverOp != OO_None) {
5164 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5165 Functions);
5166 DeclarationName OpName
5167 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5168 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5169 }
5170
5171 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5172 }
5173
5174 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5175}
5176
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005177/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005178Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5179 SourceLocation LabLoc,
5180 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005181 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005182 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005183
Daniel Dunbar879788d2008-08-04 16:51:22 +00005184 // If we haven't seen this label yet, create a forward reference. It
5185 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005186 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005187 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005188
Chris Lattner4b009652007-07-25 00:24:17 +00005189 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005190 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5191 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005192}
5193
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005194Sema::OwningExprResult
5195Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5196 SourceLocation RPLoc) { // "({..})"
5197 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005198 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5199 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5200
Eli Friedmanbc941e12009-01-24 23:09:00 +00005201 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005202 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005203 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005204
Chris Lattner4b009652007-07-25 00:24:17 +00005205 // FIXME: there are a variety of strange constraints to enforce here, for
5206 // example, it is not possible to goto into a stmt expression apparently.
5207 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005208
Chris Lattner4b009652007-07-25 00:24:17 +00005209 // If there are sub stmts in the compound stmt, take the type of the last one
5210 // as the type of the stmtexpr.
5211 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005212
Chris Lattner200964f2008-07-26 19:51:01 +00005213 if (!Compound->body_empty()) {
5214 Stmt *LastStmt = Compound->body_back();
5215 // If LastStmt is a label, skip down through into the body.
5216 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5217 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005218
Chris Lattner200964f2008-07-26 19:51:01 +00005219 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005220 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005221 }
Mike Stump9afab102009-02-19 03:04:26 +00005222
Eli Friedman2b128322009-03-23 00:24:07 +00005223 // FIXME: Check that expression type is complete/non-abstract; statement
5224 // expressions are not lvalues.
5225
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005226 substmt.release();
5227 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005228}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005229
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005230Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5231 SourceLocation BuiltinLoc,
5232 SourceLocation TypeLoc,
5233 TypeTy *argty,
5234 OffsetOfComponent *CompPtr,
5235 unsigned NumComponents,
5236 SourceLocation RPLoc) {
5237 // FIXME: This function leaks all expressions in the offset components on
5238 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005239 QualType ArgTy = QualType::getFromOpaquePtr(argty);
5240 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005241
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005242 bool Dependent = ArgTy->isDependentType();
5243
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005244 // We must have at least one component that refers to the type, and the first
5245 // one is known to be a field designator. Verify that the ArgTy represents
5246 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005247 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005248 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005249
Eli Friedman2b128322009-03-23 00:24:07 +00005250 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5251 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005252
Eli Friedman342d9432009-02-27 06:44:11 +00005253 // Otherwise, create a null pointer as the base, and iteratively process
5254 // the offsetof designators.
5255 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5256 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005257 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005258 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005259
Chris Lattnerb37522e2007-08-31 21:49:13 +00005260 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5261 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005262 // FIXME: This diagnostic isn't actually visible because the location is in
5263 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005264 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005265 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5266 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005267
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005268 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005269 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005270
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005271 // FIXME: Dependent case loses a lot of information here. And probably
5272 // leaks like a sieve.
5273 for (unsigned i = 0; i != NumComponents; ++i) {
5274 const OffsetOfComponent &OC = CompPtr[i];
5275 if (OC.isBrackets) {
5276 // Offset of an array sub-field. TODO: Should we allow vector elements?
5277 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5278 if (!AT) {
5279 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005280 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5281 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005282 }
5283
5284 // FIXME: C++: Verify that operator[] isn't overloaded.
5285
Eli Friedman342d9432009-02-27 06:44:11 +00005286 // Promote the array so it looks more like a normal array subscript
5287 // expression.
5288 DefaultFunctionArrayConversion(Res);
5289
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005290 // C99 6.5.2.1p1
5291 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005292 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005293 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005294 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005295 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005296 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005297
5298 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5299 OC.LocEnd);
5300 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005301 }
Mike Stump9afab102009-02-19 03:04:26 +00005302
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00005303 const RecordType *RC = Res->getType()->getAsRecordType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005304 if (!RC) {
5305 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005306 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5307 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005308 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005309
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005310 // Get the decl corresponding to this.
5311 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005312 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005313 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005314 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5315 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5316 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005317 DidWarnAboutNonPOD = true;
5318 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005319 }
5320
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005321 FieldDecl *MemberDecl
5322 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5323 LookupMemberName)
5324 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005325 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005326 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005327 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5328 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005329
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005330 // FIXME: C++: Verify that MemberDecl isn't a static field.
5331 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005332 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005333 Res = BuildAnonymousStructUnionMemberReference(
5334 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005335 } else {
5336 // MemberDecl->getType() doesn't get the right qualifiers, but it
5337 // doesn't matter here.
5338 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5339 MemberDecl->getType().getNonReferenceType());
5340 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005341 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005342 }
Mike Stump9afab102009-02-19 03:04:26 +00005343
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005344 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5345 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005346}
5347
5348
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005349Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5350 TypeTy *arg1,TypeTy *arg2,
5351 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00005352 QualType argT1 = QualType::getFromOpaquePtr(arg1);
5353 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005354
Steve Naroff63bad2d2007-08-01 22:05:33 +00005355 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005356
Douglas Gregore6211502009-05-19 22:28:02 +00005357 if (getLangOptions().CPlusPlus) {
5358 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5359 << SourceRange(BuiltinLoc, RPLoc);
5360 return ExprError();
5361 }
5362
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005363 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5364 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005365}
5366
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005367Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5368 ExprArg cond,
5369 ExprArg expr1, ExprArg expr2,
5370 SourceLocation RPLoc) {
5371 Expr *CondExpr = static_cast<Expr*>(cond.get());
5372 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5373 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005374
Steve Naroff93c53012007-08-03 21:21:27 +00005375 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5376
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005377 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005378 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005379 resType = Context.DependentTy;
5380 } else {
5381 // The conditional expression is required to be a constant expression.
5382 llvm::APSInt condEval(32);
5383 SourceLocation ExpLoc;
5384 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005385 return ExprError(Diag(ExpLoc,
5386 diag::err_typecheck_choose_expr_requires_constant)
5387 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005388
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005389 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5390 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5391 }
5392
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005393 cond.release(); expr1.release(); expr2.release();
5394 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5395 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005396}
5397
Steve Naroff52a81c02008-09-03 18:15:37 +00005398//===----------------------------------------------------------------------===//
5399// Clang Extensions.
5400//===----------------------------------------------------------------------===//
5401
5402/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005403void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005404 // Analyze block parameters.
5405 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005406
Steve Naroff52a81c02008-09-03 18:15:37 +00005407 // Add BSI to CurBlock.
5408 BSI->PrevBlockInfo = CurBlock;
5409 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005410
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005411 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005412 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005413 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005414 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005415 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5416 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005417
Steve Naroff52059382008-10-10 01:28:17 +00005418 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005419 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005420}
5421
Mike Stumpc1fddff2009-02-04 22:31:32 +00005422void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005423 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005424
5425 if (ParamInfo.getNumTypeObjects() == 0
5426 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005427 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005428 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5429
Mike Stump458287d2009-04-28 01:10:27 +00005430 if (T->isArrayType()) {
5431 Diag(ParamInfo.getSourceRange().getBegin(),
5432 diag::err_block_returns_array);
5433 return;
5434 }
5435
Mike Stumpc1fddff2009-02-04 22:31:32 +00005436 // The parameter list is optional, if there was none, assume ().
5437 if (!T->isFunctionType())
5438 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5439
5440 CurBlock->hasPrototype = true;
5441 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005442 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005443 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005444 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005445 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005446 // FIXME: remove the attribute.
5447 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005448 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5449
5450 // Do not allow returning a objc interface by-value.
5451 if (RetTy->isObjCInterfaceType()) {
5452 Diag(ParamInfo.getSourceRange().getBegin(),
5453 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5454 return;
5455 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005456 return;
5457 }
5458
Steve Naroff52a81c02008-09-03 18:15:37 +00005459 // Analyze arguments to block.
5460 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5461 "Not a function declarator!");
5462 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005463
Steve Naroff52059382008-10-10 01:28:17 +00005464 CurBlock->hasPrototype = FTI.hasPrototype;
5465 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005466
Steve Naroff52a81c02008-09-03 18:15:37 +00005467 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5468 // no arguments, not a function that takes a single void argument.
5469 if (FTI.hasPrototype &&
5470 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005471 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5472 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005473 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005474 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005475 } else if (FTI.hasPrototype) {
5476 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005477 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005478 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005479 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005480 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005481 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005482 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005483 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005484 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5485 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5486 // If this has an identifier, add it to the scope stack.
5487 if ((*AI)->getIdentifier())
5488 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005489
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005490 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005491 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005492 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005493 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005494 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005495 // FIXME: remove the attribute.
5496 }
5497
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005498 // Analyze the return type.
5499 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5500 QualType RetTy = T->getAsFunctionType()->getResultType();
5501
5502 // Do not allow returning a objc interface by-value.
5503 if (RetTy->isObjCInterfaceType()) {
5504 Diag(ParamInfo.getSourceRange().getBegin(),
5505 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5506 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005507 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005508}
5509
5510/// ActOnBlockError - If there is an error parsing a block, this callback
5511/// is invoked to pop the information about the block from the action impl.
5512void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5513 // Ensure that CurBlock is deleted.
5514 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005515
Chris Lattnere7765e12009-04-19 05:28:12 +00005516 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5517
Steve Naroff52a81c02008-09-03 18:15:37 +00005518 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005519 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005520 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005521 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005522}
5523
5524/// ActOnBlockStmtExpr - This is called when the body of a block statement
5525/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005526Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5527 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005528 // If blocks are disabled, emit an error.
5529 if (!LangOpts.Blocks)
5530 Diag(CaretLoc, diag::err_blocks_disable);
5531
Steve Naroff52a81c02008-09-03 18:15:37 +00005532 // Ensure that CurBlock is deleted.
5533 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005534
Steve Naroff52059382008-10-10 01:28:17 +00005535 PopDeclContext();
5536
Steve Naroff52a81c02008-09-03 18:15:37 +00005537 // Pop off CurBlock, handle nested blocks.
5538 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005539
Steve Naroff52a81c02008-09-03 18:15:37 +00005540 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005541 if (!BSI->ReturnType.isNull())
5542 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005543
Steve Naroff52a81c02008-09-03 18:15:37 +00005544 llvm::SmallVector<QualType, 8> ArgTypes;
5545 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5546 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005547
Mike Stump8e288f42009-07-28 22:04:01 +00005548 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005549 QualType BlockTy;
5550 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005551 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5552 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005553 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005554 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005555 BSI->isVariadic, 0, false, false, 0, 0,
5556 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005557
Eli Friedman2b128322009-03-23 00:24:07 +00005558 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005559 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005560 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005561
Chris Lattnere7765e12009-04-19 05:28:12 +00005562 // If needed, diagnose invalid gotos and switches in the block.
5563 if (CurFunctionNeedsScopeChecking)
5564 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5565 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5566
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005567 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005568 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005569 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5570 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005571}
5572
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005573Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5574 ExprArg expr, TypeTy *type,
5575 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005576 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005577 Expr *E = static_cast<Expr*>(expr.get());
5578 Expr *OrigExpr = E;
5579
Anders Carlsson36760332007-10-15 20:28:48 +00005580 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005581
5582 // Get the va_list type
5583 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005584 if (VaListType->isArrayType()) {
5585 // Deal with implicit array decay; for example, on x86-64,
5586 // va_list is an array, but it's supposed to decay to
5587 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005588 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005589 // Make sure the input expression also decays appropriately.
5590 UsualUnaryConversions(E);
5591 } else {
5592 // Otherwise, the va_list argument must be an l-value because
5593 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005594 if (!E->isTypeDependent() &&
5595 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005596 return ExprError();
5597 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005598
Douglas Gregor25990972009-05-19 23:10:31 +00005599 if (!E->isTypeDependent() &&
5600 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005601 return ExprError(Diag(E->getLocStart(),
5602 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005603 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005604 }
Mike Stump9afab102009-02-19 03:04:26 +00005605
Eli Friedman2b128322009-03-23 00:24:07 +00005606 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005607 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005608
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005609 expr.release();
5610 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5611 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005612}
5613
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005614Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005615 // The type of __null will be int or long, depending on the size of
5616 // pointers on the target.
5617 QualType Ty;
5618 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5619 Ty = Context.IntTy;
5620 else
5621 Ty = Context.LongTy;
5622
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005623 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005624}
5625
Chris Lattner005ed752008-01-04 18:04:52 +00005626bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5627 SourceLocation Loc,
5628 QualType DstType, QualType SrcType,
5629 Expr *SrcExpr, const char *Flavor) {
5630 // Decode the result (notice that AST's are still created for extensions).
5631 bool isInvalid = false;
5632 unsigned DiagKind;
5633 switch (ConvTy) {
5634 default: assert(0 && "Unknown conversion type");
5635 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005636 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005637 DiagKind = diag::ext_typecheck_convert_pointer_int;
5638 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005639 case IntToPointer:
5640 DiagKind = diag::ext_typecheck_convert_int_pointer;
5641 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005642 case IncompatiblePointer:
5643 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5644 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005645 case IncompatiblePointerSign:
5646 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5647 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005648 case FunctionVoidPointer:
5649 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5650 break;
5651 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005652 // If the qualifiers lost were because we were applying the
5653 // (deprecated) C++ conversion from a string literal to a char*
5654 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5655 // Ideally, this check would be performed in
5656 // CheckPointerTypesForAssignment. However, that would require a
5657 // bit of refactoring (so that the second argument is an
5658 // expression, rather than a type), which should be done as part
5659 // of a larger effort to fix CheckPointerTypesForAssignment for
5660 // C++ semantics.
5661 if (getLangOptions().CPlusPlus &&
5662 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5663 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005664 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5665 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005666 case IntToBlockPointer:
5667 DiagKind = diag::err_int_to_block_pointer;
5668 break;
5669 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005670 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005671 break;
Steve Naroff19608432008-10-14 22:18:38 +00005672 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005673 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005674 // it can give a more specific diagnostic.
5675 DiagKind = diag::warn_incompatible_qualified_id;
5676 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005677 case IncompatibleVectors:
5678 DiagKind = diag::warn_incompatible_vectors;
5679 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005680 case Incompatible:
5681 DiagKind = diag::err_typecheck_convert_incompatible;
5682 isInvalid = true;
5683 break;
5684 }
Mike Stump9afab102009-02-19 03:04:26 +00005685
Chris Lattner271d4c22008-11-24 05:29:24 +00005686 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5687 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005688 return isInvalid;
5689}
Anders Carlssond5201b92008-11-30 19:50:32 +00005690
Chris Lattnereec8ae22009-04-25 21:59:05 +00005691bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005692 llvm::APSInt ICEResult;
5693 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5694 if (Result)
5695 *Result = ICEResult;
5696 return false;
5697 }
5698
Anders Carlssond5201b92008-11-30 19:50:32 +00005699 Expr::EvalResult EvalResult;
5700
Mike Stump9afab102009-02-19 03:04:26 +00005701 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005702 EvalResult.HasSideEffects) {
5703 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5704
5705 if (EvalResult.Diag) {
5706 // We only show the note if it's not the usual "invalid subexpression"
5707 // or if it's actually in a subexpression.
5708 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5709 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5710 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5711 }
Mike Stump9afab102009-02-19 03:04:26 +00005712
Anders Carlssond5201b92008-11-30 19:50:32 +00005713 return true;
5714 }
5715
Eli Friedmance329412009-04-25 22:26:58 +00005716 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5717 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005718
Eli Friedmance329412009-04-25 22:26:58 +00005719 if (EvalResult.Diag &&
5720 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5721 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005722
Anders Carlssond5201b92008-11-30 19:50:32 +00005723 if (Result)
5724 *Result = EvalResult.Val.getInt();
5725 return false;
5726}
Douglas Gregor98189262009-06-19 23:52:42 +00005727
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005728Sema::ExpressionEvaluationContext
5729Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5730 // Introduce a new set of potentially referenced declarations to the stack.
5731 if (NewContext == PotentiallyPotentiallyEvaluated)
5732 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5733
5734 std::swap(ExprEvalContext, NewContext);
5735 return NewContext;
5736}
5737
5738void
5739Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5740 ExpressionEvaluationContext NewContext) {
5741 ExprEvalContext = NewContext;
5742
5743 if (OldContext == PotentiallyPotentiallyEvaluated) {
5744 // Mark any remaining declarations in the current position of the stack
5745 // as "referenced". If they were not meant to be referenced, semantic
5746 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5747 PotentiallyReferencedDecls RemainingDecls;
5748 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5749 PotentiallyReferencedDeclStack.pop_back();
5750
5751 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5752 IEnd = RemainingDecls.end();
5753 I != IEnd; ++I)
5754 MarkDeclarationReferenced(I->first, I->second);
5755 }
5756}
Douglas Gregor98189262009-06-19 23:52:42 +00005757
5758/// \brief Note that the given declaration was referenced in the source code.
5759///
5760/// This routine should be invoke whenever a given declaration is referenced
5761/// in the source code, and where that reference occurred. If this declaration
5762/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5763/// C99 6.9p3), then the declaration will be marked as used.
5764///
5765/// \param Loc the location where the declaration was referenced.
5766///
5767/// \param D the declaration that has been referenced by the source code.
5768void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5769 assert(D && "No declaration?");
5770
Douglas Gregorcad27f62009-06-22 23:06:13 +00005771 if (D->isUsed())
5772 return;
5773
Douglas Gregor98189262009-06-19 23:52:42 +00005774 // Mark a parameter declaration "used", regardless of whether we're in a
5775 // template or not.
5776 if (isa<ParmVarDecl>(D))
5777 D->setUsed(true);
5778
5779 // Do not mark anything as "used" within a dependent context; wait for
5780 // an instantiation.
5781 if (CurContext->isDependentContext())
5782 return;
5783
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005784 switch (ExprEvalContext) {
5785 case Unevaluated:
5786 // We are in an expression that is not potentially evaluated; do nothing.
5787 return;
5788
5789 case PotentiallyEvaluated:
5790 // We are in a potentially-evaluated expression, so this declaration is
5791 // "used"; handle this below.
5792 break;
5793
5794 case PotentiallyPotentiallyEvaluated:
5795 // We are in an expression that may be potentially evaluated; queue this
5796 // declaration reference until we know whether the expression is
5797 // potentially evaluated.
5798 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5799 return;
5800 }
5801
Douglas Gregor98189262009-06-19 23:52:42 +00005802 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005803 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005804 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005805 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5806 if (!Constructor->isUsed())
5807 DefineImplicitDefaultConstructor(Loc, Constructor);
5808 }
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005809 else if (Constructor->isImplicit() &&
5810 Constructor->isCopyConstructor(Context, TypeQuals)) {
5811 if (!Constructor->isUsed())
5812 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5813 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005814 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5815 if (Destructor->isImplicit() && !Destructor->isUsed())
5816 DefineImplicitDestructor(Loc, Destructor);
5817
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005818 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5819 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5820 MethodDecl->getOverloadedOperator() == OO_Equal) {
5821 if (!MethodDecl->isUsed())
5822 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5823 }
5824 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005825 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005826 // Implicit instantiation of function templates and member functions of
5827 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005828 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005829 // FIXME: distinguish between implicit instantiations of function
5830 // templates and explicit specializations (the latter don't get
5831 // instantiated, naturally).
5832 if (Function->getInstantiatedFromMemberFunction() ||
5833 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005834 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005835 }
5836
5837
Douglas Gregor98189262009-06-19 23:52:42 +00005838 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005839 Function->setUsed(true);
5840 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005841 }
Douglas Gregor98189262009-06-19 23:52:42 +00005842
5843 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005844 // Implicit instantiation of static data members of class templates.
5845 // FIXME: distinguish between implicit instantiations (which we need to
5846 // actually instantiate) and explicit specializations.
5847 if (Var->isStaticDataMember() &&
5848 Var->getInstantiatedFromStaticDataMember())
5849 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5850
Douglas Gregor98189262009-06-19 23:52:42 +00005851 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00005852
Douglas Gregor98189262009-06-19 23:52:42 +00005853 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00005854 return;
5855}
Douglas Gregor98189262009-06-19 23:52:42 +00005856}
5857