blob: ef8165e167159868206a0f5b26e87c369b92bf2f [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
David Chisnall44663db2009-08-17 16:35:33 +000029
Douglas Gregoraa57e862009-02-18 21:56:37 +000030/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000042 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000043 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000044 // Implementing deprecated stuff requires referencing deprecated
45 // stuff. Don't warn if we are implementing a deprecated
46 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000047 bool isSilenced = false;
48
49 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50 // If this reference happens *in* a deprecated function or method, don't
51 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000052 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000053
54 // If this is an Objective-C method implementation, check to see if the
55 // method was deprecated on the declaration, not the definition.
56 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57 // The semantic decl context of a ObjCMethodDecl is the
58 // ObjCImplementationDecl.
59 if (ObjCImplementationDecl *Impl
60 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000062 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000064 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000065 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000083 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian180f3412009-05-13 18:09:35 +000091/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96 Expr **Args, unsigned NumArgs)
97{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000099 if (!attr)
100 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000103
Mike Stumpe127ae32009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000150 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000151 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000181}
182
Douglas Gregor3bb30002009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner299b8842008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner299b8842008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
198 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000199 else if (Ty->isArrayType()) {
200 // In C90 mode, arrays only promote to pointers if the array expression is
201 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202 // type 'array of type' is converted to an expression that has type 'pointer
203 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
204 // that has type 'array of type' ...". The relevant change is "an lvalue"
205 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000206 //
207 // C++ 4.2p1:
208 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209 // T" can be converted to an rvalue of type "pointer to T".
210 //
211 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000213 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000215 }
Chris Lattner299b8842008-07-25 21:10:04 +0000216}
217
Douglas Gregor70b307e2009-05-01 20:41:21 +0000218/// \brief Whether this is a promotable bitfield reference according
219/// to C99 6.3.1.1p2, bullet 2.
220///
221/// \returns the type this bit-field will promote to, or NULL if no
222/// promotion occurs.
223static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000224 FieldDecl *Field = E->getBitField();
225 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000226 return QualType();
227
228 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
229 if (!BT)
230 return QualType();
231
232 if (BT->getKind() != BuiltinType::Bool &&
233 BT->getKind() != BuiltinType::Int &&
234 BT->getKind() != BuiltinType::UInt)
235 return QualType();
236
237 llvm::APSInt BitWidthAP;
238 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
239 return QualType();
240
241 uint64_t BitWidth = BitWidthAP.getZExtValue();
242 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
243 if (BitWidth < IntSize ||
244 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
245 return Context.IntTy;
246
247 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
248 return Context.UnsignedIntTy;
249
250 return QualType();
251}
252
Chris Lattner299b8842008-07-25 21:10:04 +0000253/// UsualUnaryConversions - Performs various conversions that are common to most
254/// operators (C99 6.3). The conversions of array and function types are
255/// sometimes surpressed. For example, the array->pointer conversion doesn't
256/// apply if the array is an argument to the sizeof or address (&) operators.
257/// In these instances, this routine should *not* be called.
258Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
259 QualType Ty = Expr->getType();
260 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
261
Douglas Gregor70b307e2009-05-01 20:41:21 +0000262 // C99 6.3.1.1p2:
263 //
264 // The following may be used in an expression wherever an int or
265 // unsigned int may be used:
266 // - an object or expression with an integer type whose integer
267 // conversion rank is less than or equal to the rank of int
268 // and unsigned int.
269 // - A bit-field of type _Bool, int, signed int, or unsigned int.
270 //
271 // If an int can represent all values of the original type, the
272 // value is converted to an int; otherwise, it is converted to an
273 // unsigned int. These are called the integer promotions. All
274 // other types are unchanged by the integer promotions.
275 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000276 QualType PT = Context.getPromotedIntegerType(Ty);
277 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000278 return Expr;
279 } else {
280 QualType T = isPromotableBitField(Expr, Context);
281 if (!T.isNull()) {
282 ImpCastExprToType(Expr, T);
283 return Expr;
284 }
285 }
286
287 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000288 return Expr;
289}
290
Chris Lattner9305c3d2008-07-25 22:25:12 +0000291/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
292/// do not have a prototype. Arguments that have type float are promoted to
293/// double. All other argument types are converted by UsualUnaryConversions().
294void Sema::DefaultArgumentPromotion(Expr *&Expr) {
295 QualType Ty = Expr->getType();
296 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
297
298 // If this is a 'float' (CVR qualified or typedef) promote to double.
299 if (const BuiltinType *BT = Ty->getAsBuiltinType())
300 if (BT->getKind() == BuiltinType::Float)
301 return ImpCastExprToType(Expr, Context.DoubleTy);
302
303 UsualUnaryConversions(Expr);
304}
305
Chris Lattner81f00ed2009-04-12 08:11:20 +0000306/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
307/// will warn if the resulting type is not a POD type, and rejects ObjC
308/// interfaces passed by value. This returns true if the argument type is
309/// completely illegal.
310bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000311 DefaultArgumentPromotion(Expr);
312
Chris Lattner81f00ed2009-04-12 08:11:20 +0000313 if (Expr->getType()->isObjCInterfaceType()) {
314 Diag(Expr->getLocStart(),
315 diag::err_cannot_pass_objc_interface_to_vararg)
316 << Expr->getType() << CT;
317 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000318 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000319
320 if (!Expr->getType()->isPODType())
321 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
322 << Expr->getType() << CT;
323
324 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000325}
326
327
Chris Lattner299b8842008-07-25 21:10:04 +0000328/// UsualArithmeticConversions - Performs various conversions that are common to
329/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
330/// routine returns the first non-arithmetic type found. The client is
331/// responsible for emitting appropriate error diagnostics.
332/// FIXME: verify the conversion rules for "complex int" are consistent with
333/// GCC.
334QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
335 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000336 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000337 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000338
339 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000340
Chris Lattner299b8842008-07-25 21:10:04 +0000341 // For conversion purposes, we ignore any qualifiers.
342 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000343 QualType lhs =
344 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
345 QualType rhs =
346 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000347
348 // If both types are identical, no conversion is needed.
349 if (lhs == rhs)
350 return lhs;
351
352 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
353 // The caller can deal with this (e.g. pointer + int).
354 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
355 return lhs;
356
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000357 // Perform bitfield promotions.
358 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
359 if (!LHSBitfieldPromoteTy.isNull())
360 lhs = LHSBitfieldPromoteTy;
361 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
362 if (!RHSBitfieldPromoteTy.isNull())
363 rhs = RHSBitfieldPromoteTy;
364
Eli Friedman6ae7d112009-08-19 07:44:53 +0000365 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000366 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000367 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000368 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000369 return destType;
370}
371
Chris Lattner299b8842008-07-25 21:10:04 +0000372//===----------------------------------------------------------------------===//
373// Semantic Analysis for various Expression Types
374//===----------------------------------------------------------------------===//
375
376
Steve Naroff87d58b42007-09-16 03:34:24 +0000377/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000378/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
379/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
380/// multiple tokens. However, the common case is that StringToks points to one
381/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000382///
383Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000384Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000385 assert(NumStringToks && "Must have at least one string!");
386
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000387 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000388 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000389 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000390
391 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
392 for (unsigned i = 0; i != NumStringToks; ++i)
393 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000394
Chris Lattnera6dcce32008-02-11 00:02:17 +0000395 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000396 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000397 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000398
399 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
400 if (getLangOptions().CPlusPlus)
401 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000402
Chris Lattnera6dcce32008-02-11 00:02:17 +0000403 // Get an array type for the string, according to C99 6.4.5. This includes
404 // the nul terminator character as well as the string length for pascal
405 // strings.
406 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000407 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000408 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000409
Chris Lattner4b009652007-07-25 00:24:17 +0000410 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000411 return Owned(StringLiteral::Create(Context, Literal.GetString(),
412 Literal.GetStringLength(),
413 Literal.AnyWide, StrTy,
414 &StringTokLocs[0],
415 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000416}
417
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000418/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
419/// CurBlock to VD should cause it to be snapshotted (as we do for auto
420/// variables defined outside the block) or false if this is not needed (e.g.
421/// for values inside the block or for globals).
422///
Chris Lattner0b464252009-04-21 22:26:47 +0000423/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
424/// up-to-date.
425///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000426static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
427 ValueDecl *VD) {
428 // If the value is defined inside the block, we couldn't snapshot it even if
429 // we wanted to.
430 if (CurBlock->TheDecl == VD->getDeclContext())
431 return false;
432
433 // If this is an enum constant or function, it is constant, don't snapshot.
434 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
435 return false;
436
437 // If this is a reference to an extern, static, or global variable, no need to
438 // snapshot it.
439 // FIXME: What about 'const' variables in C++?
440 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000441 if (!Var->hasLocalStorage())
442 return false;
443
444 // Blocks that have these can't be constant.
445 CurBlock->hasBlockDeclRefExprs = true;
446
447 // If we have nested blocks, the decl may be declared in an outer block (in
448 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
449 // be defined outside all of the current blocks (in which case the blocks do
450 // all get the bit). Walk the nesting chain.
451 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
452 NextBlock = NextBlock->PrevBlockInfo) {
453 // If we found the defining block for the variable, don't mark the block as
454 // having a reference outside it.
455 if (NextBlock->TheDecl == VD->getDeclContext())
456 break;
457
458 // Otherwise, the DeclRef from the inner block causes the outer one to need
459 // a snapshot as well.
460 NextBlock->hasBlockDeclRefExprs = true;
461 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000462
463 return true;
464}
465
466
467
Steve Naroff0acc9c92007-09-15 18:49:24 +0000468/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000469/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000470/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000471/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000472/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000473Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
474 IdentifierInfo &II,
475 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000476 const CXXScopeSpec *SS,
477 bool isAddressOfOperand) {
478 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000479 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000480}
481
Douglas Gregor566782a2009-01-06 05:10:23 +0000482/// BuildDeclRefExpr - Build either a DeclRefExpr or a
483/// QualifiedDeclRefExpr based on whether or not SS is a
484/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000485Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000486Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
487 bool TypeDependent, bool ValueDependent,
488 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000489 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
490 Diag(Loc,
491 diag::err_auto_variable_cannot_appear_in_own_initializer)
492 << D->getDeclName();
493 return ExprError();
494 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000495
496 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
497 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
498 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
499 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
500 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
501 << D->getIdentifier() << FD->getDeclName();
502 Diag(D->getLocation(), diag::note_local_variable_declared_here)
503 << D->getIdentifier();
504 return ExprError();
505 }
506 }
507 }
508 }
509
Douglas Gregor98189262009-06-19 23:52:42 +0000510 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000511
512 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000513 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000514 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
515 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000516 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000517 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000518 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
519
520 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000521}
522
Douglas Gregor723d3332009-01-07 00:43:41 +0000523/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
524/// variable corresponding to the anonymous union or struct whose type
525/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000526static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
527 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000528 assert(Record->isAnonymousStructOrUnion() &&
529 "Record must be an anonymous struct or union!");
530
Mike Stumpe127ae32009-05-16 07:39:55 +0000531 // FIXME: Once Decls are directly linked together, this will be an O(1)
532 // operation rather than a slow walk through DeclContext's vector (which
533 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000534 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000535 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
536 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000537 D != DEnd; ++D) {
538 if (*D == Record) {
539 // The object for the anonymous struct/union directly
540 // follows its type in the list of declarations.
541 ++D;
542 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000543 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000544 return *D;
545 }
546 }
547
548 assert(false && "Missing object for anonymous record");
549 return 0;
550}
551
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000552/// \brief Given a field that represents a member of an anonymous
553/// struct/union, build the path from that field's context to the
554/// actual member.
555///
556/// Construct the sequence of field member references we'll have to
557/// perform to get to the field in the anonymous union/struct. The
558/// list of members is built from the field outward, so traverse it
559/// backwards to go from an object in the current context to the field
560/// we found.
561///
562/// \returns The variable from which the field access should begin,
563/// for an anonymous struct/union that is not a member of another
564/// class. Otherwise, returns NULL.
565VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
566 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000567 assert(Field->getDeclContext()->isRecord() &&
568 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
569 && "Field must be stored inside an anonymous struct or union");
570
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000571 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000572 VarDecl *BaseObject = 0;
573 DeclContext *Ctx = Field->getDeclContext();
574 do {
575 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000576 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000577 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000578 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000579 else {
580 BaseObject = cast<VarDecl>(AnonObject);
581 break;
582 }
583 Ctx = Ctx->getParent();
584 } while (Ctx->isRecord() &&
585 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000586
587 return BaseObject;
588}
589
590Sema::OwningExprResult
591Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
592 FieldDecl *Field,
593 Expr *BaseObjectExpr,
594 SourceLocation OpLoc) {
595 llvm::SmallVector<FieldDecl *, 4> AnonFields;
596 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
597 AnonFields);
598
Douglas Gregor723d3332009-01-07 00:43:41 +0000599 // Build the expression that refers to the base object, from
600 // which we will build a sequence of member references to each
601 // of the anonymous union objects and, eventually, the field we
602 // found via name lookup.
603 bool BaseObjectIsPointer = false;
604 unsigned ExtraQuals = 0;
605 if (BaseObject) {
606 // BaseObject is an anonymous struct/union variable (and is,
607 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000608 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000609 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000610 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000611 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000612 ExtraQuals
613 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
614 } else if (BaseObjectExpr) {
615 // The caller provided the base object expression. Determine
616 // whether its a pointer and whether it adds any qualifiers to the
617 // anonymous struct/union fields we're looking into.
618 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000619 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000620 BaseObjectIsPointer = true;
621 ObjectType = ObjectPtr->getPointeeType();
622 }
623 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
624 } else {
625 // We've found a member of an anonymous struct/union that is
626 // inside a non-anonymous struct/union, so in a well-formed
627 // program our base object expression is "this".
628 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
629 if (!MD->isStatic()) {
630 QualType AnonFieldType
631 = Context.getTagDeclType(
632 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
633 QualType ThisType = Context.getTagDeclType(MD->getParent());
634 if ((Context.getCanonicalType(AnonFieldType)
635 == Context.getCanonicalType(ThisType)) ||
636 IsDerivedFrom(ThisType, AnonFieldType)) {
637 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000638 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000639 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000640 BaseObjectIsPointer = true;
641 }
642 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000643 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
644 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000645 }
646 ExtraQuals = MD->getTypeQualifiers();
647 }
648
649 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000650 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
651 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000652 }
653
654 // Build the implicit member references to the field of the
655 // anonymous struct/union.
656 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000657 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000658 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
659 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
660 FI != FIEnd; ++FI) {
661 QualType MemberType = (*FI)->getType();
662 if (!(*FI)->isMutable()) {
663 unsigned combinedQualifiers
664 = MemberType.getCVRQualifiers() | ExtraQuals;
665 MemberType = MemberType.getQualifiedType(combinedQualifiers);
666 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000667 if (BaseAddrSpace != MemberType.getAddressSpace())
668 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000669 MarkDeclarationReferenced(Loc, *FI);
Steve Naroff774e4152009-01-21 00:14:39 +0000670 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
671 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000672 BaseObjectIsPointer = false;
673 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000674 }
675
Sebastian Redlcd883f72009-01-18 18:53:16 +0000676 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000677}
678
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000679/// ActOnDeclarationNameExpr - The parser has read some kind of name
680/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
681/// performs lookup on that name and returns an expression that refers
682/// to that name. This routine isn't directly called from the parser,
683/// because the parser doesn't know about DeclarationName. Rather,
684/// this routine is called by ActOnIdentifierExpr,
685/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
686/// which form the DeclarationName from the corresponding syntactic
687/// forms.
688///
689/// HasTrailingLParen indicates whether this identifier is used in a
690/// function call context. LookupCtx is only used for a C++
691/// qualified-id (foo::bar) to indicate the class or namespace that
692/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000693///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000694/// isAddressOfOperand means that this expression is the direct operand
695/// of an address-of operator. This matters because this is the only
696/// situation where a qualified name referencing a non-static member may
697/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000698Sema::OwningExprResult
699Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
700 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000701 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000702 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000703 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000704 if (SS && SS->isInvalid())
705 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000706
707 // C++ [temp.dep.expr]p3:
708 // An id-expression is type-dependent if it contains:
709 // -- a nested-name-specifier that contains a class-name that
710 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000711 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000712 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000713 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
714 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000715 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
716 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000717 }
718
Douglas Gregor411889e2009-02-13 23:20:09 +0000719 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
720 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000721
Sebastian Redlcd883f72009-01-18 18:53:16 +0000722 if (Lookup.isAmbiguous()) {
723 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
724 SS && SS->isSet() ? SS->getRange()
725 : SourceRange());
726 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000727 }
728
729 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000730
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000731 // If this reference is in an Objective-C method, then ivar lookup happens as
732 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000733 IdentifierInfo *II = Name.getAsIdentifierInfo();
734 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000735 // There are two cases to handle here. 1) scoped lookup could have failed,
736 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000737 // found a decl, but that decl is outside the current instance method (i.e.
738 // a global variable). In these two cases, we do a lookup for an ivar with
739 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000740 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000741 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000742 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000743 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000744 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000745 if (DiagnoseUseOfDecl(IV, Loc))
746 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000747
748 // If we're referencing an invalid decl, just return this as a silent
749 // error node. The error diagnostic was already emitted on the decl.
750 if (IV->isInvalidDecl())
751 return ExprError();
752
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000753 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
754 // If a class method attemps to use a free standing ivar, this is
755 // an error.
756 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
757 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
758 << IV->getDeclName());
759 // If a class method uses a global variable, even if an ivar with
760 // same name exists, use the global.
761 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000762 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
763 ClassDeclared != IFace)
764 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000765 // FIXME: This should use a new expr for a direct reference, don't
766 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000767 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000768 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
769 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000770 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000771 return Owned(new (Context)
772 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000773 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000774 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000775 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000776 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000777 // We should warn if a local variable hides an ivar.
778 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000779 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000780 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000781 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
782 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000783 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000784 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000785 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000786 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000787 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000788 QualType T;
789
790 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000791 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
792 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000793 else
794 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000795 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000796 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000797 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000798
Douglas Gregoraa57e862009-02-18 21:56:37 +0000799 // Determine whether this name might be a candidate for
800 // argument-dependent lookup.
801 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
802 HasTrailingLParen;
803
804 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000805 // We've seen something of the form
806 //
807 // identifier(
808 //
809 // and we did not find any entity by the name
810 // "identifier". However, this identifier is still subject to
811 // argument-dependent lookup, so keep track of the name.
812 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
813 Context.OverloadTy,
814 Loc));
815 }
816
Chris Lattner4b009652007-07-25 00:24:17 +0000817 if (D == 0) {
818 // Otherwise, this could be an implicitly declared function reference (legal
819 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000820 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000821 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000822 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000823 else {
824 // If this name wasn't predeclared and if this is not a function call,
825 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000826 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000827 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
828 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000829 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
830 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000831 return ExprError(Diag(Loc, diag::err_undeclared_use)
832 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000833 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000834 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000835 }
836 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000837
838 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
839 // Warn about constructs like:
840 // if (void *X = foo()) { ... } else { X }.
841 // In the else block, the pointer is always false.
842
843 // FIXME: In a template instantiation, we don't have scope
844 // information to check this property.
845 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
846 Scope *CheckS = S;
847 while (CheckS) {
848 if (CheckS->isWithinElse() &&
849 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
850 if (Var->getType()->isBooleanType())
851 ExprError(Diag(Loc, diag::warn_value_always_false)
852 << Var->getDeclName());
853 else
854 ExprError(Diag(Loc, diag::warn_value_always_zero)
855 << Var->getDeclName());
856 break;
857 }
858
859 // Move up one more control parent to check again.
860 CheckS = CheckS->getControlParent();
861 if (CheckS)
862 CheckS = CheckS->getParent();
863 }
864 }
865 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
866 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
867 // C99 DR 316 says that, if a function type comes from a
868 // function definition (without a prototype), that type is only
869 // used for checking compatibility. Therefore, when referencing
870 // the function, we pretend that we don't have the full function
871 // type.
872 if (DiagnoseUseOfDecl(Func, Loc))
873 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000874
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000875 QualType T = Func->getType();
876 QualType NoProtoType = T;
877 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
878 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
879 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
880 }
881 }
882
883 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
884}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000885/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000886bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000887Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
888 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
889 if (CXXRecordDecl *RD =
890 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
891 QualType DestType =
892 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000893 if (DestType->isDependentType() || From->getType()->isDependentType())
894 return false;
895 QualType FromRecordType = From->getType();
896 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000897 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000898 DestType = Context.getPointerType(DestType);
899 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000900 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000901 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
902 CheckDerivedToBaseConversion(FromRecordType,
903 DestRecordType,
904 From->getSourceRange().getBegin(),
905 From->getSourceRange()))
906 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000907 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
908 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000909 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000910 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000911}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000912
913/// \brief Complete semantic analysis for a reference to the given declaration.
914Sema::OwningExprResult
915Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
916 bool HasTrailingLParen,
917 const CXXScopeSpec *SS,
918 bool isAddressOfOperand) {
919 assert(D && "Cannot refer to a NULL declaration");
920 DeclarationName Name = D->getDeclName();
921
Sebastian Redl0c9da212009-02-03 20:19:35 +0000922 // If this is an expression of the form &Class::member, don't build an
923 // implicit member ref, because we want a pointer to the member in general,
924 // not any specific instance's member.
925 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000926 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000927 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000928 QualType DType;
929 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
930 DType = FD->getType().getNonReferenceType();
931 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
932 DType = Method->getType();
933 } else if (isa<OverloadedFunctionDecl>(D)) {
934 DType = Context.OverloadTy;
935 }
936 // Could be an inner type. That's diagnosed below, so ignore it here.
937 if (!DType.isNull()) {
938 // The pointer is type- and value-dependent if it points into something
939 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000940 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000941 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000942 }
943 }
944 }
945
Douglas Gregor723d3332009-01-07 00:43:41 +0000946 // We may have found a field within an anonymous union or struct
947 // (C++ [class.union]).
948 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
949 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
950 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000951
Douglas Gregor3257fb52008-12-22 05:46:06 +0000952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
953 if (!MD->isStatic()) {
954 // C++ [class.mfct.nonstatic]p2:
955 // [...] if name lookup (3.4.1) resolves the name in the
956 // id-expression to a nonstatic nontype member of class X or of
957 // a base class of X, the id-expression is transformed into a
958 // class member access expression (5.2.5) using (*this) (9.3.2)
959 // as the postfix-expression to the left of the '.' operator.
960 DeclContext *Ctx = 0;
961 QualType MemberType;
962 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
963 Ctx = FD->getDeclContext();
964 MemberType = FD->getType();
965
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000966 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000967 MemberType = RefType->getPointeeType();
968 else if (!FD->isMutable()) {
969 unsigned combinedQualifiers
970 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
971 MemberType = MemberType.getQualifiedType(combinedQualifiers);
972 }
973 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
974 if (!Method->isStatic()) {
975 Ctx = Method->getParent();
976 MemberType = Method->getType();
977 }
978 } else if (OverloadedFunctionDecl *Ovl
979 = dyn_cast<OverloadedFunctionDecl>(D)) {
980 for (OverloadedFunctionDecl::function_iterator
981 Func = Ovl->function_begin(),
982 FuncEnd = Ovl->function_end();
983 Func != FuncEnd; ++Func) {
984 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
985 if (!DMethod->isStatic()) {
986 Ctx = Ovl->getDeclContext();
987 MemberType = Context.OverloadTy;
988 break;
989 }
990 }
991 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000992
993 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000994 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
995 QualType ThisType = Context.getTagDeclType(MD->getParent());
996 if ((Context.getCanonicalType(CtxType)
997 == Context.getCanonicalType(ThisType)) ||
998 IsDerivedFrom(ThisType, CtxType)) {
999 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001000 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001001 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001002 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001003 if (PerformObjectMemberConversion(This, D))
1004 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001005 if (DiagnoseUseOfDecl(D, Loc))
1006 return ExprError();
Douglas Gregor09be81b2009-02-04 17:27:36 +00001007 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001008 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001009 }
1010 }
1011 }
1012 }
1013
Douglas Gregor8acb7272008-12-11 16:49:14 +00001014 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001015 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1016 if (MD->isStatic())
1017 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1019 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001020 }
1021
Douglas Gregor3257fb52008-12-22 05:46:06 +00001022 // Any other ways we could have found the field in a well-formed
1023 // program would have been turned into implicit member expressions
1024 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1026 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001027 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001028
Chris Lattner4b009652007-07-25 00:24:17 +00001029 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001031 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001033 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001034 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001035
Steve Naroffd6163f32008-09-05 22:11:13 +00001036 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001037 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001038 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1039 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001040 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001041 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1042 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001043 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001044
Douglas Gregoraa57e862009-02-18 21:56:37 +00001045 // Check whether this declaration can be used. Note that we suppress
1046 // this check when we're going to perform argument-dependent lookup
1047 // on this function name, because this might not be the function
1048 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001049 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1050 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001051 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1052 return ExprError();
1053
Steve Naroffd6163f32008-09-05 22:11:13 +00001054 // Only create DeclRefExpr's for valid Decl's.
1055 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001056 return ExprError();
1057
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001058 // If the identifier reference is inside a block, and it refers to a value
1059 // that is outside the block, create a BlockDeclRefExpr instead of a
1060 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1061 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001062 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001063 // We do not do this for things like enum constants, global variables, etc,
1064 // as they do not get snapshotted.
1065 //
1066 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001067 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001068 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001069 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001070 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001071 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001072 // This is to record that a 'const' was actually synthesize and added.
1073 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001074 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001075
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001076 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001077 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1078 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001079 }
1080 // If this reference is not in a block or if the referenced variable is
1081 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001082
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001083 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001084 bool ValueDependent = false;
1085 if (getLangOptions().CPlusPlus) {
1086 // C++ [temp.dep.expr]p3:
1087 // An id-expression is type-dependent if it contains:
1088 // - an identifier that was declared with a dependent type,
1089 if (VD->getType()->isDependentType())
1090 TypeDependent = true;
1091 // - FIXME: a template-id that is dependent,
1092 // - a conversion-function-id that specifies a dependent type,
1093 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1094 Name.getCXXNameType()->isDependentType())
1095 TypeDependent = true;
1096 // - a nested-name-specifier that contains a class-name that
1097 // names a dependent type.
1098 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001099 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001100 DC; DC = DC->getParent()) {
1101 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001102 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001103 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1104 if (Context.getTypeDeclType(Record)->isDependentType()) {
1105 TypeDependent = true;
1106 break;
1107 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001108 }
1109 }
1110 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001111
Douglas Gregora5d84612008-12-10 20:57:37 +00001112 // C++ [temp.dep.constexpr]p2:
1113 //
1114 // An identifier is value-dependent if it is:
1115 // - a name declared with a dependent type,
1116 if (TypeDependent)
1117 ValueDependent = true;
1118 // - the name of a non-type template parameter,
1119 else if (isa<NonTypeTemplateParmDecl>(VD))
1120 ValueDependent = true;
1121 // - a constant with integral or enumeration type and is
1122 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001123 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1124 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1125 Dcl->getInit()) {
1126 ValueDependent = Dcl->getInit()->isValueDependent();
1127 }
1128 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001129 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001130
Anders Carlsson4571d812009-06-24 00:10:43 +00001131 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1132 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001133}
1134
Sebastian Redlcd883f72009-01-18 18:53:16 +00001135Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1136 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001137 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001138
Chris Lattner4b009652007-07-25 00:24:17 +00001139 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001140 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001141 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1142 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1143 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001144 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001145
Chris Lattner7e637512008-01-12 08:14:25 +00001146 // Pre-defined identifiers are of type char[x], where x is the length of the
1147 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001148 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001149 if (FunctionDecl *FD = getCurFunctionDecl())
1150 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001151 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1152 Length = MD->getSynthesizedMethodSize();
1153 else {
1154 Diag(Loc, diag::ext_predef_outside_function);
1155 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1156 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1157 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001158
1159
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001160 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001161 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001162 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001163 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001164}
1165
Sebastian Redlcd883f72009-01-18 18:53:16 +00001166Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001167 llvm::SmallString<16> CharBuffer;
1168 CharBuffer.resize(Tok.getLength());
1169 const char *ThisTokBegin = &CharBuffer[0];
1170 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171
Chris Lattner4b009652007-07-25 00:24:17 +00001172 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1173 Tok.getLocation(), PP);
1174 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001175 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001176
1177 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1178
Sebastian Redl75324932009-01-20 22:23:13 +00001179 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1180 Literal.isWide(),
1181 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001182}
1183
Sebastian Redlcd883f72009-01-18 18:53:16 +00001184Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1185 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001186 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1187 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001188 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001189 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001190 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001191 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001192 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001193
Chris Lattner4b009652007-07-25 00:24:17 +00001194 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001195 // Add padding so that NumericLiteralParser can overread by one character.
1196 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001197 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001198
Chris Lattner4b009652007-07-25 00:24:17 +00001199 // Get the spelling of the token, which eliminates trigraphs, etc.
1200 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001201
Chris Lattner4b009652007-07-25 00:24:17 +00001202 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1203 Tok.getLocation(), PP);
1204 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001205 return ExprError();
1206
Chris Lattner1de66eb2007-08-26 03:42:43 +00001207 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001208
Chris Lattner1de66eb2007-08-26 03:42:43 +00001209 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001210 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001211 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001212 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001213 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001214 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001215 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001216 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001217
1218 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1219
Ted Kremenekddedbe22007-11-29 00:56:49 +00001220 // isExact will be set by GetFloatValue().
1221 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001222 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1223 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001224
Chris Lattner1de66eb2007-08-26 03:42:43 +00001225 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001226 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001227 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001228 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001229
Neil Booth7421e9c2007-08-29 22:00:19 +00001230 // long long is a C99 feature.
1231 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001232 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001233 Diag(Tok.getLocation(), diag::ext_longlong);
1234
Chris Lattner4b009652007-07-25 00:24:17 +00001235 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001236 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001237
Chris Lattner4b009652007-07-25 00:24:17 +00001238 if (Literal.GetIntegerValue(ResultVal)) {
1239 // If this value didn't fit into uintmax_t, warn and force to ull.
1240 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001241 Ty = Context.UnsignedLongLongTy;
1242 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001243 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001244 } else {
1245 // If this value fits into a ULL, try to figure out what else it fits into
1246 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001247
Chris Lattner4b009652007-07-25 00:24:17 +00001248 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1249 // be an unsigned int.
1250 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1251
1252 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001253 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001254 if (!Literal.isLong && !Literal.isLongLong) {
1255 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001256 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001257
Chris Lattner4b009652007-07-25 00:24:17 +00001258 // Does it fit in a unsigned int?
1259 if (ResultVal.isIntN(IntSize)) {
1260 // Does it fit in a signed int?
1261 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001262 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001263 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001264 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001265 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001266 }
Chris Lattner4b009652007-07-25 00:24:17 +00001267 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001270 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001271 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001272
Chris Lattner4b009652007-07-25 00:24:17 +00001273 // Does it fit in a unsigned long?
1274 if (ResultVal.isIntN(LongSize)) {
1275 // Does it fit in a signed long?
1276 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001277 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001278 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001279 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001280 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001281 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001282 }
1283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001285 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001286 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001287
Chris Lattner4b009652007-07-25 00:24:17 +00001288 // Does it fit in a unsigned long long?
1289 if (ResultVal.isIntN(LongLongSize)) {
1290 // Does it fit in a signed long long?
1291 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001292 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001293 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001294 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001295 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001296 }
1297 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001298
Chris Lattner4b009652007-07-25 00:24:17 +00001299 // If we still couldn't decide a type, we probably have something that
1300 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001301 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001302 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001303 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001304 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001305 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001306
Chris Lattnere4068872008-05-09 05:59:00 +00001307 if (ResultVal.getBitWidth() != Width)
1308 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001309 }
Sebastian Redl75324932009-01-20 22:23:13 +00001310 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001311 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001312
Chris Lattner1de66eb2007-08-26 03:42:43 +00001313 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1314 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001315 Res = new (Context) ImaginaryLiteral(Res,
1316 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001317
1318 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001319}
1320
Sebastian Redlcd883f72009-01-18 18:53:16 +00001321Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1322 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001323 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001324 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001325 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001326}
1327
1328/// The UsualUnaryConversions() function is *not* called by this routine.
1329/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001330bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001331 SourceLocation OpLoc,
1332 const SourceRange &ExprRange,
1333 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001334 if (exprType->isDependentType())
1335 return false;
1336
Chris Lattner4b009652007-07-25 00:24:17 +00001337 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001338 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001339 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001340 if (isSizeof)
1341 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1342 return false;
1343 }
1344
Chris Lattner95933c12009-04-24 00:30:45 +00001345 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001346 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001347 Diag(OpLoc, diag::ext_sizeof_void_type)
1348 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001349 return false;
1350 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001351
Chris Lattner95933c12009-04-24 00:30:45 +00001352 if (RequireCompleteType(OpLoc, exprType,
1353 isSizeof ? diag::err_sizeof_incomplete_type :
1354 diag::err_alignof_incomplete_type,
1355 ExprRange))
1356 return true;
1357
1358 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001359 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001360 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001361 << exprType << isSizeof << ExprRange;
1362 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001363 }
1364
Chris Lattner95933c12009-04-24 00:30:45 +00001365 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001366}
1367
Chris Lattner8d9f7962009-01-24 20:17:12 +00001368bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1369 const SourceRange &ExprRange) {
1370 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001371
Chris Lattner8d9f7962009-01-24 20:17:12 +00001372 // alignof decl is always ok.
1373 if (isa<DeclRefExpr>(E))
1374 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001375
1376 // Cannot know anything else if the expression is dependent.
1377 if (E->isTypeDependent())
1378 return false;
1379
Douglas Gregor531434b2009-05-02 02:18:30 +00001380 if (E->getBitField()) {
1381 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1382 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001383 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001384
1385 // Alignment of a field access is always okay, so long as it isn't a
1386 // bit-field.
1387 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001388 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001389 return false;
1390
Chris Lattner8d9f7962009-01-24 20:17:12 +00001391 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1392}
1393
Douglas Gregor396f1142009-03-13 21:01:28 +00001394/// \brief Build a sizeof or alignof expression given a type operand.
1395Action::OwningExprResult
1396Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1397 bool isSizeOf, SourceRange R) {
1398 if (T.isNull())
1399 return ExprError();
1400
1401 if (!T->isDependentType() &&
1402 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1403 return ExprError();
1404
1405 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1406 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1407 Context.getSizeType(), OpLoc,
1408 R.getEnd()));
1409}
1410
1411/// \brief Build a sizeof or alignof expression given an expression
1412/// operand.
1413Action::OwningExprResult
1414Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1415 bool isSizeOf, SourceRange R) {
1416 // Verify that the operand is valid.
1417 bool isInvalid = false;
1418 if (E->isTypeDependent()) {
1419 // Delay type-checking for type-dependent expressions.
1420 } else if (!isSizeOf) {
1421 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001422 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001423 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1424 isInvalid = true;
1425 } else {
1426 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1427 }
1428
1429 if (isInvalid)
1430 return ExprError();
1431
1432 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1433 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1434 Context.getSizeType(), OpLoc,
1435 R.getEnd()));
1436}
1437
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001438/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1439/// the same for @c alignof and @c __alignof
1440/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001441Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001442Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1443 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001444 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001445 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001446
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001447 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001448 // FIXME: Preserve type source info.
1449 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001450 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1451 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001452
Douglas Gregor396f1142009-03-13 21:01:28 +00001453 // Get the end location.
1454 Expr *ArgEx = (Expr *)TyOrEx;
1455 Action::OwningExprResult Result
1456 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1457
1458 if (Result.isInvalid())
1459 DeleteExpr(ArgEx);
1460
1461 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001462}
1463
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001464QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001465 if (V->isTypeDependent())
1466 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001467
Chris Lattnera16e42d2007-08-26 05:39:26 +00001468 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001469 if (const ComplexType *CT = V->getType()->getAsComplexType())
1470 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001471
1472 // Otherwise they pass through real integer and floating point types here.
1473 if (V->getType()->isArithmeticType())
1474 return V->getType();
1475
1476 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001477 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1478 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001479 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001480}
1481
1482
Chris Lattner4b009652007-07-25 00:24:17 +00001483
Sebastian Redl8b769972009-01-19 00:08:26 +00001484Action::OwningExprResult
1485Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1486 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001487 // Since this might be a postfix expression, get rid of ParenListExprs.
1488 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001489 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001490
Chris Lattner4b009652007-07-25 00:24:17 +00001491 UnaryOperator::Opcode Opc;
1492 switch (Kind) {
1493 default: assert(0 && "Unknown unary op!");
1494 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1495 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1496 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001497
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001498 if (getLangOptions().CPlusPlus &&
1499 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1500 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001501 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001502 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1503
1504 // C++ [over.inc]p1:
1505 //
1506 // [...] If the function is a member function with one
1507 // parameter (which shall be of type int) or a non-member
1508 // function with two parameters (the second of which shall be
1509 // of type int), it defines the postfix increment operator ++
1510 // for objects of that type. When the postfix increment is
1511 // called as a result of using the ++ operator, the int
1512 // argument will have value zero.
1513 Expr *Args[2] = {
1514 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001515 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1516 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001517 };
1518
1519 // Build the candidate set for overloading
1520 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001521 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001522
1523 // Perform overload resolution.
1524 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001525 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001526 case OR_Success: {
1527 // We found a built-in operator or an overloaded operator.
1528 FunctionDecl *FnDecl = Best->Function;
1529
1530 if (FnDecl) {
1531 // We matched an overloaded operator. Build a call to that
1532 // operator.
1533
1534 // Convert the arguments.
1535 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1536 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001537 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001538 } else {
1539 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001540 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001541 FnDecl->getParamDecl(0)->getType(),
1542 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001544 }
1545
1546 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001547 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001548 = FnDecl->getType()->getAsFunctionType()->getResultType();
1549 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001550
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001551 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001552 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001553 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001554 UsualUnaryConversions(FnExpr);
1555
Sebastian Redl8b769972009-01-19 00:08:26 +00001556 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001557 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001558 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1559 Args, 2, ResultTy,
1560 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001561 } else {
1562 // We matched a built-in operator. Convert the arguments, then
1563 // break out so that we will build the appropriate built-in
1564 // operator node.
1565 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1566 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001567 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001568
1569 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001570 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001571 }
1572
1573 case OR_No_Viable_Function:
1574 // No viable function; fall through to handling this as a
1575 // built-in operator, which will produce an error message for us.
1576 break;
1577
1578 case OR_Ambiguous:
1579 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1580 << UnaryOperator::getOpcodeStr(Opc)
1581 << Arg->getSourceRange();
1582 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001584
1585 case OR_Deleted:
1586 Diag(OpLoc, diag::err_ovl_deleted_oper)
1587 << Best->Function->isDeleted()
1588 << UnaryOperator::getOpcodeStr(Opc)
1589 << Arg->getSourceRange();
1590 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1591 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001592 }
1593
1594 // Either we found no viable overloaded operator or we matched a
1595 // built-in operator. In either case, fall through to trying to
1596 // build a built-in operation.
1597 }
1598
Eli Friedman94d30952009-07-22 23:24:42 +00001599 Input.release();
1600 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001601 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001602}
1603
Sebastian Redl8b769972009-01-19 00:08:26 +00001604Action::OwningExprResult
1605Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1606 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001607 // Since this might be a postfix expression, get rid of ParenListExprs.
1608 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1609
Sebastian Redl8b769972009-01-19 00:08:26 +00001610 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1611 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001612
Douglas Gregor80723c52008-11-19 17:17:41 +00001613 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001614 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1615 Base.release();
1616 Idx.release();
1617 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1618 Context.DependentTy, RLoc));
1619 }
1620
1621 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001622 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001623 LHSExp->getType()->isEnumeralType() ||
1624 RHSExp->getType()->isRecordType() ||
1625 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001626 // Add the appropriate overloaded operators (C++ [over.match.oper])
1627 // to the candidate set.
1628 OverloadCandidateSet CandidateSet;
1629 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001630 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1631 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001632
Douglas Gregor80723c52008-11-19 17:17:41 +00001633 // Perform overload resolution.
1634 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001635 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001636 case OR_Success: {
1637 // We found a built-in operator or an overloaded operator.
1638 FunctionDecl *FnDecl = Best->Function;
1639
1640 if (FnDecl) {
1641 // We matched an overloaded operator. Build a call to that
1642 // operator.
1643
1644 // Convert the arguments.
1645 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1646 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1647 PerformCopyInitialization(RHSExp,
1648 FnDecl->getParamDecl(0)->getType(),
1649 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001650 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001651 } else {
1652 // Convert the arguments.
1653 if (PerformCopyInitialization(LHSExp,
1654 FnDecl->getParamDecl(0)->getType(),
1655 "passing") ||
1656 PerformCopyInitialization(RHSExp,
1657 FnDecl->getParamDecl(1)->getType(),
1658 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001659 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001660 }
1661
1662 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001663 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001664 = FnDecl->getType()->getAsFunctionType()->getResultType();
1665 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001666
Douglas Gregor80723c52008-11-19 17:17:41 +00001667 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001668 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1669 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001670 UsualUnaryConversions(FnExpr);
1671
Sebastian Redl8b769972009-01-19 00:08:26 +00001672 Base.release();
1673 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001674 Args[0] = LHSExp;
1675 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001676 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1677 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001678 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001679 } else {
1680 // We matched a built-in operator. Convert the arguments, then
1681 // break out so that we will build the appropriate built-in
1682 // operator node.
1683 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1684 "passing") ||
1685 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1686 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001687 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001688
1689 break;
1690 }
1691 }
1692
1693 case OR_No_Viable_Function:
1694 // No viable function; fall through to handling this as a
1695 // built-in operator, which will produce an error message for us.
1696 break;
1697
1698 case OR_Ambiguous:
1699 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1700 << "[]"
1701 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1702 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001703 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001704
1705 case OR_Deleted:
1706 Diag(LLoc, diag::err_ovl_deleted_oper)
1707 << Best->Function->isDeleted()
1708 << "[]"
1709 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1710 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1711 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001712 }
1713
1714 // Either we found no viable overloaded operator or we matched a
1715 // built-in operator. In either case, fall through to trying to
1716 // build a built-in operation.
1717 }
1718
Chris Lattner4b009652007-07-25 00:24:17 +00001719 // Perform default conversions.
1720 DefaultFunctionArrayConversion(LHSExp);
1721 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001722
Chris Lattner4b009652007-07-25 00:24:17 +00001723 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1724
1725 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001726 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001727 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001728 // and index from the expression types.
1729 Expr *BaseExpr, *IndexExpr;
1730 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001731 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1732 BaseExpr = LHSExp;
1733 IndexExpr = RHSExp;
1734 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001735 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001736 BaseExpr = LHSExp;
1737 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001738 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001739 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001740 // Handle the uncommon case of "123[Ptr]".
1741 BaseExpr = RHSExp;
1742 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001743 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001744 } else if (const ObjCObjectPointerType *PTy =
1745 LHSTy->getAsObjCObjectPointerType()) {
1746 BaseExpr = LHSExp;
1747 IndexExpr = RHSExp;
1748 ResultType = PTy->getPointeeType();
1749 } else if (const ObjCObjectPointerType *PTy =
1750 RHSTy->getAsObjCObjectPointerType()) {
1751 // Handle the uncommon case of "123[Ptr]".
1752 BaseExpr = RHSExp;
1753 IndexExpr = LHSExp;
1754 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001755 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1756 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001757 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001758
Chris Lattner4b009652007-07-25 00:24:17 +00001759 // FIXME: need to deal with const...
1760 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001761 } else if (LHSTy->isArrayType()) {
1762 // If we see an array that wasn't promoted by
1763 // DefaultFunctionArrayConversion, it must be an array that
1764 // wasn't promoted because of the C90 rule that doesn't
1765 // allow promoting non-lvalue arrays. Warn, then
1766 // force the promotion here.
1767 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1768 LHSExp->getSourceRange();
1769 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1770 LHSTy = LHSExp->getType();
1771
1772 BaseExpr = LHSExp;
1773 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001774 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001775 } else if (RHSTy->isArrayType()) {
1776 // Same as previous, except for 123[f().a] case
1777 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1778 RHSExp->getSourceRange();
1779 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1780 RHSTy = RHSExp->getType();
1781
1782 BaseExpr = RHSExp;
1783 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001784 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001785 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001786 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1787 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001788 }
Chris Lattner4b009652007-07-25 00:24:17 +00001789 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001790 if (!(IndexExpr->getType()->isIntegerType() &&
1791 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001792 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1793 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001794
Douglas Gregor05e28f62009-03-24 19:52:54 +00001795 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1796 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1797 // type. Note that Functions are not objects, and that (in C99 parlance)
1798 // incomplete types are not object types.
1799 if (ResultType->isFunctionType()) {
1800 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1801 << ResultType << BaseExpr->getSourceRange();
1802 return ExprError();
1803 }
Chris Lattner95933c12009-04-24 00:30:45 +00001804
Douglas Gregor05e28f62009-03-24 19:52:54 +00001805 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001806 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001807 BaseExpr->getSourceRange()))
1808 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001809
1810 // Diagnose bad cases where we step over interface counts.
1811 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1812 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1813 << ResultType << BaseExpr->getSourceRange();
1814 return ExprError();
1815 }
1816
Sebastian Redl8b769972009-01-19 00:08:26 +00001817 Base.release();
1818 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001819 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001820 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001821}
1822
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001823QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001824CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001825 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001826 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001827
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001828 // The vector accessor can't exceed the number of elements.
1829 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001830
Mike Stump9afab102009-02-19 03:04:26 +00001831 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001832 // special names that indicate a subset of exactly half the elements are
1833 // to be selected.
1834 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001835
Nate Begeman1486b502009-01-18 01:47:54 +00001836 // This flag determines whether or not CompName has an 's' char prefix,
1837 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001838 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001839
1840 // Check that we've found one of the special components, or that the component
1841 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001842 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001843 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1844 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001845 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001846 do
1847 compStr++;
1848 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001849 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001850 do
1851 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001852 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001853 }
Nate Begeman1486b502009-01-18 01:47:54 +00001854
Mike Stump9afab102009-02-19 03:04:26 +00001855 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001856 // We didn't get to the end of the string. This means the component names
1857 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001858 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1859 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001860 return QualType();
1861 }
Mike Stump9afab102009-02-19 03:04:26 +00001862
Nate Begeman1486b502009-01-18 01:47:54 +00001863 // Ensure no component accessor exceeds the width of the vector type it
1864 // operates on.
1865 if (!HalvingSwizzle) {
1866 compStr = CompName.getName();
1867
1868 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001869 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001870
1871 while (*compStr) {
1872 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1873 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1874 << baseType << SourceRange(CompLoc);
1875 return QualType();
1876 }
1877 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001878 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001879
Nate Begeman1486b502009-01-18 01:47:54 +00001880 // If this is a halving swizzle, verify that the base type has an even
1881 // number of elements.
1882 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001883 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001884 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001885 return QualType();
1886 }
Mike Stump9afab102009-02-19 03:04:26 +00001887
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001888 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001889 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001890 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001891 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001892 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001893 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1894 : CompName.getLength();
1895 if (HexSwizzle)
1896 CompSize--;
1897
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001898 if (CompSize == 1)
1899 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001900
Nate Begemanaf6ed502008-04-18 23:10:10 +00001901 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001902 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001903 // diagostics look bad. We want extended vector types to appear built-in.
1904 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1905 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1906 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001907 }
1908 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001909}
1910
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001911static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1912 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001913 const Selector &Sel,
1914 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001915
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001916 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001917 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001918 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001919 return OMD;
1920
1921 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1922 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001923 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1924 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001925 return D;
1926 }
1927 return 0;
1928}
1929
Steve Naroffc75c1a82009-06-17 22:40:22 +00001930static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001931 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001932 const Selector &Sel,
1933 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001934 // Check protocols on qualified interfaces.
1935 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001936 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001937 E = QIdTy->qual_end(); I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001938 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001939 GDecl = PD;
1940 break;
1941 }
1942 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001943 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001944 GDecl = OMD;
1945 break;
1946 }
1947 }
1948 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001949 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001950 E = QIdTy->qual_end(); I != E; ++I) {
1951 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001952 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001953 if (GDecl)
1954 return GDecl;
1955 }
1956 }
1957 return GDecl;
1958}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001959
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001960/// FindMethodInNestedImplementations - Look up a method in current and
1961/// all base class implementations.
1962///
1963ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1964 const ObjCInterfaceDecl *IFace,
1965 const Selector &Sel) {
1966 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001967 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001968 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001969
1970 if (!Method && IFace->getSuperClass())
1971 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1972 return Method;
1973}
1974
Sebastian Redl8b769972009-01-19 00:08:26 +00001975Action::OwningExprResult
1976Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1977 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001978 IdentifierInfo &Member,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001979 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
1980 // FIXME: handle the CXXScopeSpec for proper lookup of qualified-ids
1981 if (SS && SS->isInvalid())
1982 return ExprError();
1983
Nate Begemane85f43d2009-08-10 23:49:36 +00001984 // Since this might be a postfix expression, get rid of ParenListExprs.
1985 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1986
Anders Carlssonc154a722009-05-01 19:30:39 +00001987 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001988 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001989
Steve Naroff137e11d2007-12-16 21:42:28 +00001990 // Perform default conversions.
1991 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001992
Steve Naroff2cb66382007-07-26 03:11:44 +00001993 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001994 // If this is an Objective-C pseudo-builtin and a definition is provided then
1995 // use that.
1996 if (BaseType->isObjCIdType()) {
1997 // We have an 'id' type. Rather than fall through, we check if this
1998 // is a reference to 'isa'.
1999 if (BaseType != Context.ObjCIdRedefinitionType) {
2000 BaseType = Context.ObjCIdRedefinitionType;
2001 ImpCastExprToType(BaseExpr, BaseType);
2002 }
2003 } else if (BaseType->isObjCClassType() &&
2004 BaseType != Context.ObjCClassRedefinitionType) {
2005 BaseType = Context.ObjCClassRedefinitionType;
2006 ImpCastExprToType(BaseExpr, BaseType);
2007 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002008 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002009
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002010 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2011 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002012 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002013 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002014 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2015 BaseExpr, true,
2016 OpLoc,
2017 DeclarationName(&Member),
2018 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002019 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002020 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002021 else if (BaseType->isObjCObjectPointerType())
2022 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002023 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002024 return ExprError(Diag(MemberLoc,
2025 diag::err_typecheck_member_reference_arrow)
2026 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002027 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002028 if (BaseType->isDependentType()) {
2029 // Require that the base type isn't a pointer type
2030 // (so we'll report an error for)
2031 // T* t;
2032 // t.f;
2033 //
2034 // In Obj-C++, however, the above expression is valid, since it could be
2035 // accessing the 'f' property if T is an Obj-C interface. The extra check
2036 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002037 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002038
2039 if (!PT || (getLangOptions().ObjC1 &&
2040 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002041 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2042 BaseExpr, false,
2043 OpLoc,
2044 DeclarationName(&Member),
2045 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002046 }
Chris Lattner4b009652007-07-25 00:24:17 +00002047 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002048
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002049 // Handle field access to simple records. This also handles access to fields
2050 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002051 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002052 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002053 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002054 diag::err_typecheck_incomplete_tag,
2055 BaseExpr->getSourceRange()))
2056 return ExprError();
2057
Douglas Gregorda61ad22009-08-06 03:17:00 +00002058 DeclContext *DC = RDecl;
2059 if (SS && SS->isSet()) {
2060 // If the member name was a qualified-id, look into the
2061 // nested-name-specifier.
2062 DC = computeDeclContext(*SS, false);
2063
2064 // FIXME: If DC is not computable, we should build a
2065 // CXXUnresolvedMemberExpr.
2066 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2067 }
2068
Steve Naroff2cb66382007-07-26 03:11:44 +00002069 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002070 LookupResult Result
Douglas Gregorda61ad22009-08-06 03:17:00 +00002071 = LookupQualifiedName(DC, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002072 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002073
Douglas Gregor12431cb2009-08-06 05:28:30 +00002074 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002075 QualType BaseTypeCanon
2076 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2077 QualType MemberTypeCanon
2078 = Context.getCanonicalType(
2079 Context.getTypeDeclType(
2080 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2081
2082 if (BaseTypeCanon != MemberTypeCanon &&
2083 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2084 return ExprError(Diag(SS->getBeginLoc(),
2085 diag::err_not_direct_base_or_virtual)
2086 << MemberTypeCanon << BaseTypeCanon);
2087 }
2088
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002089 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002090 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2091 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002092 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002093 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2094 MemberLoc, BaseExpr->getSourceRange());
2095 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002096 }
2097
2098 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002099
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002100 // If the decl being referenced had an error, return an error for this
2101 // sub-expr without emitting another error, in order to avoid cascading
2102 // error cases.
2103 if (MemberDecl->isInvalidDecl())
2104 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002105
Douglas Gregoraa57e862009-02-18 21:56:37 +00002106 // Check the use of this field
2107 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2108 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002109
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002110 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002111 // We may have found a field within an anonymous union or struct
2112 // (C++ [class.union]).
2113 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002114 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002115 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002116
Douglas Gregor82d44772008-12-20 23:49:58 +00002117 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002118 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002119 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002120 MemberType = Ref->getPointeeType();
2121 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002122 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002123 unsigned combinedQualifiers =
2124 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002125 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002126 combinedQualifiers &= ~QualType::Const;
2127 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002128 if (BaseAddrSpace != MemberType.getAddressSpace())
2129 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002130 }
Eli Friedman76b49832008-02-06 22:48:16 +00002131
Douglas Gregorcad27f62009-06-22 23:06:13 +00002132 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002133 if (PerformObjectMemberConversion(BaseExpr, FD))
2134 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002135 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2136 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002137 }
2138
Douglas Gregorcad27f62009-06-22 23:06:13 +00002139 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2140 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Steve Naroff774e4152009-01-21 00:14:39 +00002141 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002142 Var, MemberLoc,
2143 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002144 }
2145 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2146 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002147 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002148 MemberFn, MemberLoc,
2149 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002150 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002151 if (OverloadedFunctionDecl *Ovl
2152 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002153 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002154 MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002155 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2156 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002157 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2158 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002159 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002160 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002161 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2162 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002163
Douglas Gregor82d44772008-12-20 23:49:58 +00002164 // We found a declaration kind that we didn't expect. This is a
2165 // generic error message that tells the user that she can't refer
2166 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002167 return ExprError(Diag(MemberLoc,
2168 diag::err_typecheck_member_reference_unknown)
2169 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002170 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002171
Steve Naroff329ec222009-07-10 23:34:53 +00002172 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002173 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002174 // Also must look for a getter name which uses property syntax.
2175 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2176 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2177 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2178 ObjCMethodDecl *Getter;
2179 // FIXME: need to also look locally in the implementation.
2180 if ((Getter = IFace->lookupClassMethod(Sel))) {
2181 // Check the use of this method.
2182 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2183 return ExprError();
2184 }
2185 // If we found a getter then this may be a valid dot-reference, we
2186 // will look for the matching setter, in case it is needed.
2187 Selector SetterSel =
2188 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2189 PP.getSelectorTable(), &Member);
2190 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2191 if (!Setter) {
2192 // If this reference is in an @implementation, also check for 'private'
2193 // methods.
2194 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2195 }
2196 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002197 if (!Setter)
2198 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002199
2200 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2201 return ExprError();
2202
2203 if (Getter || Setter) {
2204 QualType PType;
2205
2206 if (Getter)
2207 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002208 else
2209 // Get the expression type from Setter's incoming parameter.
2210 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002211 // FIXME: we must check that the setter has property type.
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002212 return Owned(new (Context) ObjCImplctSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002213 Setter, MemberLoc, BaseExpr));
2214 }
2215 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2216 << &Member << BaseType);
2217 }
2218 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002219 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2220 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002221 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2222 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2223 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2224 const ObjCInterfaceType *IFaceT =
2225 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002226 if (IFaceT) {
2227 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2228 ObjCInterfaceDecl *ClassDeclared;
2229 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(&Member, ClassDeclared);
2230
2231 if (IV) {
2232 // If the decl being referenced had an error, return an error for this
2233 // sub-expr without emitting another error, in order to avoid cascading
2234 // error cases.
2235 if (IV->isInvalidDecl())
2236 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002237
Steve Naroff4e743962009-07-16 00:25:06 +00002238 // Check whether we can reference this field.
2239 if (DiagnoseUseOfDecl(IV, MemberLoc))
2240 return ExprError();
2241 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2242 IV->getAccessControl() != ObjCIvarDecl::Package) {
2243 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2244 if (ObjCMethodDecl *MD = getCurMethodDecl())
2245 ClassOfMethodDecl = MD->getClassInterface();
2246 else if (ObjCImpDecl && getCurFunctionDecl()) {
2247 // Case of a c-function declared inside an objc implementation.
2248 // FIXME: For a c-style function nested inside an objc implementation
2249 // class, there is no implementation context available, so we pass
2250 // down the context as argument to this routine. Ideally, this context
2251 // need be passed down in the AST node and somehow calculated from the
2252 // AST for a function decl.
2253 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2254 if (ObjCImplementationDecl *IMPD =
2255 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2256 ClassOfMethodDecl = IMPD->getClassInterface();
2257 else if (ObjCCategoryImplDecl* CatImplClass =
2258 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2259 ClassOfMethodDecl = CatImplClass->getClassInterface();
2260 }
2261
2262 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2263 if (ClassDeclared != IDecl ||
2264 ClassOfMethodDecl != ClassDeclared)
2265 Diag(MemberLoc, diag::error_private_ivar_access)
2266 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002267 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2268 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002269 Diag(MemberLoc, diag::error_protected_ivar_access)
2270 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002271 }
Steve Naroff4e743962009-07-16 00:25:06 +00002272
2273 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2274 MemberLoc, BaseExpr,
2275 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002276 }
Steve Naroff4e743962009-07-16 00:25:06 +00002277 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2278 << IDecl->getDeclName() << &Member
2279 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002280 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002281 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002282 // Handle properties on 'id' and qualified "id".
2283 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2284 BaseType->isObjCQualifiedIdType())) {
2285 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2286
Steve Naroff329ec222009-07-10 23:34:53 +00002287 // Check protocols on qualified interfaces.
2288 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2289 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2290 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2291 // Check the use of this declaration
2292 if (DiagnoseUseOfDecl(PD, MemberLoc))
2293 return ExprError();
2294
2295 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2296 MemberLoc, BaseExpr));
2297 }
2298 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2299 // Check the use of this method.
2300 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2301 return ExprError();
2302
2303 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2304 OMD->getResultType(),
2305 OMD, OpLoc, MemberLoc,
2306 NULL, 0));
2307 }
2308 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002309
Steve Naroff329ec222009-07-10 23:34:53 +00002310 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2311 << &Member << BaseType);
2312 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002313 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2314 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002315 const ObjCObjectPointerType *OPT;
2316 if (OpKind == tok::period &&
2317 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2318 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2319 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2320
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002321 // Search for a declared property first.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002322 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002323 // Check whether we can reference this property.
2324 if (DiagnoseUseOfDecl(PD, MemberLoc))
2325 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002326 QualType ResTy = PD->getType();
2327 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002328 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002329 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2330 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002331 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002332 MemberLoc, BaseExpr));
2333 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002334 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002335 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2336 E = OPT->qual_end(); I != E; ++I)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002337 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002338 // Check whether we can reference this property.
2339 if (DiagnoseUseOfDecl(PD, MemberLoc))
2340 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002341
Steve Naroff774e4152009-01-21 00:14:39 +00002342 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002343 MemberLoc, BaseExpr));
2344 }
Steve Naroff329ec222009-07-10 23:34:53 +00002345 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2346 E = OPT->qual_end(); I != E; ++I)
2347 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2348 // Check whether we can reference this property.
2349 if (DiagnoseUseOfDecl(PD, MemberLoc))
2350 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002351
Steve Naroff329ec222009-07-10 23:34:53 +00002352 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2353 MemberLoc, BaseExpr));
2354 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002355 // If that failed, look for an "implicit" property by seeing if the nullary
2356 // selector is implemented.
2357
2358 // FIXME: The logic for looking up nullary and unary selectors should be
2359 // shared with the code in ActOnInstanceMessage.
2360
2361 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002362 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002363
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002364 // If this reference is in an @implementation, check for 'private' methods.
2365 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002366 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002367
Steve Naroff04151f32008-10-22 19:16:27 +00002368 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002369 if (!Getter)
2370 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002371 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002372 // Check if we can reference this property.
2373 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2374 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002375 }
2376 // If we found a getter then this may be a valid dot-reference, we
2377 // will look for the matching setter, in case it is needed.
2378 Selector SetterSel =
2379 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2380 PP.getSelectorTable(), &Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002381 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002382 if (!Setter) {
2383 // If this reference is in an @implementation, also check for 'private'
2384 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002385 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002386 }
2387 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002388 if (!Setter)
2389 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002390
Steve Naroffdede0c92009-03-11 13:48:17 +00002391 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2392 return ExprError();
2393
2394 if (Getter || Setter) {
2395 QualType PType;
2396
2397 if (Getter)
2398 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002399 else
2400 // Get the expression type from Setter's incoming parameter.
2401 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002402 // FIXME: we must check that the setter has property type.
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002403 return Owned(new (Context) ObjCImplctSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002404 Setter, MemberLoc, BaseExpr));
2405 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002406 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2407 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002408 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002409
Steve Naroff29d293b2009-07-24 17:54:45 +00002410 // Handle the following exceptional case (*Obj).isa.
2411 if (OpKind == tok::period &&
2412 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Steve Naroffbbe4f962009-07-29 14:06:03 +00002413 Member.isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002414 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2415 Context.getObjCIdType()));
2416
Chris Lattnera57cf472008-07-21 04:28:12 +00002417 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002418 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002419 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2420 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002421 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002422 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002423 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002424 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002425
Douglas Gregor762da552009-03-27 06:00:30 +00002426 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2427 << BaseType << BaseExpr->getSourceRange();
2428
2429 // If the user is trying to apply -> or . to a function or function
2430 // pointer, it's probably because they forgot parentheses to call
2431 // the function. Suggest the addition of those parentheses.
2432 if (BaseType == Context.OverloadTy ||
2433 BaseType->isFunctionType() ||
2434 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002435 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002436 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2437 Diag(Loc, diag::note_member_reference_needs_call)
2438 << CodeModificationHint::CreateInsertion(Loc, "()");
2439 }
2440
2441 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002442}
2443
Douglas Gregor3257fb52008-12-22 05:46:06 +00002444/// ConvertArgumentsForCall - Converts the arguments specified in
2445/// Args/NumArgs to the parameter types of the function FDecl with
2446/// function prototype Proto. Call is the call expression itself, and
2447/// Fn is the function expression. For a C++ member function, this
2448/// routine does not attempt to convert the object argument. Returns
2449/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002450bool
2451Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002452 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002453 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002454 Expr **Args, unsigned NumArgs,
2455 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002456 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002457 // assignment, to the types of the corresponding parameter, ...
2458 unsigned NumArgsInProto = Proto->getNumArgs();
2459 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002460 bool Invalid = false;
2461
Douglas Gregor3257fb52008-12-22 05:46:06 +00002462 // If too few arguments are available (and we don't have default
2463 // arguments for the remaining parameters), don't make the call.
2464 if (NumArgs < NumArgsInProto) {
2465 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2466 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2467 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2468 // Use default arguments for missing arguments
2469 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002470 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002471 }
2472
2473 // If too many are passed and not variadic, error on the extras and drop
2474 // them.
2475 if (NumArgs > NumArgsInProto) {
2476 if (!Proto->isVariadic()) {
2477 Diag(Args[NumArgsInProto]->getLocStart(),
2478 diag::err_typecheck_call_too_many_args)
2479 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2480 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2481 Args[NumArgs-1]->getLocEnd());
2482 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002483 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002484 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002485 }
2486 NumArgsToCheck = NumArgsInProto;
2487 }
Mike Stump9afab102009-02-19 03:04:26 +00002488
Douglas Gregor3257fb52008-12-22 05:46:06 +00002489 // Continue to check argument types (even if we have too few/many args).
2490 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2491 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002492
Douglas Gregor3257fb52008-12-22 05:46:06 +00002493 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002494 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002495 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002496
Eli Friedman83dec9e2009-03-22 22:00:50 +00002497 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2498 ProtoArgType,
2499 diag::err_call_incomplete_argument,
2500 Arg->getSourceRange()))
2501 return true;
2502
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002503 // Pass the argument.
2504 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2505 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002506 } else {
2507 if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2508 Diag (Call->getSourceRange().getBegin(),
2509 diag::err_use_of_default_argument_to_function_declared_later) <<
2510 FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2511 Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2512 diag::note_default_argument_declared_here);
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002513 } else {
2514 Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2515
2516 // If the default expression creates temporaries, we need to
2517 // push them to the current stack of expression temporaries so they'll
2518 // be properly destroyed.
2519 if (CXXExprWithTemporaries *E
2520 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2521 assert(!E->shouldDestroyTemporaries() &&
2522 "Can't destroy temporaries in a default argument expr!");
2523 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2524 ExprTemporaries.push_back(E->getTemporary(I));
2525 }
Anders Carlssona116e6e2009-06-12 16:51:40 +00002526 }
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002527
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002528 // We already type-checked the argument, so we know it works.
Anders Carlsson3d752db2009-08-14 18:30:22 +00002529 Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(i));
Anders Carlssona116e6e2009-06-12 16:51:40 +00002530 }
2531
Douglas Gregor3257fb52008-12-22 05:46:06 +00002532 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002533
Douglas Gregor3257fb52008-12-22 05:46:06 +00002534 Call->setArg(i, Arg);
2535 }
Mike Stump9afab102009-02-19 03:04:26 +00002536
Douglas Gregor3257fb52008-12-22 05:46:06 +00002537 // If this is a variadic call, handle args passed through "...".
2538 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002539 VariadicCallType CallType = VariadicFunction;
2540 if (Fn->getType()->isBlockPointerType())
2541 CallType = VariadicBlock; // Block
2542 else if (isa<MemberExpr>(Fn))
2543 CallType = VariadicMethod;
2544
Douglas Gregor3257fb52008-12-22 05:46:06 +00002545 // Promote the arguments (C99 6.5.2.2p7).
2546 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2547 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002548 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002549 Call->setArg(i, Arg);
2550 }
2551 }
2552
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002553 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002554}
2555
Steve Naroff87d58b42007-09-16 03:34:24 +00002556/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002557/// This provides the location of the left/right parens and a list of comma
2558/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002559Action::OwningExprResult
2560Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2561 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002562 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002563 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002564
2565 // Since this might be a postfix expression, get rid of ParenListExprs.
2566 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2567
Anders Carlssonc154a722009-05-01 19:30:39 +00002568 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002569 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002570 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002571 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002572 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002573 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002574
Douglas Gregor3257fb52008-12-22 05:46:06 +00002575 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002576 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002577 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002578 // FIXME: Will need to cache the results of name lookup (including ADL) in
2579 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002580 bool Dependent = false;
2581 if (Fn->isTypeDependent())
2582 Dependent = true;
2583 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2584 Dependent = true;
2585
2586 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002587 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002588 Context.DependentTy, RParenLoc));
2589
2590 // Determine whether this is a call to an object (C++ [over.call.object]).
2591 if (Fn->getType()->isRecordType())
2592 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2593 CommaLocs, RParenLoc));
2594
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002595 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002596 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2597 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2598 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2599 isa<CXXMethodDecl>(MemDecl) ||
2600 (isa<FunctionTemplateDecl>(MemDecl) &&
2601 isa<CXXMethodDecl>(
2602 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002603 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2604 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002605 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002606 }
2607
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002608 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002609 // Also, in C++, keep track of whether we should perform argument-dependent
2610 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002611 Expr *FnExpr = Fn;
2612 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002613 bool HasExplicitTemplateArgs = 0;
2614 const TemplateArgument *ExplicitTemplateArgs = 0;
2615 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002616 while (true) {
2617 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2618 FnExpr = IcExpr->getSubExpr();
2619 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002620 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002621 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002622 ADL = false;
2623 FnExpr = PExpr->getSubExpr();
2624 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002625 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002626 == UnaryOperator::AddrOf) {
2627 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002628 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002629 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2630 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002631 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002632 break;
Mike Stump9afab102009-02-19 03:04:26 +00002633 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002634 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2635 UnqualifiedName = DepName->getName();
2636 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002637 } else if (TemplateIdRefExpr *TemplateIdRef
2638 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2639 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002640 if (!NDecl)
2641 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002642 HasExplicitTemplateArgs = true;
2643 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2644 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2645
2646 // C++ [temp.arg.explicit]p6:
2647 // [Note: For simple function names, argument dependent lookup (3.4.2)
2648 // applies even when the function name is not visible within the
2649 // scope of the call. This is because the call still has the syntactic
2650 // form of a function call (3.4.1). But when a function template with
2651 // explicit template arguments is used, the call does not have the
2652 // correct syntactic form unless there is a function template with
2653 // that name visible at the point of the call. If no such name is
2654 // visible, the call is not syntactically well-formed and
2655 // argument-dependent lookup does not apply. If some such name is
2656 // visible, argument dependent lookup applies and additional function
2657 // templates may be found in other namespaces.
2658 //
2659 // The summary of this paragraph is that, if we get to this point and the
2660 // template-id was not a qualified name, then argument-dependent lookup
2661 // is still possible.
2662 if (TemplateIdRef->getQualifier())
2663 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002664 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002665 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002666 // Any kind of name that does not refer to a declaration (or
2667 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2668 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002669 break;
2670 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002671 }
Mike Stump9afab102009-02-19 03:04:26 +00002672
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002673 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002674 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002675 if (NDecl) {
2676 FDecl = dyn_cast<FunctionDecl>(NDecl);
2677 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002678 FDecl = FunctionTemplate->getTemplatedDecl();
2679 else
Douglas Gregor28857752009-06-30 22:34:41 +00002680 FDecl = dyn_cast<FunctionDecl>(NDecl);
2681 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002682 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002683
Douglas Gregorb60eb752009-06-25 22:08:12 +00002684 if (Ovl || FunctionTemplate ||
2685 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002686 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002687 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002688 ADL = false;
2689
Douglas Gregorfcb19192009-02-11 23:02:49 +00002690 // We don't perform ADL in C.
2691 if (!getLangOptions().CPlusPlus)
2692 ADL = false;
2693
Douglas Gregorb60eb752009-06-25 22:08:12 +00002694 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002695 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2696 HasExplicitTemplateArgs,
2697 ExplicitTemplateArgs,
2698 NumExplicitTemplateArgs,
2699 LParenLoc, Args, NumArgs, CommaLocs,
2700 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002701 if (!FDecl)
2702 return ExprError();
2703
2704 // Update Fn to refer to the actual function selected.
2705 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002706 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002707 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002708 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2709 QDRExpr->getLocation(),
2710 false, false,
2711 QDRExpr->getQualifierRange(),
2712 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002713 else
Mike Stump9afab102009-02-19 03:04:26 +00002714 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002715 Fn->getSourceRange().getBegin());
2716 Fn->Destroy(Context);
2717 Fn = NewFn;
2718 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002719 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002720
2721 // Promote the function operand.
2722 UsualUnaryConversions(Fn);
2723
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002724 // Make the call expr early, before semantic checks. This guarantees cleanup
2725 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002726 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2727 Args, NumArgs,
2728 Context.BoolTy,
2729 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002730
Steve Naroffd6163f32008-09-05 22:11:13 +00002731 const FunctionType *FuncT;
2732 if (!Fn->getType()->isBlockPointerType()) {
2733 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2734 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002735 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002736 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002737 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2738 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002739 FuncT = PT->getPointeeType()->getAsFunctionType();
2740 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002741 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002742 getAsFunctionType();
2743 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002744 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002745 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2746 << Fn->getType() << Fn->getSourceRange());
2747
Eli Friedman83dec9e2009-03-22 22:00:50 +00002748 // Check for a valid return type
2749 if (!FuncT->getResultType()->isVoidType() &&
2750 RequireCompleteType(Fn->getSourceRange().getBegin(),
2751 FuncT->getResultType(),
2752 diag::err_call_incomplete_return,
2753 TheCall->getSourceRange()))
2754 return ExprError();
2755
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002756 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002757 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002758
Douglas Gregor4fa58902009-02-26 23:50:07 +00002759 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002760 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002761 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002762 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002763 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002764 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002765
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002766 if (FDecl) {
2767 // Check if we have too few/too many template arguments, based
2768 // on our knowledge of the function definition.
2769 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002770 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002771 const FunctionProtoType *Proto =
2772 Def->getType()->getAsFunctionProtoType();
2773 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2774 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2775 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2776 }
2777 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002778 }
2779
Steve Naroffdb65e052007-08-28 23:30:39 +00002780 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002781 for (unsigned i = 0; i != NumArgs; i++) {
2782 Expr *Arg = Args[i];
2783 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002784 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2785 Arg->getType(),
2786 diag::err_call_incomplete_argument,
2787 Arg->getSourceRange()))
2788 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002789 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002790 }
Chris Lattner4b009652007-07-25 00:24:17 +00002791 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002792
Douglas Gregor3257fb52008-12-22 05:46:06 +00002793 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2794 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002795 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2796 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002797
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002798 // Check for sentinels
2799 if (NDecl)
2800 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002801
Chris Lattner2e64c072007-08-10 20:18:51 +00002802 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002803 if (FDecl) {
2804 if (CheckFunctionCall(FDecl, TheCall.get()))
2805 return ExprError();
2806
2807 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2808 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2809 } else if (NDecl) {
2810 if (CheckBlockCall(NDecl, TheCall.get()))
2811 return ExprError();
2812 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002813
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002814 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002815}
2816
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002817Action::OwningExprResult
2818Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2819 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002820 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002821 //FIXME: Preserve type source info.
2822 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002823 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002824 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002825 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002826
Eli Friedman8c2173d2008-05-20 05:22:08 +00002827 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002828 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002829 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2830 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002831 } else if (!literalType->isDependentType() &&
2832 RequireCompleteType(LParenLoc, literalType,
2833 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002834 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002835 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002836
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002837 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002838 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002839 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002840
Chris Lattnere5cb5862008-12-04 23:50:19 +00002841 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002842 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002843 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002844 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002845 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002846 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002847 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002848 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002849}
2850
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002851Action::OwningExprResult
2852Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002853 SourceLocation RBraceLoc) {
2854 unsigned NumInit = initlist.size();
2855 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002856
Steve Naroff0acc9c92007-09-15 18:49:24 +00002857 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002858 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002859
Mike Stump9afab102009-02-19 03:04:26 +00002860 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002861 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002862 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002863 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002864}
2865
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002866/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002867bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Anders Carlsson9583fa72009-08-07 22:21:05 +00002868 CastExpr::CastKind& Kind, bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002869 if (getLangOptions().CPlusPlus)
Anders Carlsson9583fa72009-08-07 22:21:05 +00002870 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002871
Eli Friedman01e0f652009-08-15 19:02:19 +00002872 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002873
2874 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2875 // type needs to be scalar.
2876 if (castType->isVoidType()) {
2877 // Cast to void allows any expr type.
2878 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002879 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2880 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2881 (castType->isStructureType() || castType->isUnionType())) {
2882 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002883 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002884 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2885 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002886 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002887 } else if (castType->isUnionType()) {
2888 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002889 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002890 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002891 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002892 Field != FieldEnd; ++Field) {
2893 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2894 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2895 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2896 << castExpr->getSourceRange();
2897 break;
2898 }
2899 }
2900 if (Field == FieldEnd)
2901 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2902 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002903 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002904 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002905 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002906 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002907 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002908 }
Mike Stump9afab102009-02-19 03:04:26 +00002909 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002910 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002911 return Diag(castExpr->getLocStart(),
2912 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002913 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002914 } else if (castType->isExtVectorType()) {
2915 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002916 return true;
2917 } else if (castType->isVectorType()) {
2918 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2919 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002920 } else if (castExpr->getType()->isVectorType()) {
2921 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2922 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002923 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002924 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002925 } else if (!castType->isArithmeticType()) {
2926 QualType castExprType = castExpr->getType();
2927 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2928 return Diag(castExpr->getLocStart(),
2929 diag::err_cast_pointer_from_non_pointer_int)
2930 << castExprType << castExpr->getSourceRange();
2931 } else if (!castExpr->getType()->isArithmeticType()) {
2932 if (!castType->isIntegralType() && castType->isArithmeticType())
2933 return Diag(castExpr->getLocStart(),
2934 diag::err_cast_pointer_to_non_pointer_int)
2935 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002936 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00002937 if (isa<ObjCSelectorExpr>(castExpr))
2938 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002939 return false;
2940}
2941
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002942bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002943 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002944
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002945 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002946 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002947 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002948 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002949 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002950 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002951 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002952 } else
2953 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002954 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002955 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002956
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002957 return false;
2958}
2959
Nate Begemanbd42e022009-06-26 00:50:28 +00002960bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
2961 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
2962
Nate Begeman9e063702009-06-27 22:05:55 +00002963 // If SrcTy is a VectorType, the total size must match to explicitly cast to
2964 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00002965 if (SrcTy->isVectorType()) {
2966 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
2967 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
2968 << DestTy << SrcTy << R;
2969 return false;
2970 }
2971
Nate Begeman0e0eadd2009-06-28 02:36:38 +00002972 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00002973 // conversion will take place first from scalar to elt type, and then
2974 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00002975 if (SrcTy->isPointerType())
2976 return Diag(R.getBegin(),
2977 diag::err_invalid_conversion_between_vector_and_scalar)
2978 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00002979 return false;
2980}
2981
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002982Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00002983Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002984 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00002985 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
2986
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002987 assert((Ty != 0) && (Op.get() != 0) &&
2988 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002989
Nate Begemane85f43d2009-08-10 23:49:36 +00002990 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002991 //FIXME: Preserve type source info.
2992 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00002993
2994 // If the Expr being casted is a ParenListExpr, handle it specially.
2995 if (isa<ParenListExpr>(castExpr))
2996 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Chris Lattner4b009652007-07-25 00:24:17 +00002997
Anders Carlsson9583fa72009-08-07 22:21:05 +00002998 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
2999 Kind))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003000 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003001
3002 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003003 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003004 Kind, castExpr, castType,
3005 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003006}
3007
Nate Begemane85f43d2009-08-10 23:49:36 +00003008/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3009/// of comma binary operators.
3010Action::OwningExprResult
3011Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3012 Expr *expr = EA.takeAs<Expr>();
3013 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3014 if (!E)
3015 return Owned(expr);
3016
3017 OwningExprResult Result(*this, E->getExpr(0));
3018
3019 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3020 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3021 Owned(E->getExpr(i)));
3022
3023 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3024}
3025
3026Action::OwningExprResult
3027Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3028 SourceLocation RParenLoc, ExprArg Op,
3029 QualType Ty) {
3030 ParenListExpr *PE = (ParenListExpr *)Op.get();
3031
3032 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3033 // then handle it as such.
3034 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3035 if (PE->getNumExprs() == 0) {
3036 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3037 return ExprError();
3038 }
3039
3040 llvm::SmallVector<Expr *, 8> initExprs;
3041 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3042 initExprs.push_back(PE->getExpr(i));
3043
3044 // FIXME: This means that pretty-printing the final AST will produce curly
3045 // braces instead of the original commas.
3046 Op.release();
3047 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3048 initExprs.size(), RParenLoc);
3049 E->setType(Ty);
3050 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3051 Owned(E));
3052 } else {
3053 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3054 // sequence of BinOp comma operators.
3055 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3056 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3057 }
3058}
3059
3060Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3061 SourceLocation R,
3062 MultiExprArg Val) {
3063 unsigned nexprs = Val.size();
3064 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3065 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3066 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3067 return Owned(expr);
3068}
3069
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003070/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3071/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003072/// C99 6.5.15
3073QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3074 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003075 // C++ is sufficiently different to merit its own checker.
3076 if (getLangOptions().CPlusPlus)
3077 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3078
Chris Lattnere2897262009-02-18 04:28:32 +00003079 UsualUnaryConversions(Cond);
3080 UsualUnaryConversions(LHS);
3081 UsualUnaryConversions(RHS);
3082 QualType CondTy = Cond->getType();
3083 QualType LHSTy = LHS->getType();
3084 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003085
3086 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003087 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3088 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3089 << CondTy;
3090 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003091 }
Mike Stump9afab102009-02-19 03:04:26 +00003092
Chris Lattner992ae932008-01-06 22:42:25 +00003093 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003094 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3095 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003096
Chris Lattner992ae932008-01-06 22:42:25 +00003097 // If both operands have arithmetic type, do the usual arithmetic conversions
3098 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003099 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3100 UsualArithmeticConversions(LHS, RHS);
3101 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003102 }
Mike Stump9afab102009-02-19 03:04:26 +00003103
Chris Lattner992ae932008-01-06 22:42:25 +00003104 // If both operands are the same structure or union type, the result is that
3105 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003106 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3107 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003108 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003109 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003110 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003111 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003112 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003113 }
Mike Stump9afab102009-02-19 03:04:26 +00003114
Chris Lattner992ae932008-01-06 22:42:25 +00003115 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003116 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003117 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3118 if (!LHSTy->isVoidType())
3119 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3120 << RHS->getSourceRange();
3121 if (!RHSTy->isVoidType())
3122 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3123 << LHS->getSourceRange();
3124 ImpCastExprToType(LHS, Context.VoidTy);
3125 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003126 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003127 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003128 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3129 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003130 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003131 RHS->isNullPointerConstant(Context)) {
3132 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3133 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003134 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003135 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003136 LHS->isNullPointerConstant(Context)) {
3137 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3138 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003139 }
David Chisnall44663db2009-08-17 16:35:33 +00003140 // Handle things like Class and struct objc_class*. Here we case the result
3141 // to the pseudo-builtin, because that will be implicitly cast back to the
3142 // redefinition type if an attempt is made to access its fields.
3143 if (LHSTy->isObjCClassType() &&
3144 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3145 ImpCastExprToType(RHS, LHSTy);
3146 return LHSTy;
3147 }
3148 if (RHSTy->isObjCClassType() &&
3149 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3150 ImpCastExprToType(LHS, RHSTy);
3151 return RHSTy;
3152 }
3153 // And the same for struct objc_object* / id
3154 if (LHSTy->isObjCIdType() &&
3155 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3156 ImpCastExprToType(RHS, LHSTy);
3157 return LHSTy;
3158 }
3159 if (RHSTy->isObjCIdType() &&
3160 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3161 ImpCastExprToType(LHS, RHSTy);
3162 return RHSTy;
3163 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003164 // Handle block pointer types.
3165 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3166 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3167 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3168 QualType destType = Context.getPointerType(Context.VoidTy);
3169 ImpCastExprToType(LHS, destType);
3170 ImpCastExprToType(RHS, destType);
3171 return destType;
3172 }
3173 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3174 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3175 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003176 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003177 // We have 2 block pointer types.
3178 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3179 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003180 return LHSTy;
3181 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003182 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003183 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3184 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003185
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003186 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3187 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003188 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3189 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3190 // In this situation, we assume void* type. No especially good
3191 // reason, but this is what gcc does, and we do have to pick
3192 // to get a consistent AST.
3193 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3194 ImpCastExprToType(LHS, incompatTy);
3195 ImpCastExprToType(RHS, incompatTy);
3196 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003197 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003198 // The block pointer types are compatible.
3199 ImpCastExprToType(LHS, LHSTy);
3200 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003201 return LHSTy;
3202 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003203 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003204 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003205
3206 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3207 // Two identical object pointer types are always compatible.
3208 return LHSTy;
3209 }
Steve Naroff329ec222009-07-10 23:34:53 +00003210 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3211 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003212 QualType compositeType = LHSTy;
3213
3214 // If both operands are interfaces and either operand can be
3215 // assigned to the other, use that type as the composite
3216 // type. This allows
3217 // xxx ? (A*) a : (B*) b
3218 // where B is a subclass of A.
3219 //
3220 // Additionally, as for assignment, if either type is 'id'
3221 // allow silent coercion. Finally, if the types are
3222 // incompatible then make sure to use 'id' as the composite
3223 // type so the result is acceptable for sending messages to.
3224
3225 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3226 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003227 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003228 compositeType = LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003229 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003230 compositeType = RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003231 } else if ((LHSTy->isObjCQualifiedIdType() ||
3232 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003233 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003234 // Need to handle "id<xx>" explicitly.
3235 // GCC allows qualified id and any Objective-C type to devolve to
3236 // id. Currently localizing to here until clear this should be
3237 // part of ObjCQualifiedIdTypesAreCompatible.
3238 compositeType = Context.getObjCIdType();
3239 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003240 compositeType = Context.getObjCIdType();
3241 } else {
3242 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3243 << LHSTy << RHSTy
3244 << LHS->getSourceRange() << RHS->getSourceRange();
3245 QualType incompatTy = Context.getObjCIdType();
3246 ImpCastExprToType(LHS, incompatTy);
3247 ImpCastExprToType(RHS, incompatTy);
3248 return incompatTy;
3249 }
3250 // The object pointer types are compatible.
3251 ImpCastExprToType(LHS, compositeType);
3252 ImpCastExprToType(RHS, compositeType);
3253 return compositeType;
3254 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003255 // Check Objective-C object pointer types and 'void *'
3256 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003257 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003258 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3259 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3260 QualType destType = Context.getPointerType(destPointee);
3261 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3262 ImpCastExprToType(RHS, destType); // promote to void*
3263 return destType;
3264 }
3265 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3266 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003267 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003268 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3269 QualType destType = Context.getPointerType(destPointee);
3270 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3271 ImpCastExprToType(LHS, destType); // promote to void*
3272 return destType;
3273 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003274 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3275 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3276 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003277 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3278 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003279
3280 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3281 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3282 // Figure out necessary qualifiers (C99 6.5.15p6)
3283 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3284 QualType destType = Context.getPointerType(destPointee);
3285 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3286 ImpCastExprToType(RHS, destType); // promote to void*
3287 return destType;
3288 }
3289 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3290 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3291 QualType destType = Context.getPointerType(destPointee);
3292 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3293 ImpCastExprToType(RHS, destType); // promote to void*
3294 return destType;
3295 }
3296
3297 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3298 // Two identical pointer types are always compatible.
3299 return LHSTy;
3300 }
3301 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3302 rhptee.getUnqualifiedType())) {
3303 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3304 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3305 // In this situation, we assume void* type. No especially good
3306 // reason, but this is what gcc does, and we do have to pick
3307 // to get a consistent AST.
3308 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3309 ImpCastExprToType(LHS, incompatTy);
3310 ImpCastExprToType(RHS, incompatTy);
3311 return incompatTy;
3312 }
3313 // The pointer types are compatible.
3314 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3315 // differently qualified versions of compatible types, the result type is
3316 // a pointer to an appropriately qualified version of the *composite*
3317 // type.
3318 // FIXME: Need to calculate the composite type.
3319 // FIXME: Need to add qualifiers
3320 ImpCastExprToType(LHS, LHSTy);
3321 ImpCastExprToType(RHS, LHSTy);
3322 return LHSTy;
3323 }
3324
3325 // GCC compatibility: soften pointer/integer mismatch.
3326 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3327 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3328 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3329 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3330 return RHSTy;
3331 }
3332 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3333 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3334 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3335 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3336 return LHSTy;
3337 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003338
Chris Lattner992ae932008-01-06 22:42:25 +00003339 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003340 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3341 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003342 return QualType();
3343}
3344
Steve Naroff87d58b42007-09-16 03:34:24 +00003345/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003346/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003347Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3348 SourceLocation ColonLoc,
3349 ExprArg Cond, ExprArg LHS,
3350 ExprArg RHS) {
3351 Expr *CondExpr = (Expr *) Cond.get();
3352 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003353
3354 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3355 // was the condition.
3356 bool isLHSNull = LHSExpr == 0;
3357 if (isLHSNull)
3358 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003359
3360 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003361 RHSExpr, QuestionLoc);
3362 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003363 return ExprError();
3364
3365 Cond.release();
3366 LHS.release();
3367 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003368 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003369 isLHSNull ? 0 : LHSExpr,
3370 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003371}
3372
Chris Lattner4b009652007-07-25 00:24:17 +00003373// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003374// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003375// routine is it effectively iqnores the qualifiers on the top level pointee.
3376// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3377// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003378Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003379Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3380 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003381
David Chisnall44663db2009-08-17 16:35:33 +00003382 if ((lhsType->isObjCClassType() &&
3383 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3384 (rhsType->isObjCClassType() &&
3385 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3386 return Compatible;
3387 }
3388
Chris Lattner4b009652007-07-25 00:24:17 +00003389 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003390 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3391 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003392
Chris Lattner4b009652007-07-25 00:24:17 +00003393 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003394 lhptee = Context.getCanonicalType(lhptee);
3395 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003396
Chris Lattner005ed752008-01-04 18:04:52 +00003397 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003398
3399 // C99 6.5.16.1p1: This following citation is common to constraints
3400 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3401 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003402 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003403 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003404 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003405
Mike Stump9afab102009-02-19 03:04:26 +00003406 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3407 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003408 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003409 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003410 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003411 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003412
Chris Lattner4ca3d772008-01-03 22:56:36 +00003413 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003414 assert(rhptee->isFunctionType());
3415 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003416 }
Mike Stump9afab102009-02-19 03:04:26 +00003417
Chris Lattner4ca3d772008-01-03 22:56:36 +00003418 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003419 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003420 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003421
3422 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003423 assert(lhptee->isFunctionType());
3424 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003425 }
Mike Stump9afab102009-02-19 03:04:26 +00003426 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003427 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003428 lhptee = lhptee.getUnqualifiedType();
3429 rhptee = rhptee.getUnqualifiedType();
3430 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3431 // Check if the pointee types are compatible ignoring the sign.
3432 // We explicitly check for char so that we catch "char" vs
3433 // "unsigned char" on systems where "char" is unsigned.
3434 if (lhptee->isCharType()) {
3435 lhptee = Context.UnsignedCharTy;
3436 } else if (lhptee->isSignedIntegerType()) {
3437 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3438 }
3439 if (rhptee->isCharType()) {
3440 rhptee = Context.UnsignedCharTy;
3441 } else if (rhptee->isSignedIntegerType()) {
3442 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3443 }
3444 if (lhptee == rhptee) {
3445 // Types are compatible ignoring the sign. Qualifier incompatibility
3446 // takes priority over sign incompatibility because the sign
3447 // warning can be disabled.
3448 if (ConvTy != Compatible)
3449 return ConvTy;
3450 return IncompatiblePointerSign;
3451 }
3452 // General pointer incompatibility takes priority over qualifiers.
3453 return IncompatiblePointer;
3454 }
Chris Lattner005ed752008-01-04 18:04:52 +00003455 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003456}
3457
Steve Naroff3454b6c2008-09-04 15:10:53 +00003458/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3459/// block pointer types are compatible or whether a block and normal pointer
3460/// are compatible. It is more restrict than comparing two function pointer
3461// types.
Mike Stump9afab102009-02-19 03:04:26 +00003462Sema::AssignConvertType
3463Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003464 QualType rhsType) {
3465 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003466
Steve Naroff3454b6c2008-09-04 15:10:53 +00003467 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003468 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3469 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003470
Steve Naroff3454b6c2008-09-04 15:10:53 +00003471 // make sure we operate on the canonical type
3472 lhptee = Context.getCanonicalType(lhptee);
3473 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003474
Steve Naroff3454b6c2008-09-04 15:10:53 +00003475 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003476
Steve Naroff3454b6c2008-09-04 15:10:53 +00003477 // For blocks we enforce that qualifiers are identical.
3478 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3479 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003480
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003481 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003482 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003483 return ConvTy;
3484}
3485
Mike Stump9afab102009-02-19 03:04:26 +00003486/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3487/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003488/// pointers. Here are some objectionable examples that GCC considers warnings:
3489///
3490/// int a, *pint;
3491/// short *pshort;
3492/// struct foo *pfoo;
3493///
3494/// pint = pshort; // warning: assignment from incompatible pointer type
3495/// a = pint; // warning: assignment makes integer from pointer without a cast
3496/// pint = a; // warning: assignment makes pointer from integer without a cast
3497/// pint = pfoo; // warning: assignment from incompatible pointer type
3498///
3499/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003500/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003501///
Chris Lattner005ed752008-01-04 18:04:52 +00003502Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003503Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003504 // Get canonical types. We're not formatting these types, just comparing
3505 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003506 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3507 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003508
3509 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003510 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003511
David Chisnall44663db2009-08-17 16:35:33 +00003512 if ((lhsType->isObjCClassType() &&
3513 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3514 (rhsType->isObjCClassType() &&
3515 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3516 return Compatible;
3517 }
3518
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003519 // If the left-hand side is a reference type, then we are in a
3520 // (rare!) case where we've allowed the use of references in C,
3521 // e.g., as a parameter type in a built-in function. In this case,
3522 // just make sure that the type referenced is compatible with the
3523 // right-hand side type. The caller is responsible for adjusting
3524 // lhsType so that the resulting expression does not have reference
3525 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003526 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003527 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003528 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003529 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003530 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003531 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3532 // to the same ExtVector type.
3533 if (lhsType->isExtVectorType()) {
3534 if (rhsType->isExtVectorType())
3535 return lhsType == rhsType ? Compatible : Incompatible;
3536 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3537 return Compatible;
3538 }
3539
Nate Begemanc5f0f652008-07-14 18:02:46 +00003540 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003541 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003542 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003543 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003544 if (getLangOptions().LaxVectorConversions &&
3545 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003546 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003547 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003548 }
3549 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003550 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003551
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003552 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003553 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003554
Chris Lattner390564e2008-04-07 06:49:41 +00003555 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003556 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003557 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003558
Chris Lattner390564e2008-04-07 06:49:41 +00003559 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003560 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003561
Steve Naroff8194a542009-07-20 17:56:53 +00003562 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003563 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003564 if (lhsType->isVoidPointerType()) // an exception to the rule.
3565 return Compatible;
3566 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003567 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003568 if (rhsType->getAs<BlockPointerType>()) {
3569 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003570 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003571
3572 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003573 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003574 return Compatible;
3575 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003576 return Incompatible;
3577 }
3578
3579 if (isa<BlockPointerType>(lhsType)) {
3580 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003581 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003582
Steve Naroffa982c712008-09-29 18:10:17 +00003583 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003584 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003585 return Compatible;
3586
Steve Naroff3454b6c2008-09-04 15:10:53 +00003587 if (rhsType->isBlockPointerType())
3588 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003589
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003590 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003591 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003592 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003593 }
Chris Lattner1853da22008-01-04 23:18:45 +00003594 return Incompatible;
3595 }
3596
Steve Naroff329ec222009-07-10 23:34:53 +00003597 if (isa<ObjCObjectPointerType>(lhsType)) {
3598 if (rhsType->isIntegerType())
3599 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003600
3601 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003602 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003603 if (rhsType->isVoidPointerType()) // an exception to the rule.
3604 return Compatible;
3605 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003606 }
3607 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003608 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3609 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003610 if (Context.typesAreCompatible(lhsType, rhsType))
3611 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003612 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3613 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003614 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003615 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003616 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003617 if (RHSPT->getPointeeType()->isVoidType())
3618 return Compatible;
3619 }
3620 // Treat block pointers as objects.
3621 if (rhsType->isBlockPointerType())
3622 return Compatible;
3623 return Incompatible;
3624 }
Chris Lattner390564e2008-04-07 06:49:41 +00003625 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003626 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003627 if (lhsType == Context.BoolTy)
3628 return Compatible;
3629
3630 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003631 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003632
Mike Stump9afab102009-02-19 03:04:26 +00003633 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003634 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003635
3636 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003637 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003638 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003639 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003640 }
Steve Naroff329ec222009-07-10 23:34:53 +00003641 if (isa<ObjCObjectPointerType>(rhsType)) {
3642 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3643 if (lhsType == Context.BoolTy)
3644 return Compatible;
3645
3646 if (lhsType->isIntegerType())
3647 return PointerToInt;
3648
Steve Naroff8194a542009-07-20 17:56:53 +00003649 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003650 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003651 if (lhsType->isVoidPointerType()) // an exception to the rule.
3652 return Compatible;
3653 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003654 }
3655 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003656 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003657 return Compatible;
3658 return Incompatible;
3659 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003660
Chris Lattner1853da22008-01-04 23:18:45 +00003661 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003662 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003663 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003664 }
3665 return Incompatible;
3666}
3667
Douglas Gregor144b06c2009-04-29 22:16:16 +00003668/// \brief Constructs a transparent union from an expression that is
3669/// used to initialize the transparent union.
3670static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3671 QualType UnionType, FieldDecl *Field) {
3672 // Build an initializer list that designates the appropriate member
3673 // of the transparent union.
3674 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3675 &E, 1,
3676 SourceLocation());
3677 Initializer->setType(UnionType);
3678 Initializer->setInitializedFieldInUnion(Field);
3679
3680 // Build a compound literal constructing a value of the transparent
3681 // union type from this initializer list.
3682 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3683 false);
3684}
3685
3686Sema::AssignConvertType
3687Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3688 QualType FromType = rExpr->getType();
3689
3690 // If the ArgType is a Union type, we want to handle a potential
3691 // transparent_union GCC extension.
3692 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003693 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003694 return Incompatible;
3695
3696 // The field to initialize within the transparent union.
3697 RecordDecl *UD = UT->getDecl();
3698 FieldDecl *InitField = 0;
3699 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003700 for (RecordDecl::field_iterator it = UD->field_begin(),
3701 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003702 it != itend; ++it) {
3703 if (it->getType()->isPointerType()) {
3704 // If the transparent union contains a pointer type, we allow:
3705 // 1) void pointer
3706 // 2) null pointer constant
3707 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003708 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003709 ImpCastExprToType(rExpr, it->getType());
3710 InitField = *it;
3711 break;
3712 }
3713
3714 if (rExpr->isNullPointerConstant(Context)) {
3715 ImpCastExprToType(rExpr, it->getType());
3716 InitField = *it;
3717 break;
3718 }
3719 }
3720
3721 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3722 == Compatible) {
3723 InitField = *it;
3724 break;
3725 }
3726 }
3727
3728 if (!InitField)
3729 return Incompatible;
3730
3731 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3732 return Compatible;
3733}
3734
Chris Lattner005ed752008-01-04 18:04:52 +00003735Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003736Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003737 if (getLangOptions().CPlusPlus) {
3738 if (!lhsType->isRecordType()) {
3739 // C++ 5.17p3: If the left operand is not of class type, the
3740 // expression is implicitly converted (C++ 4) to the
3741 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003742 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3743 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003744 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003745 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003746 }
3747
3748 // FIXME: Currently, we fall through and treat C++ classes like C
3749 // structures.
3750 }
3751
Steve Naroffcdee22d2007-11-27 17:58:44 +00003752 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3753 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003754 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003755 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003756 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003757 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003758 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003759 return Compatible;
3760 }
Mike Stump9afab102009-02-19 03:04:26 +00003761
Chris Lattner5f505bf2007-10-16 02:55:40 +00003762 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003763 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003764 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003765 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003766 //
Mike Stump9afab102009-02-19 03:04:26 +00003767 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003768 if (!lhsType->isReferenceType())
3769 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003770
Chris Lattner005ed752008-01-04 18:04:52 +00003771 Sema::AssignConvertType result =
3772 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003773
Steve Naroff0f32f432007-08-24 22:33:52 +00003774 // C99 6.5.16.1p2: The value of the right operand is converted to the
3775 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003776 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3777 // so that we can use references in built-in functions even in C.
3778 // The getNonReferenceType() call makes sure that the resulting expression
3779 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003780 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003781 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003782 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003783}
3784
Chris Lattner1eafdea2008-11-18 01:30:42 +00003785QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003786 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003787 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003788 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003789 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003790}
3791
Mike Stump9afab102009-02-19 03:04:26 +00003792inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003793 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003794 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003795 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003796 QualType lhsType =
3797 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3798 QualType rhsType =
3799 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003800
Nate Begemanc5f0f652008-07-14 18:02:46 +00003801 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003802 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003803 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003804
Nate Begemanc5f0f652008-07-14 18:02:46 +00003805 // Handle the case of a vector & extvector type of the same size and element
3806 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003807 if (getLangOptions().LaxVectorConversions) {
3808 // FIXME: Should we warn here?
3809 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003810 if (const VectorType *RV = rhsType->getAsVectorType())
3811 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003812 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003813 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003814 }
3815 }
3816 }
Mike Stump9afab102009-02-19 03:04:26 +00003817
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003818 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3819 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3820 bool swapped = false;
3821 if (rhsType->isExtVectorType()) {
3822 swapped = true;
3823 std::swap(rex, lex);
3824 std::swap(rhsType, lhsType);
3825 }
3826
Nate Begemanf1695892009-06-28 19:12:57 +00003827 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003828 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3829 QualType EltTy = LV->getElementType();
3830 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3831 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003832 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003833 if (swapped) std::swap(rex, lex);
3834 return lhsType;
3835 }
3836 }
3837 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3838 rhsType->isRealFloatingType()) {
3839 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003840 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003841 if (swapped) std::swap(rex, lex);
3842 return lhsType;
3843 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003844 }
3845 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003846
Nate Begemanf1695892009-06-28 19:12:57 +00003847 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003848 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003849 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003850 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003851 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003852}
3853
Chris Lattner4b009652007-07-25 00:24:17 +00003854inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003855 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003856{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003857 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003858 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003859
Steve Naroff8f708362007-08-24 19:07:16 +00003860 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003861
Chris Lattner4b009652007-07-25 00:24:17 +00003862 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003863 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003864 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003865}
3866
3867inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003868 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003869{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003870 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3871 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3872 return CheckVectorOperands(Loc, lex, rex);
3873 return InvalidOperands(Loc, lex, rex);
3874 }
Chris Lattner4b009652007-07-25 00:24:17 +00003875
Steve Naroff8f708362007-08-24 19:07:16 +00003876 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003877
Chris Lattner4b009652007-07-25 00:24:17 +00003878 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003879 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003880 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003881}
3882
3883inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003884 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003885{
Eli Friedman3cd92882009-03-28 01:22:36 +00003886 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3887 QualType compType = CheckVectorOperands(Loc, lex, rex);
3888 if (CompLHSTy) *CompLHSTy = compType;
3889 return compType;
3890 }
Chris Lattner4b009652007-07-25 00:24:17 +00003891
Eli Friedman3cd92882009-03-28 01:22:36 +00003892 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003893
Chris Lattner4b009652007-07-25 00:24:17 +00003894 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003895 if (lex->getType()->isArithmeticType() &&
3896 rex->getType()->isArithmeticType()) {
3897 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003898 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003899 }
Chris Lattner4b009652007-07-25 00:24:17 +00003900
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003901 // Put any potential pointer into PExp
3902 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003903 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003904 std::swap(PExp, IExp);
3905
Steve Naroff79ae19a2009-07-14 18:25:06 +00003906 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003907
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003908 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003909 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003910
Chris Lattner184f92d2009-04-24 23:50:08 +00003911 // Check for arithmetic on pointers to incomplete types.
3912 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003913 if (getLangOptions().CPlusPlus) {
3914 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003915 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003916 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003917 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003918
3919 // GNU extension: arithmetic on pointer to void
3920 Diag(Loc, diag::ext_gnu_void_ptr)
3921 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003922 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003923 if (getLangOptions().CPlusPlus) {
3924 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3925 << lex->getType() << lex->getSourceRange();
3926 return QualType();
3927 }
3928
3929 // GNU extension: arithmetic on pointer to function
3930 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3931 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00003932 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00003933 // Check if we require a complete type.
3934 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00003935 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00003936 PExp->getType()->isObjCObjectPointerType()) &&
3937 RequireCompleteType(Loc, PointeeTy,
3938 diag::err_typecheck_arithmetic_incomplete_type,
3939 PExp->getSourceRange(), SourceRange(),
3940 PExp->getType()))
3941 return QualType();
3942 }
Chris Lattner184f92d2009-04-24 23:50:08 +00003943 // Diagnose bad cases where we step over interface counts.
3944 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3945 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3946 << PointeeTy << PExp->getSourceRange();
3947 return QualType();
3948 }
3949
Eli Friedman3cd92882009-03-28 01:22:36 +00003950 if (CompLHSTy) {
3951 QualType LHSTy = lex->getType();
3952 if (LHSTy->isPromotableIntegerType())
Eli Friedman6ae7d112009-08-19 07:44:53 +00003953 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003954 else {
3955 QualType T = isPromotableBitField(lex, Context);
3956 if (!T.isNull())
3957 LHSTy = T;
3958 }
3959
Eli Friedman3cd92882009-03-28 01:22:36 +00003960 *CompLHSTy = LHSTy;
3961 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003962 return PExp->getType();
3963 }
3964 }
3965
Chris Lattner1eafdea2008-11-18 01:30:42 +00003966 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003967}
3968
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003969// C99 6.5.6
3970QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003971 SourceLocation Loc, QualType* CompLHSTy) {
3972 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3973 QualType compType = CheckVectorOperands(Loc, lex, rex);
3974 if (CompLHSTy) *CompLHSTy = compType;
3975 return compType;
3976 }
Mike Stump9afab102009-02-19 03:04:26 +00003977
Eli Friedman3cd92882009-03-28 01:22:36 +00003978 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003979
Chris Lattnerf6da2912007-12-09 21:53:25 +00003980 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003981
Chris Lattnerf6da2912007-12-09 21:53:25 +00003982 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00003983 if (lex->getType()->isArithmeticType()
3984 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00003985 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003986 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003987 }
Steve Naroff329ec222009-07-10 23:34:53 +00003988
Chris Lattnerf6da2912007-12-09 21:53:25 +00003989 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00003990 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00003991 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003992
Douglas Gregor05e28f62009-03-24 19:52:54 +00003993 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003994
Douglas Gregor05e28f62009-03-24 19:52:54 +00003995 bool ComplainAboutVoid = false;
3996 Expr *ComplainAboutFunc = 0;
3997 if (lpointee->isVoidType()) {
3998 if (getLangOptions().CPlusPlus) {
3999 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4000 << lex->getSourceRange() << rex->getSourceRange();
4001 return QualType();
4002 }
4003
4004 // GNU C extension: arithmetic on pointer to void
4005 ComplainAboutVoid = true;
4006 } else if (lpointee->isFunctionType()) {
4007 if (getLangOptions().CPlusPlus) {
4008 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004009 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004010 return QualType();
4011 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004012
4013 // GNU C extension: arithmetic on pointer to function
4014 ComplainAboutFunc = lex;
4015 } else if (!lpointee->isDependentType() &&
4016 RequireCompleteType(Loc, lpointee,
4017 diag::err_typecheck_sub_ptr_object,
4018 lex->getSourceRange(),
4019 SourceRange(),
4020 lex->getType()))
4021 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004022
Chris Lattner184f92d2009-04-24 23:50:08 +00004023 // Diagnose bad cases where we step over interface counts.
4024 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4025 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4026 << lpointee << lex->getSourceRange();
4027 return QualType();
4028 }
4029
Chris Lattnerf6da2912007-12-09 21:53:25 +00004030 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004031 if (rex->getType()->isIntegerType()) {
4032 if (ComplainAboutVoid)
4033 Diag(Loc, diag::ext_gnu_void_ptr)
4034 << lex->getSourceRange() << rex->getSourceRange();
4035 if (ComplainAboutFunc)
4036 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4037 << ComplainAboutFunc->getType()
4038 << ComplainAboutFunc->getSourceRange();
4039
Eli Friedman3cd92882009-03-28 01:22:36 +00004040 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004041 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004042 }
Mike Stump9afab102009-02-19 03:04:26 +00004043
Chris Lattnerf6da2912007-12-09 21:53:25 +00004044 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004045 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004046 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004047
Douglas Gregor05e28f62009-03-24 19:52:54 +00004048 // RHS must be a completely-type object type.
4049 // Handle the GNU void* extension.
4050 if (rpointee->isVoidType()) {
4051 if (getLangOptions().CPlusPlus) {
4052 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4053 << lex->getSourceRange() << rex->getSourceRange();
4054 return QualType();
4055 }
Mike Stump9afab102009-02-19 03:04:26 +00004056
Douglas Gregor05e28f62009-03-24 19:52:54 +00004057 ComplainAboutVoid = true;
4058 } else if (rpointee->isFunctionType()) {
4059 if (getLangOptions().CPlusPlus) {
4060 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004061 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004062 return QualType();
4063 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004064
4065 // GNU extension: arithmetic on pointer to function
4066 if (!ComplainAboutFunc)
4067 ComplainAboutFunc = rex;
4068 } else if (!rpointee->isDependentType() &&
4069 RequireCompleteType(Loc, rpointee,
4070 diag::err_typecheck_sub_ptr_object,
4071 rex->getSourceRange(),
4072 SourceRange(),
4073 rex->getType()))
4074 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004075
Eli Friedman143ddc92009-05-16 13:54:38 +00004076 if (getLangOptions().CPlusPlus) {
4077 // Pointee types must be the same: C++ [expr.add]
4078 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4079 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4080 << lex->getType() << rex->getType()
4081 << lex->getSourceRange() << rex->getSourceRange();
4082 return QualType();
4083 }
4084 } else {
4085 // Pointee types must be compatible C99 6.5.6p3
4086 if (!Context.typesAreCompatible(
4087 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4088 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4089 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4090 << lex->getType() << rex->getType()
4091 << lex->getSourceRange() << rex->getSourceRange();
4092 return QualType();
4093 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004094 }
Mike Stump9afab102009-02-19 03:04:26 +00004095
Douglas Gregor05e28f62009-03-24 19:52:54 +00004096 if (ComplainAboutVoid)
4097 Diag(Loc, diag::ext_gnu_void_ptr)
4098 << lex->getSourceRange() << rex->getSourceRange();
4099 if (ComplainAboutFunc)
4100 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4101 << ComplainAboutFunc->getType()
4102 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004103
4104 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004105 return Context.getPointerDiffType();
4106 }
4107 }
Mike Stump9afab102009-02-19 03:04:26 +00004108
Chris Lattner1eafdea2008-11-18 01:30:42 +00004109 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004110}
4111
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004112// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004113QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004114 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004115 // C99 6.5.7p2: Each of the operands shall have integer type.
4116 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004117 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004118
Chris Lattner2c8bff72007-12-12 05:47:28 +00004119 // Shifts don't perform usual arithmetic conversions, they just do integer
4120 // promotions on each operand. C99 6.5.7p3
Eli Friedman6ae7d112009-08-19 07:44:53 +00004121 QualType LHSTy = lex->getType();
4122 if (LHSTy->isPromotableIntegerType())
4123 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004124 else {
Eli Friedman6ae7d112009-08-19 07:44:53 +00004125 QualType T = isPromotableBitField(lex, Context);
4126 if (!T.isNull())
4127 LHSTy = T;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004128 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004129 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004130 ImpCastExprToType(lex, LHSTy);
4131
Chris Lattner2c8bff72007-12-12 05:47:28 +00004132 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004133
Ryan Flynnf109fff2009-08-07 16:20:20 +00004134 // Sanity-check shift operands
4135 llvm::APSInt Right;
4136 // Check right/shifter operand
4137 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004138 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004139 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4140 else {
4141 llvm::APInt LeftBits(Right.getBitWidth(),
4142 Context.getTypeSize(lex->getType()));
4143 if (Right.uge(LeftBits))
4144 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4145 }
4146 }
4147
Chris Lattner2c8bff72007-12-12 05:47:28 +00004148 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004149 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004150}
4151
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004152// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004153QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004154 unsigned OpaqueOpc, bool isRelational) {
4155 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4156
Nate Begemanc5f0f652008-07-14 18:02:46 +00004157 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004158 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004159
Chris Lattner254f3bc2007-08-26 01:18:55 +00004160 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004161 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4162 UsualArithmeticConversions(lex, rex);
4163 else {
4164 UsualUnaryConversions(lex);
4165 UsualUnaryConversions(rex);
4166 }
Chris Lattner4b009652007-07-25 00:24:17 +00004167 QualType lType = lex->getType();
4168 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004169
Mike Stumpea3d74e2009-05-07 18:43:07 +00004170 if (!lType->isFloatingType()
4171 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004172 // For non-floating point types, check for self-comparisons of the form
4173 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4174 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004175 // NOTE: Don't warn about comparisons of enum constants. These can arise
4176 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004177 Expr *LHSStripped = lex->IgnoreParens();
4178 Expr *RHSStripped = rex->IgnoreParens();
4179 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4180 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004181 if (DRL->getDecl() == DRR->getDecl() &&
4182 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004183 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004184
4185 if (isa<CastExpr>(LHSStripped))
4186 LHSStripped = LHSStripped->IgnoreParenCasts();
4187 if (isa<CastExpr>(RHSStripped))
4188 RHSStripped = RHSStripped->IgnoreParenCasts();
4189
4190 // Warn about comparisons against a string constant (unless the other
4191 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004192 Expr *literalString = 0;
4193 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004194 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004195 !RHSStripped->isNullPointerConstant(Context)) {
4196 literalString = lex;
4197 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004198 } else if ((isa<StringLiteral>(RHSStripped) ||
4199 isa<ObjCEncodeExpr>(RHSStripped)) &&
4200 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004201 literalString = rex;
4202 literalStringStripped = RHSStripped;
4203 }
4204
4205 if (literalString) {
4206 std::string resultComparison;
4207 switch (Opc) {
4208 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4209 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4210 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4211 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4212 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4213 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4214 default: assert(false && "Invalid comparison operator");
4215 }
4216 Diag(Loc, diag::warn_stringcompare)
4217 << isa<ObjCEncodeExpr>(literalStringStripped)
4218 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004219 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4220 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4221 "strcmp(")
4222 << CodeModificationHint::CreateInsertion(
4223 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004224 resultComparison);
4225 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004226 }
Mike Stump9afab102009-02-19 03:04:26 +00004227
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004228 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004229 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004230
Chris Lattner254f3bc2007-08-26 01:18:55 +00004231 if (isRelational) {
4232 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004233 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004234 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004235 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004236 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004237 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004238 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004239 }
Mike Stump9afab102009-02-19 03:04:26 +00004240
Chris Lattner254f3bc2007-08-26 01:18:55 +00004241 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004242 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004243 }
Mike Stump9afab102009-02-19 03:04:26 +00004244
Chris Lattner22be8422007-08-26 01:10:14 +00004245 bool LHSIsNull = lex->isNullPointerConstant(Context);
4246 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004247
Chris Lattner254f3bc2007-08-26 01:18:55 +00004248 // All of the following pointer related warnings are GCC extensions, except
4249 // when handling null pointer constants. One day, we can consider making them
4250 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004251 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004252 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004253 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004254 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004255 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004256
Douglas Gregor4da47382009-07-06 20:14:23 +00004257 if (isRelational) {
4258 if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004259 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4260 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4261 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004262 if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) {
4263 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4264 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4265 }
4266 } else {
4267 if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) {
4268 if (!LHSIsNull && !RHSIsNull)
4269 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4270 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4271 }
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004272 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004273
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004274 // Simple check: if the pointee types are identical, we're done.
4275 if (LCanPointeeTy == RCanPointeeTy)
4276 return ResultTy;
4277
4278 if (getLangOptions().CPlusPlus) {
4279 // C++ [expr.rel]p2:
4280 // [...] Pointer conversions (4.10) and qualification
4281 // conversions (4.4) are performed on pointer operands (or on
4282 // a pointer operand and a null pointer constant) to bring
4283 // them to their composite pointer type. [...]
4284 //
4285 // C++ [expr.eq]p2 uses the same notion for (in)equality
4286 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004287 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004288 if (T.isNull()) {
4289 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4290 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4291 return QualType();
4292 }
4293
4294 ImpCastExprToType(lex, T);
4295 ImpCastExprToType(rex, T);
4296 return ResultTy;
4297 }
4298
Steve Naroff3b435622007-11-13 14:57:38 +00004299 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004300 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4301 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Steve Naroff329ec222009-07-10 23:34:53 +00004302 RCanPointeeTy.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004303 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004304 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004305 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004306 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004307 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004308 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004309 // C++ allows comparison of pointers with null pointer constants.
4310 if (getLangOptions().CPlusPlus) {
4311 if (lType->isPointerType() && RHSIsNull) {
4312 ImpCastExprToType(rex, lType);
4313 return ResultTy;
4314 }
4315 if (rType->isPointerType() && LHSIsNull) {
4316 ImpCastExprToType(lex, rType);
4317 return ResultTy;
4318 }
4319 // And comparison of nullptr_t with itself.
4320 if (lType->isNullPtrType() && rType->isNullPtrType())
4321 return ResultTy;
4322 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004323 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004324 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004325 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4326 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004327
Steve Naroff3454b6c2008-09-04 15:10:53 +00004328 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004329 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004330 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004331 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004332 }
4333 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004334 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004335 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004336 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004337 if (!isRelational
4338 && ((lType->isBlockPointerType() && rType->isPointerType())
4339 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004340 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004341 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004342 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004343 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004344 ->getPointeeType()->isVoidType())))
4345 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4346 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004347 }
4348 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004349 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004350 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004351
Steve Naroff329ec222009-07-10 23:34:53 +00004352 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004353 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004354 const PointerType *LPT = lType->getAs<PointerType>();
4355 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004356 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004357 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004358 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004359 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004360
Steve Naroff030fcda2008-11-17 19:49:16 +00004361 if (!LPtrToVoid && !RPtrToVoid &&
4362 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004363 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004364 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004365 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004366 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004367 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004368 }
Steve Naroff329ec222009-07-10 23:34:53 +00004369 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4370 if (!Context.areComparableObjCPointerTypes(lType, rType)) {
4371 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4372 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4373 }
Steve Naroff936c4362008-06-03 14:04:54 +00004374 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004375 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004376 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004377 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004378 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004379 if (isRelational)
4380 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4381 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4382 else if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004383 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004384 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004385 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004386 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004387 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004388 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004389 if (isRelational)
4390 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4391 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4392 else if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004393 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004394 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004395 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004396 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004397 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004398 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004399 if (!isRelational && RHSIsNull
4400 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004401 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004402 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004403 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004404 if (!isRelational && LHSIsNull
4405 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004406 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004407 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004408 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004409 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004410}
4411
Nate Begemanc5f0f652008-07-14 18:02:46 +00004412/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004413/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004414/// like a scalar comparison, a vector comparison produces a vector of integer
4415/// types.
4416QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004417 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004418 bool isRelational) {
4419 // Check to make sure we're operating on vectors of the same type and width,
4420 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004421 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004422 if (vType.isNull())
4423 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004424
Nate Begemanc5f0f652008-07-14 18:02:46 +00004425 QualType lType = lex->getType();
4426 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004427
Nate Begemanc5f0f652008-07-14 18:02:46 +00004428 // For non-floating point types, check for self-comparisons of the form
4429 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4430 // often indicate logic errors in the program.
4431 if (!lType->isFloatingType()) {
4432 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4433 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4434 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004435 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004436 }
Mike Stump9afab102009-02-19 03:04:26 +00004437
Nate Begemanc5f0f652008-07-14 18:02:46 +00004438 // Check for comparisons of floating point operands using != and ==.
4439 if (!isRelational && lType->isFloatingType()) {
4440 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004441 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004442 }
Mike Stump9afab102009-02-19 03:04:26 +00004443
Nate Begemanc5f0f652008-07-14 18:02:46 +00004444 // Return the type for the comparison, which is the same as vector type for
4445 // integer vectors, or an integer type of identical size and number of
4446 // elements for floating point vectors.
4447 if (lType->isIntegerType())
4448 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004449
Nate Begemanc5f0f652008-07-14 18:02:46 +00004450 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004451 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004452 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004453 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004454 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004455 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4456
Mike Stump9afab102009-02-19 03:04:26 +00004457 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004458 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004459 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4460}
4461
Chris Lattner4b009652007-07-25 00:24:17 +00004462inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004463 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004464{
4465 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004466 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004467
Steve Naroff8f708362007-08-24 19:07:16 +00004468 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004469
Chris Lattner4b009652007-07-25 00:24:17 +00004470 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004471 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004472 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004473}
4474
4475inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004476 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004477{
4478 UsualUnaryConversions(lex);
4479 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004480
Eli Friedmanbea3f842008-05-13 20:16:47 +00004481 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004482 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004483 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004484}
4485
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004486/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4487/// is a read-only property; return true if so. A readonly property expression
4488/// depends on various declarations and thus must be treated specially.
4489///
Mike Stump9afab102009-02-19 03:04:26 +00004490static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004491{
4492 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4493 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4494 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4495 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004496 if (const ObjCObjectPointerType *OPT =
4497 BaseType->getAsObjCInterfacePointerType())
4498 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4499 if (S.isPropertyReadonly(PDecl, IFace))
4500 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004501 }
4502 }
4503 return false;
4504}
4505
Chris Lattner4c2642c2008-11-18 01:22:49 +00004506/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4507/// emit an error and return true. If so, return false.
4508static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004509 SourceLocation OrigLoc = Loc;
4510 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4511 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004512 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4513 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004514 if (IsLV == Expr::MLV_Valid)
4515 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004516
Chris Lattner4c2642c2008-11-18 01:22:49 +00004517 unsigned Diag = 0;
4518 bool NeedType = false;
4519 switch (IsLV) { // C99 6.5.16p2
4520 default: assert(0 && "Unknown result from isModifiableLvalue!");
4521 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004522 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004523 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4524 NeedType = true;
4525 break;
Mike Stump9afab102009-02-19 03:04:26 +00004526 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004527 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4528 NeedType = true;
4529 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004530 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004531 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4532 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004533 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004534 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4535 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004536 case Expr::MLV_IncompleteType:
4537 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004538 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004539 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4540 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004541 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004542 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4543 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004544 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004545 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4546 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004547 case Expr::MLV_ReadonlyProperty:
4548 Diag = diag::error_readonly_property_assignment;
4549 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004550 case Expr::MLV_NoSetterProperty:
4551 Diag = diag::error_nosetter_property_assignment;
4552 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004553 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004554
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004555 SourceRange Assign;
4556 if (Loc != OrigLoc)
4557 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004558 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004559 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004560 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004561 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004562 return true;
4563}
4564
4565
4566
4567// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004568QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4569 SourceLocation Loc,
4570 QualType CompoundType) {
4571 // Verify that LHS is a modifiable lvalue, and emit error if not.
4572 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004573 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004574
4575 QualType LHSType = LHS->getType();
4576 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004577
Chris Lattner005ed752008-01-04 18:04:52 +00004578 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004579 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004580 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004581 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004582 // Special case of NSObject attributes on c-style pointer types.
4583 if (ConvTy == IncompatiblePointer &&
4584 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004585 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004586 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004587 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004588 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004589
Chris Lattner34c85082008-08-21 18:04:13 +00004590 // If the RHS is a unary plus or minus, check to see if they = and + are
4591 // right next to each other. If so, the user may have typo'd "x =+ 4"
4592 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004593 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004594 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4595 RHSCheck = ICE->getSubExpr();
4596 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4597 if ((UO->getOpcode() == UnaryOperator::Plus ||
4598 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004599 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004600 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004601 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4602 // And there is a space or other character before the subexpr of the
4603 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004604 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4605 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004606 Diag(Loc, diag::warn_not_compound_assign)
4607 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4608 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004609 }
Chris Lattner34c85082008-08-21 18:04:13 +00004610 }
4611 } else {
4612 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004613 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004614 }
Chris Lattner005ed752008-01-04 18:04:52 +00004615
Chris Lattner1eafdea2008-11-18 01:30:42 +00004616 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4617 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004618 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004619
Chris Lattner4b009652007-07-25 00:24:17 +00004620 // C99 6.5.16p3: The type of an assignment expression is the type of the
4621 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004622 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004623 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4624 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004625 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004626 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004627 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004628}
4629
Chris Lattner1eafdea2008-11-18 01:30:42 +00004630// C99 6.5.17
4631QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004632 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004633 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004634
4635 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4636 // incomplete in C++).
4637
Chris Lattner1eafdea2008-11-18 01:30:42 +00004638 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004639}
4640
4641/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4642/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004643QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4644 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004645 if (Op->isTypeDependent())
4646 return Context.DependentTy;
4647
Chris Lattnere65182c2008-11-21 07:05:48 +00004648 QualType ResType = Op->getType();
4649 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004650
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004651 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4652 // Decrement of bool is not allowed.
4653 if (!isInc) {
4654 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4655 return QualType();
4656 }
4657 // Increment of bool sets it to true, but is deprecated.
4658 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4659 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004660 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004661 } else if (ResType->isAnyPointerType()) {
4662 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004663
Chris Lattnere65182c2008-11-21 07:05:48 +00004664 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004665 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004666 if (getLangOptions().CPlusPlus) {
4667 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4668 << Op->getSourceRange();
4669 return QualType();
4670 }
4671
4672 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004673 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004674 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004675 if (getLangOptions().CPlusPlus) {
4676 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4677 << Op->getType() << Op->getSourceRange();
4678 return QualType();
4679 }
4680
4681 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004682 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004683 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004684 diag::err_typecheck_arithmetic_incomplete_type,
4685 Op->getSourceRange(), SourceRange(),
4686 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004687 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004688 // Diagnose bad cases where we step over interface counts.
4689 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4690 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4691 << PointeeTy << Op->getSourceRange();
4692 return QualType();
4693 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004694 } else if (ResType->isComplexType()) {
4695 // C99 does not support ++/-- on complex types, we allow as an extension.
4696 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004697 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004698 } else {
4699 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004700 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004701 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004702 }
Mike Stump9afab102009-02-19 03:04:26 +00004703 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004704 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004705 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004706 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004707 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004708}
4709
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004710/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004711/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004712/// where the declaration is needed for type checking. We only need to
4713/// handle cases when the expression references a function designator
4714/// or is an lvalue. Here are some examples:
4715/// - &(x) => x
4716/// - &*****f => f for f a function designator.
4717/// - &s.xx => s
4718/// - &s.zz[1].yy -> s, if zz is an array
4719/// - *(x + 1) -> x, if x is an array
4720/// - &"123"[2] -> 0
4721/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004722static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004723 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004724 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004725 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004726 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004727 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004728 // If this is an arrow operator, the address is an offset from
4729 // the base's value, so the object the base refers to is
4730 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004731 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004732 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004733 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004734 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004735 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004736 // FIXME: This code shouldn't be necessary! We should catch the implicit
4737 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004738 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4739 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4740 if (ICE->getSubExpr()->getType()->isArrayType())
4741 return getPrimaryDecl(ICE->getSubExpr());
4742 }
4743 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004744 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004745 case Stmt::UnaryOperatorClass: {
4746 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004747
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004748 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004749 case UnaryOperator::Real:
4750 case UnaryOperator::Imag:
4751 case UnaryOperator::Extension:
4752 return getPrimaryDecl(UO->getSubExpr());
4753 default:
4754 return 0;
4755 }
4756 }
Chris Lattner4b009652007-07-25 00:24:17 +00004757 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004758 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004759 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004760 // If the result of an implicit cast is an l-value, we care about
4761 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004762 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004763 default:
4764 return 0;
4765 }
4766}
4767
4768/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004769/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004770/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004771/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004772/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004773/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004774/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004775QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004776 // Make sure to ignore parentheses in subsequent checks
4777 op = op->IgnoreParens();
4778
Douglas Gregore6be68a2008-12-17 22:52:20 +00004779 if (op->isTypeDependent())
4780 return Context.DependentTy;
4781
Steve Naroff9c6c3592008-01-13 17:10:08 +00004782 if (getLangOptions().C99) {
4783 // Implement C99-only parts of addressof rules.
4784 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4785 if (uOp->getOpcode() == UnaryOperator::Deref)
4786 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4787 // (assuming the deref expression is valid).
4788 return uOp->getSubExpr()->getType();
4789 }
4790 // Technically, there should be a check for array subscript
4791 // expressions here, but the result of one is always an lvalue anyway.
4792 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004793 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004794 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004795
Eli Friedman14ab4c42009-05-16 23:27:50 +00004796 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4797 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004798 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004799 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004800 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004801 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4802 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004803 return QualType();
4804 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004805 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004806 // The operand cannot be a bit-field
4807 Diag(OpLoc, diag::err_typecheck_address_of)
4808 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004809 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004810 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4811 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004812 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004813 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004814 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004815 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004816 } else if (isa<ObjCPropertyRefExpr>(op)) {
4817 // cannot take address of a property expression.
4818 Diag(OpLoc, diag::err_typecheck_address_of)
4819 << "property expression" << op->getSourceRange();
4820 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004821 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004822 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004823 // with the register storage-class specifier.
4824 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4825 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004826 Diag(OpLoc, diag::err_typecheck_address_of)
4827 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004828 return QualType();
4829 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004830 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4831 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004832 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004833 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004834 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004835 // Could be a pointer to member, though, if there is an explicit
4836 // scope qualifier for the class.
4837 if (isa<QualifiedDeclRefExpr>(op)) {
4838 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004839 if (Ctx && Ctx->isRecord()) {
4840 if (FD->getType()->isReferenceType()) {
4841 Diag(OpLoc,
4842 diag::err_cannot_form_pointer_to_member_of_reference_type)
4843 << FD->getDeclName() << FD->getType();
4844 return QualType();
4845 }
4846
Sebastian Redl0c9da212009-02-03 20:19:35 +00004847 return Context.getMemberPointerType(op->getType(),
4848 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004849 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004850 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004851 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004852 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004853 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004854 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4855 return Context.getMemberPointerType(op->getType(),
4856 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4857 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004858 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004859 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004860
Eli Friedman14ab4c42009-05-16 23:27:50 +00004861 if (lval == Expr::LV_IncompleteVoidType) {
4862 // Taking the address of a void variable is technically illegal, but we
4863 // allow it in cases which are otherwise valid.
4864 // Example: "extern void x; void* y = &x;".
4865 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4866 }
4867
Chris Lattner4b009652007-07-25 00:24:17 +00004868 // If the operand has type "type", the result has type "pointer to type".
4869 return Context.getPointerType(op->getType());
4870}
4871
Chris Lattnerda5c0872008-11-23 09:13:29 +00004872QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004873 if (Op->isTypeDependent())
4874 return Context.DependentTy;
4875
Chris Lattnerda5c0872008-11-23 09:13:29 +00004876 UsualUnaryConversions(Op);
4877 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004878
Chris Lattnerda5c0872008-11-23 09:13:29 +00004879 // Note that per both C89 and C99, this is always legal, even if ptype is an
4880 // incomplete type or void. It would be possible to warn about dereferencing
4881 // a void pointer, but it's completely well-defined, and such a warning is
4882 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004883 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004884 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004885
Steve Naroff329ec222009-07-10 23:34:53 +00004886 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4887 return OPT->getPointeeType();
4888
Chris Lattner77d52da2008-11-20 06:06:08 +00004889 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004890 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004891 return QualType();
4892}
4893
4894static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4895 tok::TokenKind Kind) {
4896 BinaryOperator::Opcode Opc;
4897 switch (Kind) {
4898 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004899 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4900 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004901 case tok::star: Opc = BinaryOperator::Mul; break;
4902 case tok::slash: Opc = BinaryOperator::Div; break;
4903 case tok::percent: Opc = BinaryOperator::Rem; break;
4904 case tok::plus: Opc = BinaryOperator::Add; break;
4905 case tok::minus: Opc = BinaryOperator::Sub; break;
4906 case tok::lessless: Opc = BinaryOperator::Shl; break;
4907 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4908 case tok::lessequal: Opc = BinaryOperator::LE; break;
4909 case tok::less: Opc = BinaryOperator::LT; break;
4910 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4911 case tok::greater: Opc = BinaryOperator::GT; break;
4912 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4913 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4914 case tok::amp: Opc = BinaryOperator::And; break;
4915 case tok::caret: Opc = BinaryOperator::Xor; break;
4916 case tok::pipe: Opc = BinaryOperator::Or; break;
4917 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4918 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4919 case tok::equal: Opc = BinaryOperator::Assign; break;
4920 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4921 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4922 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4923 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4924 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4925 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4926 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4927 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4928 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4929 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4930 case tok::comma: Opc = BinaryOperator::Comma; break;
4931 }
4932 return Opc;
4933}
4934
4935static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4936 tok::TokenKind Kind) {
4937 UnaryOperator::Opcode Opc;
4938 switch (Kind) {
4939 default: assert(0 && "Unknown unary op!");
4940 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4941 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4942 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4943 case tok::star: Opc = UnaryOperator::Deref; break;
4944 case tok::plus: Opc = UnaryOperator::Plus; break;
4945 case tok::minus: Opc = UnaryOperator::Minus; break;
4946 case tok::tilde: Opc = UnaryOperator::Not; break;
4947 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004948 case tok::kw___real: Opc = UnaryOperator::Real; break;
4949 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4950 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4951 }
4952 return Opc;
4953}
4954
Douglas Gregord7f915e2008-11-06 23:29:22 +00004955/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4956/// operator @p Opc at location @c TokLoc. This routine only supports
4957/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004958Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4959 unsigned Op,
4960 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004961 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004962 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004963 // The following two variables are used for compound assignment operators
4964 QualType CompLHSTy; // Type of LHS after promotions for computation
4965 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004966
4967 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004968 case BinaryOperator::Assign:
4969 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4970 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004971 case BinaryOperator::PtrMemD:
4972 case BinaryOperator::PtrMemI:
4973 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4974 Opc == BinaryOperator::PtrMemI);
4975 break;
4976 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004977 case BinaryOperator::Div:
4978 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4979 break;
4980 case BinaryOperator::Rem:
4981 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4982 break;
4983 case BinaryOperator::Add:
4984 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4985 break;
4986 case BinaryOperator::Sub:
4987 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4988 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004989 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004990 case BinaryOperator::Shr:
4991 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4992 break;
4993 case BinaryOperator::LE:
4994 case BinaryOperator::LT:
4995 case BinaryOperator::GE:
4996 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004997 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004998 break;
4999 case BinaryOperator::EQ:
5000 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005001 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005002 break;
5003 case BinaryOperator::And:
5004 case BinaryOperator::Xor:
5005 case BinaryOperator::Or:
5006 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5007 break;
5008 case BinaryOperator::LAnd:
5009 case BinaryOperator::LOr:
5010 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5011 break;
5012 case BinaryOperator::MulAssign:
5013 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005014 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5015 CompLHSTy = CompResultTy;
5016 if (!CompResultTy.isNull())
5017 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005018 break;
5019 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005020 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5021 CompLHSTy = CompResultTy;
5022 if (!CompResultTy.isNull())
5023 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005024 break;
5025 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005026 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5027 if (!CompResultTy.isNull())
5028 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005029 break;
5030 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005031 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5032 if (!CompResultTy.isNull())
5033 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005034 break;
5035 case BinaryOperator::ShlAssign:
5036 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005037 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5038 CompLHSTy = CompResultTy;
5039 if (!CompResultTy.isNull())
5040 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005041 break;
5042 case BinaryOperator::AndAssign:
5043 case BinaryOperator::XorAssign:
5044 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005045 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5046 CompLHSTy = CompResultTy;
5047 if (!CompResultTy.isNull())
5048 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005049 break;
5050 case BinaryOperator::Comma:
5051 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5052 break;
5053 }
5054 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005055 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005056 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005057 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5058 else
5059 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005060 CompLHSTy, CompResultTy,
5061 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005062}
5063
Chris Lattner4b009652007-07-25 00:24:17 +00005064// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005065Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5066 tok::TokenKind Kind,
5067 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005068 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005069 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005070
Steve Naroff87d58b42007-09-16 03:34:24 +00005071 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5072 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005073
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005074 if (getLangOptions().CPlusPlus &&
5075 (lhs->getType()->isOverloadableType() ||
5076 rhs->getType()->isOverloadableType())) {
5077 // Find all of the overloaded operators visible from this
5078 // point. We perform both an operator-name lookup from the local
5079 // scope and an argument-dependent lookup based on the types of
5080 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005081 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005082 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5083 if (OverOp != OO_None) {
5084 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5085 Functions);
5086 Expr *Args[2] = { lhs, rhs };
5087 DeclarationName OpName
5088 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5089 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005090 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005091
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005092 // Build the (potentially-overloaded, potentially-dependent)
5093 // binary operation.
5094 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005095 }
5096
Douglas Gregord7f915e2008-11-06 23:29:22 +00005097 // Build a built-in binary operation.
5098 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005099}
5100
Douglas Gregorc78182d2009-03-13 23:49:33 +00005101Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5102 unsigned OpcIn,
5103 ExprArg InputArg) {
5104 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005105
Mike Stumpe127ae32009-05-16 07:39:55 +00005106 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005107 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005108 QualType resultType;
5109 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005110 case UnaryOperator::OffsetOf:
5111 assert(false && "Invalid unary operator");
5112 break;
5113
Chris Lattner4b009652007-07-25 00:24:17 +00005114 case UnaryOperator::PreInc:
5115 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005116 case UnaryOperator::PostInc:
5117 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005118 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005119 Opc == UnaryOperator::PreInc ||
5120 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005121 break;
Mike Stump9afab102009-02-19 03:04:26 +00005122 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005123 resultType = CheckAddressOfOperand(Input, OpLoc);
5124 break;
Mike Stump9afab102009-02-19 03:04:26 +00005125 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005126 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005127 resultType = CheckIndirectionOperand(Input, OpLoc);
5128 break;
5129 case UnaryOperator::Plus:
5130 case UnaryOperator::Minus:
5131 UsualUnaryConversions(Input);
5132 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005133 if (resultType->isDependentType())
5134 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005135 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5136 break;
5137 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5138 resultType->isEnumeralType())
5139 break;
5140 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5141 Opc == UnaryOperator::Plus &&
5142 resultType->isPointerType())
5143 break;
5144
Sebastian Redl8b769972009-01-19 00:08:26 +00005145 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5146 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005147 case UnaryOperator::Not: // bitwise complement
5148 UsualUnaryConversions(Input);
5149 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005150 if (resultType->isDependentType())
5151 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005152 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5153 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5154 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005155 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005156 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005157 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005158 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5159 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005160 break;
5161 case UnaryOperator::LNot: // logical negation
5162 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5163 DefaultFunctionArrayConversion(Input);
5164 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005165 if (resultType->isDependentType())
5166 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005167 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005168 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5169 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005170 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005171 // In C++, it's bool. C++ 5.3.1p8
5172 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005173 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005174 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005175 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005176 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005177 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005178 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005179 resultType = Input->getType();
5180 break;
5181 }
5182 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005183 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005184
5185 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005186 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005187}
5188
Douglas Gregorc78182d2009-03-13 23:49:33 +00005189// Unary Operators. 'Tok' is the token for the operator.
5190Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5191 tok::TokenKind Op, ExprArg input) {
5192 Expr *Input = (Expr*)input.get();
5193 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5194
5195 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5196 // Find all of the overloaded operators visible from this
5197 // point. We perform both an operator-name lookup from the local
5198 // scope and an argument-dependent lookup based on the types of
5199 // the arguments.
5200 FunctionSet Functions;
5201 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5202 if (OverOp != OO_None) {
5203 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5204 Functions);
5205 DeclarationName OpName
5206 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5207 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5208 }
5209
5210 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5211 }
5212
5213 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5214}
5215
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005216/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005217Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5218 SourceLocation LabLoc,
5219 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005220 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005221 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005222
Daniel Dunbar879788d2008-08-04 16:51:22 +00005223 // If we haven't seen this label yet, create a forward reference. It
5224 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005225 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005226 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005227
Chris Lattner4b009652007-07-25 00:24:17 +00005228 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005229 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5230 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005231}
5232
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005233Sema::OwningExprResult
5234Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5235 SourceLocation RPLoc) { // "({..})"
5236 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005237 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5238 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5239
Eli Friedmanbc941e12009-01-24 23:09:00 +00005240 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005241 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005242 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005243
Chris Lattner4b009652007-07-25 00:24:17 +00005244 // FIXME: there are a variety of strange constraints to enforce here, for
5245 // example, it is not possible to goto into a stmt expression apparently.
5246 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005247
Chris Lattner4b009652007-07-25 00:24:17 +00005248 // If there are sub stmts in the compound stmt, take the type of the last one
5249 // as the type of the stmtexpr.
5250 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005251
Chris Lattner200964f2008-07-26 19:51:01 +00005252 if (!Compound->body_empty()) {
5253 Stmt *LastStmt = Compound->body_back();
5254 // If LastStmt is a label, skip down through into the body.
5255 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5256 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005257
Chris Lattner200964f2008-07-26 19:51:01 +00005258 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005259 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005260 }
Mike Stump9afab102009-02-19 03:04:26 +00005261
Eli Friedman2b128322009-03-23 00:24:07 +00005262 // FIXME: Check that expression type is complete/non-abstract; statement
5263 // expressions are not lvalues.
5264
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005265 substmt.release();
5266 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005267}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005268
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005269Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5270 SourceLocation BuiltinLoc,
5271 SourceLocation TypeLoc,
5272 TypeTy *argty,
5273 OffsetOfComponent *CompPtr,
5274 unsigned NumComponents,
5275 SourceLocation RPLoc) {
5276 // FIXME: This function leaks all expressions in the offset components on
5277 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005278 // FIXME: Preserve type source info.
5279 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005280 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005281
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005282 bool Dependent = ArgTy->isDependentType();
5283
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005284 // We must have at least one component that refers to the type, and the first
5285 // one is known to be a field designator. Verify that the ArgTy represents
5286 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005287 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005288 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005289
Eli Friedman2b128322009-03-23 00:24:07 +00005290 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5291 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005292
Eli Friedman342d9432009-02-27 06:44:11 +00005293 // Otherwise, create a null pointer as the base, and iteratively process
5294 // the offsetof designators.
5295 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5296 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005297 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005298 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005299
Chris Lattnerb37522e2007-08-31 21:49:13 +00005300 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5301 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005302 // FIXME: This diagnostic isn't actually visible because the location is in
5303 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005304 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005305 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5306 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005307
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005308 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005309 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005310
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005311 // FIXME: Dependent case loses a lot of information here. And probably
5312 // leaks like a sieve.
5313 for (unsigned i = 0; i != NumComponents; ++i) {
5314 const OffsetOfComponent &OC = CompPtr[i];
5315 if (OC.isBrackets) {
5316 // Offset of an array sub-field. TODO: Should we allow vector elements?
5317 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5318 if (!AT) {
5319 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005320 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5321 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005322 }
5323
5324 // FIXME: C++: Verify that operator[] isn't overloaded.
5325
Eli Friedman342d9432009-02-27 06:44:11 +00005326 // Promote the array so it looks more like a normal array subscript
5327 // expression.
5328 DefaultFunctionArrayConversion(Res);
5329
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005330 // C99 6.5.2.1p1
5331 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005332 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005333 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005334 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005335 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005336 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005337
5338 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5339 OC.LocEnd);
5340 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005341 }
Mike Stump9afab102009-02-19 03:04:26 +00005342
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005343 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005344 if (!RC) {
5345 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005346 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5347 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005348 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005349
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005350 // Get the decl corresponding to this.
5351 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005352 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005353 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005354 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5355 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5356 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005357 DidWarnAboutNonPOD = true;
5358 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005359 }
5360
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005361 FieldDecl *MemberDecl
5362 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5363 LookupMemberName)
5364 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005365 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005366 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005367 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5368 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005369
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005370 // FIXME: C++: Verify that MemberDecl isn't a static field.
5371 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005372 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005373 Res = BuildAnonymousStructUnionMemberReference(
5374 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005375 } else {
5376 // MemberDecl->getType() doesn't get the right qualifiers, but it
5377 // doesn't matter here.
5378 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5379 MemberDecl->getType().getNonReferenceType());
5380 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005381 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005382 }
Mike Stump9afab102009-02-19 03:04:26 +00005383
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005384 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5385 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005386}
5387
5388
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005389Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5390 TypeTy *arg1,TypeTy *arg2,
5391 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005392 // FIXME: Preserve type source info.
5393 QualType argT1 = GetTypeFromParser(arg1);
5394 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005395
Steve Naroff63bad2d2007-08-01 22:05:33 +00005396 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005397
Douglas Gregore6211502009-05-19 22:28:02 +00005398 if (getLangOptions().CPlusPlus) {
5399 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5400 << SourceRange(BuiltinLoc, RPLoc);
5401 return ExprError();
5402 }
5403
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005404 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5405 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005406}
5407
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005408Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5409 ExprArg cond,
5410 ExprArg expr1, ExprArg expr2,
5411 SourceLocation RPLoc) {
5412 Expr *CondExpr = static_cast<Expr*>(cond.get());
5413 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5414 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005415
Steve Naroff93c53012007-08-03 21:21:27 +00005416 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5417
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005418 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005419 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005420 resType = Context.DependentTy;
5421 } else {
5422 // The conditional expression is required to be a constant expression.
5423 llvm::APSInt condEval(32);
5424 SourceLocation ExpLoc;
5425 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005426 return ExprError(Diag(ExpLoc,
5427 diag::err_typecheck_choose_expr_requires_constant)
5428 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005429
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005430 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5431 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5432 }
5433
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005434 cond.release(); expr1.release(); expr2.release();
5435 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5436 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005437}
5438
Steve Naroff52a81c02008-09-03 18:15:37 +00005439//===----------------------------------------------------------------------===//
5440// Clang Extensions.
5441//===----------------------------------------------------------------------===//
5442
5443/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005444void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005445 // Analyze block parameters.
5446 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005447
Steve Naroff52a81c02008-09-03 18:15:37 +00005448 // Add BSI to CurBlock.
5449 BSI->PrevBlockInfo = CurBlock;
5450 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005451
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005452 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005453 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005454 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005455 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005456 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5457 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005458
Steve Naroff52059382008-10-10 01:28:17 +00005459 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005460 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005461}
5462
Mike Stumpc1fddff2009-02-04 22:31:32 +00005463void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005464 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005465
5466 if (ParamInfo.getNumTypeObjects() == 0
5467 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005468 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005469 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5470
Mike Stump458287d2009-04-28 01:10:27 +00005471 if (T->isArrayType()) {
5472 Diag(ParamInfo.getSourceRange().getBegin(),
5473 diag::err_block_returns_array);
5474 return;
5475 }
5476
Mike Stumpc1fddff2009-02-04 22:31:32 +00005477 // The parameter list is optional, if there was none, assume ().
5478 if (!T->isFunctionType())
5479 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5480
5481 CurBlock->hasPrototype = true;
5482 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005483 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005484 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005485 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005486 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005487 // FIXME: remove the attribute.
5488 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005489 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5490
5491 // Do not allow returning a objc interface by-value.
5492 if (RetTy->isObjCInterfaceType()) {
5493 Diag(ParamInfo.getSourceRange().getBegin(),
5494 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5495 return;
5496 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005497 return;
5498 }
5499
Steve Naroff52a81c02008-09-03 18:15:37 +00005500 // Analyze arguments to block.
5501 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5502 "Not a function declarator!");
5503 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005504
Steve Naroff52059382008-10-10 01:28:17 +00005505 CurBlock->hasPrototype = FTI.hasPrototype;
5506 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005507
Steve Naroff52a81c02008-09-03 18:15:37 +00005508 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5509 // no arguments, not a function that takes a single void argument.
5510 if (FTI.hasPrototype &&
5511 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005512 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5513 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005514 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005515 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005516 } else if (FTI.hasPrototype) {
5517 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005518 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005519 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005520 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005521 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005522 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005523 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005524 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005525 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5526 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5527 // If this has an identifier, add it to the scope stack.
5528 if ((*AI)->getIdentifier())
5529 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005530
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005531 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005532 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005533 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005534 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005535 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005536 // FIXME: remove the attribute.
5537 }
5538
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005539 // Analyze the return type.
5540 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5541 QualType RetTy = T->getAsFunctionType()->getResultType();
5542
5543 // Do not allow returning a objc interface by-value.
5544 if (RetTy->isObjCInterfaceType()) {
5545 Diag(ParamInfo.getSourceRange().getBegin(),
5546 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5547 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005548 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005549}
5550
5551/// ActOnBlockError - If there is an error parsing a block, this callback
5552/// is invoked to pop the information about the block from the action impl.
5553void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5554 // Ensure that CurBlock is deleted.
5555 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005556
Chris Lattnere7765e12009-04-19 05:28:12 +00005557 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5558
Steve Naroff52a81c02008-09-03 18:15:37 +00005559 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005560 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005561 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005562 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005563}
5564
5565/// ActOnBlockStmtExpr - This is called when the body of a block statement
5566/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005567Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5568 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005569 // If blocks are disabled, emit an error.
5570 if (!LangOpts.Blocks)
5571 Diag(CaretLoc, diag::err_blocks_disable);
5572
Steve Naroff52a81c02008-09-03 18:15:37 +00005573 // Ensure that CurBlock is deleted.
5574 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005575
Steve Naroff52059382008-10-10 01:28:17 +00005576 PopDeclContext();
5577
Steve Naroff52a81c02008-09-03 18:15:37 +00005578 // Pop off CurBlock, handle nested blocks.
5579 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005580
Steve Naroff52a81c02008-09-03 18:15:37 +00005581 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005582 if (!BSI->ReturnType.isNull())
5583 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005584
Steve Naroff52a81c02008-09-03 18:15:37 +00005585 llvm::SmallVector<QualType, 8> ArgTypes;
5586 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5587 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005588
Mike Stump8e288f42009-07-28 22:04:01 +00005589 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005590 QualType BlockTy;
5591 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005592 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5593 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005594 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005595 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005596 BSI->isVariadic, 0, false, false, 0, 0,
5597 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005598
Eli Friedman2b128322009-03-23 00:24:07 +00005599 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005600 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005601 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005602
Chris Lattnere7765e12009-04-19 05:28:12 +00005603 // If needed, diagnose invalid gotos and switches in the block.
5604 if (CurFunctionNeedsScopeChecking)
5605 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5606 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5607
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005608 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005609 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005610 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5611 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005612}
5613
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005614Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5615 ExprArg expr, TypeTy *type,
5616 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005617 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005618 Expr *E = static_cast<Expr*>(expr.get());
5619 Expr *OrigExpr = E;
5620
Anders Carlsson36760332007-10-15 20:28:48 +00005621 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005622
5623 // Get the va_list type
5624 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005625 if (VaListType->isArrayType()) {
5626 // Deal with implicit array decay; for example, on x86-64,
5627 // va_list is an array, but it's supposed to decay to
5628 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005629 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005630 // Make sure the input expression also decays appropriately.
5631 UsualUnaryConversions(E);
5632 } else {
5633 // Otherwise, the va_list argument must be an l-value because
5634 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005635 if (!E->isTypeDependent() &&
5636 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005637 return ExprError();
5638 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005639
Douglas Gregor25990972009-05-19 23:10:31 +00005640 if (!E->isTypeDependent() &&
5641 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005642 return ExprError(Diag(E->getLocStart(),
5643 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005644 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005645 }
Mike Stump9afab102009-02-19 03:04:26 +00005646
Eli Friedman2b128322009-03-23 00:24:07 +00005647 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005648 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005649
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005650 expr.release();
5651 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5652 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005653}
5654
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005655Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005656 // The type of __null will be int or long, depending on the size of
5657 // pointers on the target.
5658 QualType Ty;
5659 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5660 Ty = Context.IntTy;
5661 else
5662 Ty = Context.LongTy;
5663
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005664 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005665}
5666
Chris Lattner005ed752008-01-04 18:04:52 +00005667bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5668 SourceLocation Loc,
5669 QualType DstType, QualType SrcType,
5670 Expr *SrcExpr, const char *Flavor) {
5671 // Decode the result (notice that AST's are still created for extensions).
5672 bool isInvalid = false;
5673 unsigned DiagKind;
5674 switch (ConvTy) {
5675 default: assert(0 && "Unknown conversion type");
5676 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005677 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005678 DiagKind = diag::ext_typecheck_convert_pointer_int;
5679 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005680 case IntToPointer:
5681 DiagKind = diag::ext_typecheck_convert_int_pointer;
5682 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005683 case IncompatiblePointer:
5684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5685 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005686 case IncompatiblePointerSign:
5687 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5688 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005689 case FunctionVoidPointer:
5690 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5691 break;
5692 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005693 // If the qualifiers lost were because we were applying the
5694 // (deprecated) C++ conversion from a string literal to a char*
5695 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5696 // Ideally, this check would be performed in
5697 // CheckPointerTypesForAssignment. However, that would require a
5698 // bit of refactoring (so that the second argument is an
5699 // expression, rather than a type), which should be done as part
5700 // of a larger effort to fix CheckPointerTypesForAssignment for
5701 // C++ semantics.
5702 if (getLangOptions().CPlusPlus &&
5703 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5704 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005705 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5706 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005707 case IntToBlockPointer:
5708 DiagKind = diag::err_int_to_block_pointer;
5709 break;
5710 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005711 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005712 break;
Steve Naroff19608432008-10-14 22:18:38 +00005713 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005714 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005715 // it can give a more specific diagnostic.
5716 DiagKind = diag::warn_incompatible_qualified_id;
5717 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005718 case IncompatibleVectors:
5719 DiagKind = diag::warn_incompatible_vectors;
5720 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005721 case Incompatible:
5722 DiagKind = diag::err_typecheck_convert_incompatible;
5723 isInvalid = true;
5724 break;
5725 }
Mike Stump9afab102009-02-19 03:04:26 +00005726
Chris Lattner271d4c22008-11-24 05:29:24 +00005727 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5728 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005729 return isInvalid;
5730}
Anders Carlssond5201b92008-11-30 19:50:32 +00005731
Chris Lattnereec8ae22009-04-25 21:59:05 +00005732bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005733 llvm::APSInt ICEResult;
5734 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5735 if (Result)
5736 *Result = ICEResult;
5737 return false;
5738 }
5739
Anders Carlssond5201b92008-11-30 19:50:32 +00005740 Expr::EvalResult EvalResult;
5741
Mike Stump9afab102009-02-19 03:04:26 +00005742 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005743 EvalResult.HasSideEffects) {
5744 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5745
5746 if (EvalResult.Diag) {
5747 // We only show the note if it's not the usual "invalid subexpression"
5748 // or if it's actually in a subexpression.
5749 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5750 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5751 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5752 }
Mike Stump9afab102009-02-19 03:04:26 +00005753
Anders Carlssond5201b92008-11-30 19:50:32 +00005754 return true;
5755 }
5756
Eli Friedmance329412009-04-25 22:26:58 +00005757 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5758 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005759
Eli Friedmance329412009-04-25 22:26:58 +00005760 if (EvalResult.Diag &&
5761 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5762 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005763
Anders Carlssond5201b92008-11-30 19:50:32 +00005764 if (Result)
5765 *Result = EvalResult.Val.getInt();
5766 return false;
5767}
Douglas Gregor98189262009-06-19 23:52:42 +00005768
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005769Sema::ExpressionEvaluationContext
5770Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5771 // Introduce a new set of potentially referenced declarations to the stack.
5772 if (NewContext == PotentiallyPotentiallyEvaluated)
5773 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5774
5775 std::swap(ExprEvalContext, NewContext);
5776 return NewContext;
5777}
5778
5779void
5780Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5781 ExpressionEvaluationContext NewContext) {
5782 ExprEvalContext = NewContext;
5783
5784 if (OldContext == PotentiallyPotentiallyEvaluated) {
5785 // Mark any remaining declarations in the current position of the stack
5786 // as "referenced". If they were not meant to be referenced, semantic
5787 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5788 PotentiallyReferencedDecls RemainingDecls;
5789 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5790 PotentiallyReferencedDeclStack.pop_back();
5791
5792 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5793 IEnd = RemainingDecls.end();
5794 I != IEnd; ++I)
5795 MarkDeclarationReferenced(I->first, I->second);
5796 }
5797}
Douglas Gregor98189262009-06-19 23:52:42 +00005798
5799/// \brief Note that the given declaration was referenced in the source code.
5800///
5801/// This routine should be invoke whenever a given declaration is referenced
5802/// in the source code, and where that reference occurred. If this declaration
5803/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5804/// C99 6.9p3), then the declaration will be marked as used.
5805///
5806/// \param Loc the location where the declaration was referenced.
5807///
5808/// \param D the declaration that has been referenced by the source code.
5809void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5810 assert(D && "No declaration?");
5811
Douglas Gregorcad27f62009-06-22 23:06:13 +00005812 if (D->isUsed())
5813 return;
5814
Douglas Gregor98189262009-06-19 23:52:42 +00005815 // Mark a parameter declaration "used", regardless of whether we're in a
5816 // template or not.
5817 if (isa<ParmVarDecl>(D))
5818 D->setUsed(true);
5819
5820 // Do not mark anything as "used" within a dependent context; wait for
5821 // an instantiation.
5822 if (CurContext->isDependentContext())
5823 return;
5824
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005825 switch (ExprEvalContext) {
5826 case Unevaluated:
5827 // We are in an expression that is not potentially evaluated; do nothing.
5828 return;
5829
5830 case PotentiallyEvaluated:
5831 // We are in a potentially-evaluated expression, so this declaration is
5832 // "used"; handle this below.
5833 break;
5834
5835 case PotentiallyPotentiallyEvaluated:
5836 // We are in an expression that may be potentially evaluated; queue this
5837 // declaration reference until we know whether the expression is
5838 // potentially evaluated.
5839 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5840 return;
5841 }
5842
Douglas Gregor98189262009-06-19 23:52:42 +00005843 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005844 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005845 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005846 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5847 if (!Constructor->isUsed())
5848 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005849 } else if (Constructor->isImplicit() &&
5850 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005851 if (!Constructor->isUsed())
5852 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5853 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005854 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5855 if (Destructor->isImplicit() && !Destructor->isUsed())
5856 DefineImplicitDestructor(Loc, Destructor);
5857
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005858 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5859 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5860 MethodDecl->getOverloadedOperator() == OO_Equal) {
5861 if (!MethodDecl->isUsed())
5862 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5863 }
5864 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005865 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005866 // Implicit instantiation of function templates and member functions of
5867 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005868 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005869 // FIXME: distinguish between implicit instantiations of function
5870 // templates and explicit specializations (the latter don't get
5871 // instantiated, naturally).
5872 if (Function->getInstantiatedFromMemberFunction() ||
5873 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005874 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005875 }
5876
5877
Douglas Gregor98189262009-06-19 23:52:42 +00005878 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005879 Function->setUsed(true);
5880 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005881 }
Douglas Gregor98189262009-06-19 23:52:42 +00005882
5883 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005884 // Implicit instantiation of static data members of class templates.
5885 // FIXME: distinguish between implicit instantiations (which we need to
5886 // actually instantiate) and explicit specializations.
5887 if (Var->isStaticDataMember() &&
5888 Var->getInstantiatedFromStaticDataMember())
5889 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5890
Douglas Gregor98189262009-06-19 23:52:42 +00005891 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00005892
Douglas Gregor98189262009-06-19 23:52:42 +00005893 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00005894 return;
5895}
Douglas Gregor98189262009-06-19 23:52:42 +00005896}
5897