blob: c01097e363c11707ed951962c416d53f548aa07d [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"
Anders Carlssonb5247af2009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
David Chisnall44663db2009-08-17 16:35:33 +000030
Douglas Gregoraa57e862009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000048 bool isSilenced = false;
49
50 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000054
55 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000066 }
67 }
68 }
69
70 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000081 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregoraa57e862009-02-18 21:56:37 +000089 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian180f3412009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97 Expr **Args, unsigned NumArgs)
98{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000099 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000100 if (!attr)
101 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000102 int sentinelPos = attr->getSentinel();
103 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000104
Mike Stumpe127ae32009-05-16 07:39:55 +0000105 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
106 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000107 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000108 bool warnNotEnoughArgs = false;
109 int isMethod = 0;
110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = MD->param_end();
113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
120 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000121 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000131 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000132 // block or function pointer call.
133 QualType Ty = V->getType();
134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000136 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
137 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139 unsigned NumArgsInProto = Proto->getNumArgs();
140 unsigned k;
141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148 }
149 if (Ty->isBlockPointerType())
150 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000151 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000152 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000153 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000154 return;
155
156 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000157 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000159 return;
160 }
161 int sentinel = i;
162 while (sentinelPos > 0 && i < NumArgs-1) {
163 --sentinelPos;
164 ++i;
165 }
166 if (sentinelPos > 0) {
167 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000168 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000169 return;
170 }
171 while (i < NumArgs-1) {
172 ++i;
173 ++sentinel;
174 }
175 Expr *sentinelExpr = Args[sentinel];
176 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
177 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000178 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000180 }
181 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000182}
183
Douglas Gregor3bb30002009-02-26 21:00:50 +0000184SourceRange Sema::getExprRange(ExprTy *E) const {
185 Expr *Ex = (Expr *)E;
186 return Ex? Ex->getSourceRange() : SourceRange();
187}
188
Chris Lattner299b8842008-07-25 21:10:04 +0000189//===----------------------------------------------------------------------===//
190// Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
Chris Lattner299b8842008-07-25 21:10:04 +0000193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195 QualType Ty = E->getType();
196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
Chris Lattner299b8842008-07-25 21:10:04 +0000198 if (Ty->isFunctionType())
Anders Carlssonb6feaf32009-09-01 20:37:18 +0000199 ImpCastExprToType(E, Context.getPointerType(Ty),
200 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000201 else if (Ty->isArrayType()) {
202 // In C90 mode, arrays only promote to pointers if the array expression is
203 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
204 // type 'array of type' is converted to an expression that has type 'pointer
205 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
206 // that has type 'array of type' ...". The relevant change is "an lvalue"
207 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000208 //
209 // C++ 4.2p1:
210 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
211 // T" can be converted to an rvalue of type "pointer to T".
212 //
213 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
214 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000215 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
216 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000217 }
Chris Lattner299b8842008-07-25 21:10:04 +0000218}
219
220/// UsualUnaryConversions - Performs various conversions that are common to most
221/// operators (C99 6.3). The conversions of array and function types are
222/// sometimes surpressed. For example, the array->pointer conversion doesn't
223/// apply if the array is an argument to the sizeof or address (&) operators.
224/// In these instances, this routine should *not* be called.
225Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
226 QualType Ty = Expr->getType();
227 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
228
Douglas Gregor70b307e2009-05-01 20:41:21 +0000229 // C99 6.3.1.1p2:
230 //
231 // The following may be used in an expression wherever an int or
232 // unsigned int may be used:
233 // - an object or expression with an integer type whose integer
234 // conversion rank is less than or equal to the rank of int
235 // and unsigned int.
236 // - A bit-field of type _Bool, int, signed int, or unsigned int.
237 //
238 // If an int can represent all values of the original type, the
239 // value is converted to an int; otherwise, it is converted to an
240 // unsigned int. These are called the integer promotions. All
241 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000242 QualType PTy = Context.isPromotableBitField(Expr);
243 if (!PTy.isNull()) {
244 ImpCastExprToType(Expr, PTy);
245 return Expr;
246 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000247 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000248 QualType PT = Context.getPromotedIntegerType(Ty);
249 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000250 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000251 }
252
Douglas Gregor70b307e2009-05-01 20:41:21 +0000253 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000254 return Expr;
255}
256
Chris Lattner9305c3d2008-07-25 22:25:12 +0000257/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
258/// do not have a prototype. Arguments that have type float are promoted to
259/// double. All other argument types are converted by UsualUnaryConversions().
260void Sema::DefaultArgumentPromotion(Expr *&Expr) {
261 QualType Ty = Expr->getType();
262 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
263
264 // If this is a 'float' (CVR qualified or typedef) promote to double.
265 if (const BuiltinType *BT = Ty->getAsBuiltinType())
266 if (BT->getKind() == BuiltinType::Float)
267 return ImpCastExprToType(Expr, Context.DoubleTy);
268
269 UsualUnaryConversions(Expr);
270}
271
Chris Lattner81f00ed2009-04-12 08:11:20 +0000272/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
273/// will warn if the resulting type is not a POD type, and rejects ObjC
274/// interfaces passed by value. This returns true if the argument type is
275/// completely illegal.
276bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000277 DefaultArgumentPromotion(Expr);
278
Chris Lattner81f00ed2009-04-12 08:11:20 +0000279 if (Expr->getType()->isObjCInterfaceType()) {
280 Diag(Expr->getLocStart(),
281 diag::err_cannot_pass_objc_interface_to_vararg)
282 << Expr->getType() << CT;
283 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000284 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000285
286 if (!Expr->getType()->isPODType())
287 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
288 << Expr->getType() << CT;
289
290 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000291}
292
293
Chris Lattner299b8842008-07-25 21:10:04 +0000294/// UsualArithmeticConversions - Performs various conversions that are common to
295/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
296/// routine returns the first non-arithmetic type found. The client is
297/// responsible for emitting appropriate error diagnostics.
298/// FIXME: verify the conversion rules for "complex int" are consistent with
299/// GCC.
300QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
301 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000302 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000303 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000304
305 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000306
Chris Lattner299b8842008-07-25 21:10:04 +0000307 // For conversion purposes, we ignore any qualifiers.
308 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000309 QualType lhs =
310 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
311 QualType rhs =
312 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000313
314 // If both types are identical, no conversion is needed.
315 if (lhs == rhs)
316 return lhs;
317
318 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
319 // The caller can deal with this (e.g. pointer + int).
320 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
321 return lhs;
322
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000323 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000324 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000325 if (!LHSBitfieldPromoteTy.isNull())
326 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000327 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000328 if (!RHSBitfieldPromoteTy.isNull())
329 rhs = RHSBitfieldPromoteTy;
330
Eli Friedman6ae7d112009-08-19 07:44:53 +0000331 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000332 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000333 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000334 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000335 return destType;
336}
337
Chris Lattner299b8842008-07-25 21:10:04 +0000338//===----------------------------------------------------------------------===//
339// Semantic Analysis for various Expression Types
340//===----------------------------------------------------------------------===//
341
342
Steve Naroff87d58b42007-09-16 03:34:24 +0000343/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000344/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
345/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
346/// multiple tokens. However, the common case is that StringToks points to one
347/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000348///
349Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000351 assert(NumStringToks && "Must have at least one string!");
352
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000353 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000354 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000356
357 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
358 for (unsigned i = 0; i != NumStringToks; ++i)
359 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000360
Chris Lattnera6dcce32008-02-11 00:02:17 +0000361 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000362 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000363 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000364
365 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
366 if (getLangOptions().CPlusPlus)
367 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000368
Chris Lattnera6dcce32008-02-11 00:02:17 +0000369 // Get an array type for the string, according to C99 6.4.5. This includes
370 // the nul terminator character as well as the string length for pascal
371 // strings.
372 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000373 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000374 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000375
Chris Lattner4b009652007-07-25 00:24:17 +0000376 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000377 return Owned(StringLiteral::Create(Context, Literal.GetString(),
378 Literal.GetStringLength(),
379 Literal.AnyWide, StrTy,
380 &StringTokLocs[0],
381 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000382}
383
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000384/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
385/// CurBlock to VD should cause it to be snapshotted (as we do for auto
386/// variables defined outside the block) or false if this is not needed (e.g.
387/// for values inside the block or for globals).
388///
Chris Lattner0b464252009-04-21 22:26:47 +0000389/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
390/// up-to-date.
391///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000392static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
393 ValueDecl *VD) {
394 // If the value is defined inside the block, we couldn't snapshot it even if
395 // we wanted to.
396 if (CurBlock->TheDecl == VD->getDeclContext())
397 return false;
398
399 // If this is an enum constant or function, it is constant, don't snapshot.
400 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
401 return false;
402
403 // If this is a reference to an extern, static, or global variable, no need to
404 // snapshot it.
405 // FIXME: What about 'const' variables in C++?
406 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000407 if (!Var->hasLocalStorage())
408 return false;
409
410 // Blocks that have these can't be constant.
411 CurBlock->hasBlockDeclRefExprs = true;
412
413 // If we have nested blocks, the decl may be declared in an outer block (in
414 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
415 // be defined outside all of the current blocks (in which case the blocks do
416 // all get the bit). Walk the nesting chain.
417 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
418 NextBlock = NextBlock->PrevBlockInfo) {
419 // If we found the defining block for the variable, don't mark the block as
420 // having a reference outside it.
421 if (NextBlock->TheDecl == VD->getDeclContext())
422 break;
423
424 // Otherwise, the DeclRef from the inner block causes the outer one to need
425 // a snapshot as well.
426 NextBlock->hasBlockDeclRefExprs = true;
427 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000428
429 return true;
430}
431
432
433
Steve Naroff0acc9c92007-09-15 18:49:24 +0000434/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000435/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000436/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000437/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000438/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000439Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
440 IdentifierInfo &II,
441 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000442 const CXXScopeSpec *SS,
443 bool isAddressOfOperand) {
444 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000445 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000446}
447
Douglas Gregor566782a2009-01-06 05:10:23 +0000448/// BuildDeclRefExpr - Build either a DeclRefExpr or a
449/// QualifiedDeclRefExpr based on whether or not SS is a
450/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000451Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000452Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
453 bool TypeDependent, bool ValueDependent,
454 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000455 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
456 Diag(Loc,
457 diag::err_auto_variable_cannot_appear_in_own_initializer)
458 << D->getDeclName();
459 return ExprError();
460 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000461
462 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
463 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
465 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
466 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
467 << D->getIdentifier() << FD->getDeclName();
468 Diag(D->getLocation(), diag::note_local_variable_declared_here)
469 << D->getIdentifier();
470 return ExprError();
471 }
472 }
473 }
474 }
475
Douglas Gregor98189262009-06-19 23:52:42 +0000476 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000477
478 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000479 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000480 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
481 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000482 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000483 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000484 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
485
486 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000487}
488
Douglas Gregor723d3332009-01-07 00:43:41 +0000489/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
490/// variable corresponding to the anonymous union or struct whose type
491/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000492static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
493 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000494 assert(Record->isAnonymousStructOrUnion() &&
495 "Record must be an anonymous struct or union!");
496
Mike Stumpe127ae32009-05-16 07:39:55 +0000497 // FIXME: Once Decls are directly linked together, this will be an O(1)
498 // operation rather than a slow walk through DeclContext's vector (which
499 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000500 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000501 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
502 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000503 D != DEnd; ++D) {
504 if (*D == Record) {
505 // The object for the anonymous struct/union directly
506 // follows its type in the list of declarations.
507 ++D;
508 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000509 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000510 return *D;
511 }
512 }
513
514 assert(false && "Missing object for anonymous record");
515 return 0;
516}
517
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000518/// \brief Given a field that represents a member of an anonymous
519/// struct/union, build the path from that field's context to the
520/// actual member.
521///
522/// Construct the sequence of field member references we'll have to
523/// perform to get to the field in the anonymous union/struct. The
524/// list of members is built from the field outward, so traverse it
525/// backwards to go from an object in the current context to the field
526/// we found.
527///
528/// \returns The variable from which the field access should begin,
529/// for an anonymous struct/union that is not a member of another
530/// class. Otherwise, returns NULL.
531VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
532 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000533 assert(Field->getDeclContext()->isRecord() &&
534 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
535 && "Field must be stored inside an anonymous struct or union");
536
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000537 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000538 VarDecl *BaseObject = 0;
539 DeclContext *Ctx = Field->getDeclContext();
540 do {
541 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000542 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000544 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000545 else {
546 BaseObject = cast<VarDecl>(AnonObject);
547 break;
548 }
549 Ctx = Ctx->getParent();
550 } while (Ctx->isRecord() &&
551 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000552
553 return BaseObject;
554}
555
556Sema::OwningExprResult
557Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
558 FieldDecl *Field,
559 Expr *BaseObjectExpr,
560 SourceLocation OpLoc) {
561 llvm::SmallVector<FieldDecl *, 4> AnonFields;
562 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
563 AnonFields);
564
Douglas Gregor723d3332009-01-07 00:43:41 +0000565 // Build the expression that refers to the base object, from
566 // which we will build a sequence of member references to each
567 // of the anonymous union objects and, eventually, the field we
568 // found via name lookup.
569 bool BaseObjectIsPointer = false;
570 unsigned ExtraQuals = 0;
571 if (BaseObject) {
572 // BaseObject is an anonymous struct/union variable (and is,
573 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000574 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000575 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000576 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000577 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000578 ExtraQuals
579 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
580 } else if (BaseObjectExpr) {
581 // The caller provided the base object expression. Determine
582 // whether its a pointer and whether it adds any qualifiers to the
583 // anonymous struct/union fields we're looking into.
584 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000585 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000586 BaseObjectIsPointer = true;
587 ObjectType = ObjectPtr->getPointeeType();
588 }
589 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
590 } else {
591 // We've found a member of an anonymous struct/union that is
592 // inside a non-anonymous struct/union, so in a well-formed
593 // program our base object expression is "this".
594 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
595 if (!MD->isStatic()) {
596 QualType AnonFieldType
597 = Context.getTagDeclType(
598 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
599 QualType ThisType = Context.getTagDeclType(MD->getParent());
600 if ((Context.getCanonicalType(AnonFieldType)
601 == Context.getCanonicalType(ThisType)) ||
602 IsDerivedFrom(ThisType, AnonFieldType)) {
603 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000604 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000605 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000606 BaseObjectIsPointer = true;
607 }
608 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
610 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000611 }
612 ExtraQuals = MD->getTypeQualifiers();
613 }
614
615 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
617 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000618 }
619
620 // Build the implicit member references to the field of the
621 // anonymous struct/union.
622 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000623 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000624 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
625 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
626 FI != FIEnd; ++FI) {
627 QualType MemberType = (*FI)->getType();
628 if (!(*FI)->isMutable()) {
629 unsigned combinedQualifiers
630 = MemberType.getCVRQualifiers() | ExtraQuals;
631 MemberType = MemberType.getQualifiedType(combinedQualifiers);
632 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000633 if (BaseAddrSpace != MemberType.getAddressSpace())
634 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000635 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000636 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000637 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
638 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000639 BaseObjectIsPointer = false;
640 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000641 }
642
Sebastian Redlcd883f72009-01-18 18:53:16 +0000643 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000644}
645
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000646/// ActOnDeclarationNameExpr - The parser has read some kind of name
647/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
648/// performs lookup on that name and returns an expression that refers
649/// to that name. This routine isn't directly called from the parser,
650/// because the parser doesn't know about DeclarationName. Rather,
651/// this routine is called by ActOnIdentifierExpr,
652/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
653/// which form the DeclarationName from the corresponding syntactic
654/// forms.
655///
656/// HasTrailingLParen indicates whether this identifier is used in a
657/// function call context. LookupCtx is only used for a C++
658/// qualified-id (foo::bar) to indicate the class or namespace that
659/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000660///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000661/// isAddressOfOperand means that this expression is the direct operand
662/// of an address-of operator. This matters because this is the only
663/// situation where a qualified name referencing a non-static member may
664/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000665Sema::OwningExprResult
666Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
667 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000668 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000669 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000670 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000671 if (SS && SS->isInvalid())
672 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000673
674 // C++ [temp.dep.expr]p3:
675 // An id-expression is type-dependent if it contains:
676 // -- a nested-name-specifier that contains a class-name that
677 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000678 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000679 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000680 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
681 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000682 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
683 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000684 }
685
Douglas Gregor411889e2009-02-13 23:20:09 +0000686 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
687 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000688
Sebastian Redlcd883f72009-01-18 18:53:16 +0000689 if (Lookup.isAmbiguous()) {
690 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
691 SS && SS->isSet() ? SS->getRange()
692 : SourceRange());
693 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000694 }
695
696 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000697
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000698 // If this reference is in an Objective-C method, then ivar lookup happens as
699 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000700 IdentifierInfo *II = Name.getAsIdentifierInfo();
701 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000702 // There are two cases to handle here. 1) scoped lookup could have failed,
703 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000704 // found a decl, but that decl is outside the current instance method (i.e.
705 // a global variable). In these two cases, we do a lookup for an ivar with
706 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000707 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000708 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000709 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000710 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000711 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000712 if (DiagnoseUseOfDecl(IV, Loc))
713 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000714
715 // If we're referencing an invalid decl, just return this as a silent
716 // error node. The error diagnostic was already emitted on the decl.
717 if (IV->isInvalidDecl())
718 return ExprError();
719
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000720 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
721 // If a class method attemps to use a free standing ivar, this is
722 // an error.
723 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
724 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
725 << IV->getDeclName());
726 // If a class method uses a global variable, even if an ivar with
727 // same name exists, use the global.
728 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000729 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
730 ClassDeclared != IFace)
731 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000732 // FIXME: This should use a new expr for a direct reference, don't
733 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000734 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000735 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
736 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000737 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000738 return Owned(new (Context)
739 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000740 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000741 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000742 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000743 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000744 // We should warn if a local variable hides an ivar.
745 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000746 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000747 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000748 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
749 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000750 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000751 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000752 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000753 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000754 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000755 QualType T;
756
757 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000758 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
759 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000760 else
761 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000762 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000763 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000764 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000765
Douglas Gregoraa57e862009-02-18 21:56:37 +0000766 // Determine whether this name might be a candidate for
767 // argument-dependent lookup.
768 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
769 HasTrailingLParen;
770
771 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000772 // We've seen something of the form
773 //
774 // identifier(
775 //
776 // and we did not find any entity by the name
777 // "identifier". However, this identifier is still subject to
778 // argument-dependent lookup, so keep track of the name.
779 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
780 Context.OverloadTy,
781 Loc));
782 }
783
Chris Lattner4b009652007-07-25 00:24:17 +0000784 if (D == 0) {
785 // Otherwise, this could be an implicitly declared function reference (legal
786 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000787 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000788 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000789 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000790 else {
791 // If this name wasn't predeclared and if this is not a function call,
792 // diagnose the problem.
Anders Carlsson4355a392009-08-30 00:54:35 +0000793 if (SS && !SS->isEmpty()) {
794 DiagnoseMissingMember(Loc, Name,
795 (NestedNameSpecifier *)SS->getScopeRep(),
796 SS->getRange());
797 return ExprError();
798 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000799 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_use)
801 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000802 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000803 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000804 }
805 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000806
807 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
808 // Warn about constructs like:
809 // if (void *X = foo()) { ... } else { X }.
810 // In the else block, the pointer is always false.
811
812 // FIXME: In a template instantiation, we don't have scope
813 // information to check this property.
814 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
815 Scope *CheckS = S;
816 while (CheckS) {
817 if (CheckS->isWithinElse() &&
818 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
819 if (Var->getType()->isBooleanType())
820 ExprError(Diag(Loc, diag::warn_value_always_false)
821 << Var->getDeclName());
822 else
823 ExprError(Diag(Loc, diag::warn_value_always_zero)
824 << Var->getDeclName());
825 break;
826 }
827
828 // Move up one more control parent to check again.
829 CheckS = CheckS->getControlParent();
830 if (CheckS)
831 CheckS = CheckS->getParent();
832 }
833 }
834 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
835 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
836 // C99 DR 316 says that, if a function type comes from a
837 // function definition (without a prototype), that type is only
838 // used for checking compatibility. Therefore, when referencing
839 // the function, we pretend that we don't have the full function
840 // type.
841 if (DiagnoseUseOfDecl(Func, Loc))
842 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000843
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000844 QualType T = Func->getType();
845 QualType NoProtoType = T;
846 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
847 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
848 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
849 }
850 }
851
852 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
853}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000854/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000855bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000856Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
857 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
858 if (CXXRecordDecl *RD =
859 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
860 QualType DestType =
861 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000862 if (DestType->isDependentType() || From->getType()->isDependentType())
863 return false;
864 QualType FromRecordType = From->getType();
865 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000866 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000867 DestType = Context.getPointerType(DestType);
868 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000869 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000870 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
871 CheckDerivedToBaseConversion(FromRecordType,
872 DestRecordType,
873 From->getSourceRange().getBegin(),
874 From->getSourceRange()))
875 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000876 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
877 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000878 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000879 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000880}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000881
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000882/// \brief Build a MemberExpr AST node.
Douglas Gregore399ad42009-08-26 22:36:53 +0000883static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
884 const CXXScopeSpec *SS, NamedDecl *Member,
885 SourceLocation Loc, QualType Ty) {
886 if (SS && SS->isSet())
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000887 return MemberExpr::Create(C, Base, isArrow,
888 (NestedNameSpecifier *)SS->getScopeRep(),
Douglas Gregord33e3282009-09-01 00:37:14 +0000889 SS->getRange(), Member, Loc,
890 // FIXME: Explicit template argument lists
891 false, SourceLocation(), 0, 0, SourceLocation(),
892 Ty);
Douglas Gregore399ad42009-08-26 22:36:53 +0000893
894 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
895}
896
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000897/// \brief Complete semantic analysis for a reference to the given declaration.
898Sema::OwningExprResult
899Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
900 bool HasTrailingLParen,
901 const CXXScopeSpec *SS,
902 bool isAddressOfOperand) {
903 assert(D && "Cannot refer to a NULL declaration");
904 DeclarationName Name = D->getDeclName();
905
Sebastian Redl0c9da212009-02-03 20:19:35 +0000906 // If this is an expression of the form &Class::member, don't build an
907 // implicit member ref, because we want a pointer to the member in general,
908 // not any specific instance's member.
909 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000910 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000911 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000912 QualType DType;
913 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
914 DType = FD->getType().getNonReferenceType();
915 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
916 DType = Method->getType();
917 } else if (isa<OverloadedFunctionDecl>(D)) {
918 DType = Context.OverloadTy;
919 }
920 // Could be an inner type. That's diagnosed below, so ignore it here.
921 if (!DType.isNull()) {
922 // The pointer is type- and value-dependent if it points into something
923 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000924 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000925 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000926 }
927 }
928 }
929
Douglas Gregor723d3332009-01-07 00:43:41 +0000930 // We may have found a field within an anonymous union or struct
931 // (C++ [class.union]).
932 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
933 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
934 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000935
Douglas Gregor3257fb52008-12-22 05:46:06 +0000936 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
937 if (!MD->isStatic()) {
938 // C++ [class.mfct.nonstatic]p2:
939 // [...] if name lookup (3.4.1) resolves the name in the
940 // id-expression to a nonstatic nontype member of class X or of
941 // a base class of X, the id-expression is transformed into a
942 // class member access expression (5.2.5) using (*this) (9.3.2)
943 // as the postfix-expression to the left of the '.' operator.
944 DeclContext *Ctx = 0;
945 QualType MemberType;
946 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
947 Ctx = FD->getDeclContext();
948 MemberType = FD->getType();
949
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000950 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000951 MemberType = RefType->getPointeeType();
952 else if (!FD->isMutable()) {
953 unsigned combinedQualifiers
954 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
955 MemberType = MemberType.getQualifiedType(combinedQualifiers);
956 }
957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
958 if (!Method->isStatic()) {
959 Ctx = Method->getParent();
960 MemberType = Method->getType();
961 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000962 } else if (FunctionTemplateDecl *FunTmpl
963 = dyn_cast<FunctionTemplateDecl>(D)) {
964 if (CXXMethodDecl *Method
965 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
966 if (!Method->isStatic()) {
967 Ctx = Method->getParent();
968 MemberType = Context.OverloadTy;
969 }
970 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000971 } else if (OverloadedFunctionDecl *Ovl
972 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000973 // FIXME: We need an abstraction for iterating over one or more function
974 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000975 for (OverloadedFunctionDecl::function_iterator
976 Func = Ovl->function_begin(),
977 FuncEnd = Ovl->function_end();
978 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000979 CXXMethodDecl *DMethod = 0;
980 if (FunctionTemplateDecl *FunTmpl
981 = dyn_cast<FunctionTemplateDecl>(*Func))
982 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
983 else
984 DMethod = dyn_cast<CXXMethodDecl>(*Func);
985
986 if (DMethod && !DMethod->isStatic()) {
987 Ctx = DMethod->getDeclContext();
988 MemberType = Context.OverloadTy;
989 break;
990 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000991 }
992 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000993
994 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000995 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
996 QualType ThisType = Context.getTagDeclType(MD->getParent());
997 if ((Context.getCanonicalType(CtxType)
998 == Context.getCanonicalType(ThisType)) ||
999 IsDerivedFrom(ThisType, CtxType)) {
1000 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001001 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001002 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001003 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001004 if (PerformObjectMemberConversion(This, D))
1005 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001006 if (DiagnoseUseOfDecl(D, Loc))
1007 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001008 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1009 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001010 }
1011 }
1012 }
1013 }
1014
Douglas Gregor8acb7272008-12-11 16:49:14 +00001015 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1017 if (MD->isStatic())
1018 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001019 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1020 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001021 }
1022
Douglas Gregor3257fb52008-12-22 05:46:06 +00001023 // Any other ways we could have found the field in a well-formed
1024 // program would have been turned into implicit member expressions
1025 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1027 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001028 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001031 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001032 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001034 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001035 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
Steve Naroffd6163f32008-09-05 22:11:13 +00001037 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001038 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001039 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1040 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001041 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001042 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1043 false, false, SS);
Anders Carlsson89908542009-08-29 01:06:32 +00001044 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1045 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1046 /*TypeDependent=*/true,
1047 /*ValueDependent=*/true, SS);
1048
Steve Naroffd6163f32008-09-05 22:11:13 +00001049 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001050
Douglas Gregoraa57e862009-02-18 21:56:37 +00001051 // Check whether this declaration can be used. Note that we suppress
1052 // this check when we're going to perform argument-dependent lookup
1053 // on this function name, because this might not be the function
1054 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001055 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1056 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001057 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1058 return ExprError();
1059
Steve Naroffd6163f32008-09-05 22:11:13 +00001060 // Only create DeclRefExpr's for valid Decl's.
1061 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062 return ExprError();
1063
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001064 // If the identifier reference is inside a block, and it refers to a value
1065 // that is outside the block, create a BlockDeclRefExpr instead of a
1066 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1067 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001068 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001069 // We do not do this for things like enum constants, global variables, etc,
1070 // as they do not get snapshotted.
1071 //
1072 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001073 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001074 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001075 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001076 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001077 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001078 // This is to record that a 'const' was actually synthesize and added.
1079 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001080 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001081
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001082 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001083 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1084 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001085 }
1086 // If this reference is not in a block or if the referenced variable is
1087 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001088
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001089 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001090 bool ValueDependent = false;
1091 if (getLangOptions().CPlusPlus) {
1092 // C++ [temp.dep.expr]p3:
1093 // An id-expression is type-dependent if it contains:
1094 // - an identifier that was declared with a dependent type,
1095 if (VD->getType()->isDependentType())
1096 TypeDependent = true;
1097 // - FIXME: a template-id that is dependent,
1098 // - a conversion-function-id that specifies a dependent type,
1099 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1100 Name.getCXXNameType()->isDependentType())
1101 TypeDependent = true;
1102 // - a nested-name-specifier that contains a class-name that
1103 // names a dependent type.
1104 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001105 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001106 DC; DC = DC->getParent()) {
1107 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001108 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001109 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1110 if (Context.getTypeDeclType(Record)->isDependentType()) {
1111 TypeDependent = true;
1112 break;
1113 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001114 }
1115 }
1116 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001117
Douglas Gregora5d84612008-12-10 20:57:37 +00001118 // C++ [temp.dep.constexpr]p2:
1119 //
1120 // An identifier is value-dependent if it is:
1121 // - a name declared with a dependent type,
1122 if (TypeDependent)
1123 ValueDependent = true;
1124 // - the name of a non-type template parameter,
1125 else if (isa<NonTypeTemplateParmDecl>(VD))
1126 ValueDependent = true;
1127 // - a constant with integral or enumeration type and is
1128 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001129 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1130 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1131 Dcl->getInit()) {
1132 ValueDependent = Dcl->getInit()->isValueDependent();
1133 }
1134 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001135 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001136
Anders Carlsson4571d812009-06-24 00:10:43 +00001137 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1138 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
Sebastian Redlcd883f72009-01-18 18:53:16 +00001141Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1142 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001143 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001144
Chris Lattner4b009652007-07-25 00:24:17 +00001145 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001146 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001147 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1148 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1149 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001151
Chris Lattner7e637512008-01-12 08:14:25 +00001152 // Pre-defined identifiers are of type char[x], where x is the length of the
1153 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001154 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001155 if (FunctionDecl *FD = getCurFunctionDecl())
1156 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001157 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1158 Length = MD->getSynthesizedMethodSize();
1159 else {
1160 Diag(Loc, diag::ext_predef_outside_function);
1161 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1162 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1163 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001164
1165
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001166 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001167 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001168 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001169 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001170}
1171
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001173 llvm::SmallString<16> CharBuffer;
1174 CharBuffer.resize(Tok.getLength());
1175 const char *ThisTokBegin = &CharBuffer[0];
1176 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001177
Chris Lattner4b009652007-07-25 00:24:17 +00001178 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1179 Tok.getLocation(), PP);
1180 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001181 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001182
1183 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1184
Sebastian Redl75324932009-01-20 22:23:13 +00001185 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1186 Literal.isWide(),
1187 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001188}
1189
Sebastian Redlcd883f72009-01-18 18:53:16 +00001190Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1191 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001192 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1193 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001194 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001195 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001196 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001197 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001198 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001199
Chris Lattner4b009652007-07-25 00:24:17 +00001200 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001201 // Add padding so that NumericLiteralParser can overread by one character.
1202 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001203 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001204
Chris Lattner4b009652007-07-25 00:24:17 +00001205 // Get the spelling of the token, which eliminates trigraphs, etc.
1206 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001207
Chris Lattner4b009652007-07-25 00:24:17 +00001208 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1209 Tok.getLocation(), PP);
1210 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001211 return ExprError();
1212
Chris Lattner1de66eb2007-08-26 03:42:43 +00001213 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001214
Chris Lattner1de66eb2007-08-26 03:42:43 +00001215 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001216 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001217 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001218 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001219 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001220 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001221 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001222 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001223
1224 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1225
Ted Kremenekddedbe22007-11-29 00:56:49 +00001226 // isExact will be set by GetFloatValue().
1227 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001228 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1229 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001230
Chris Lattner1de66eb2007-08-26 03:42:43 +00001231 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001232 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001233 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001234 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001235
Neil Booth7421e9c2007-08-29 22:00:19 +00001236 // long long is a C99 feature.
1237 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001238 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001239 Diag(Tok.getLocation(), diag::ext_longlong);
1240
Chris Lattner4b009652007-07-25 00:24:17 +00001241 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001242 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001243
Chris Lattner4b009652007-07-25 00:24:17 +00001244 if (Literal.GetIntegerValue(ResultVal)) {
1245 // If this value didn't fit into uintmax_t, warn and force to ull.
1246 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001247 Ty = Context.UnsignedLongLongTy;
1248 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001249 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001250 } else {
1251 // If this value fits into a ULL, try to figure out what else it fits into
1252 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1255 // be an unsigned int.
1256 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1257
1258 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001259 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001260 if (!Literal.isLong && !Literal.isLongLong) {
1261 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001262 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001263
Chris Lattner4b009652007-07-25 00:24:17 +00001264 // Does it fit in a unsigned int?
1265 if (ResultVal.isIntN(IntSize)) {
1266 // Does it fit in a signed int?
1267 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001268 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001269 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001270 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001271 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Chris Lattner4b009652007-07-25 00:24:17 +00001273 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001274
Chris Lattner4b009652007-07-25 00:24:17 +00001275 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001276 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001277 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001278
Chris Lattner4b009652007-07-25 00:24:17 +00001279 // Does it fit in a unsigned long?
1280 if (ResultVal.isIntN(LongSize)) {
1281 // Does it fit in a signed long?
1282 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001283 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001284 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001285 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001286 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001287 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001288 }
1289
Chris Lattner4b009652007-07-25 00:24:17 +00001290 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001291 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001292 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001293
Chris Lattner4b009652007-07-25 00:24:17 +00001294 // Does it fit in a unsigned long long?
1295 if (ResultVal.isIntN(LongLongSize)) {
1296 // Does it fit in a signed long long?
1297 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001298 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001299 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001300 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001301 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001302 }
1303 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001304
Chris Lattner4b009652007-07-25 00:24:17 +00001305 // If we still couldn't decide a type, we probably have something that
1306 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001307 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001308 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001309 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001310 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001311 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001312
Chris Lattnere4068872008-05-09 05:59:00 +00001313 if (ResultVal.getBitWidth() != Width)
1314 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001315 }
Sebastian Redl75324932009-01-20 22:23:13 +00001316 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001317 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001318
Chris Lattner1de66eb2007-08-26 03:42:43 +00001319 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1320 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001321 Res = new (Context) ImaginaryLiteral(Res,
1322 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001323
1324 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001325}
1326
Sebastian Redlcd883f72009-01-18 18:53:16 +00001327Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1328 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001329 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001330 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001331 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001332}
1333
1334/// The UsualUnaryConversions() function is *not* called by this routine.
1335/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001336bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001337 SourceLocation OpLoc,
1338 const SourceRange &ExprRange,
1339 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001340 if (exprType->isDependentType())
1341 return false;
1342
Chris Lattner4b009652007-07-25 00:24:17 +00001343 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001344 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001345 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001346 if (isSizeof)
1347 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1348 return false;
1349 }
1350
Chris Lattner95933c12009-04-24 00:30:45 +00001351 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001352 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001353 Diag(OpLoc, diag::ext_sizeof_void_type)
1354 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001355 return false;
1356 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001357
Chris Lattner95933c12009-04-24 00:30:45 +00001358 if (RequireCompleteType(OpLoc, exprType,
1359 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001360 PDiag(diag::err_alignof_incomplete_type)
1361 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001362 return true;
1363
1364 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001365 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001366 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001367 << exprType << isSizeof << ExprRange;
1368 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001369 }
1370
Chris Lattner95933c12009-04-24 00:30:45 +00001371 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001372}
1373
Chris Lattner8d9f7962009-01-24 20:17:12 +00001374bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1375 const SourceRange &ExprRange) {
1376 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001377
Chris Lattner8d9f7962009-01-24 20:17:12 +00001378 // alignof decl is always ok.
1379 if (isa<DeclRefExpr>(E))
1380 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001381
1382 // Cannot know anything else if the expression is dependent.
1383 if (E->isTypeDependent())
1384 return false;
1385
Douglas Gregor531434b2009-05-02 02:18:30 +00001386 if (E->getBitField()) {
1387 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1388 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001389 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001390
1391 // Alignment of a field access is always okay, so long as it isn't a
1392 // bit-field.
1393 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001394 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001395 return false;
1396
Chris Lattner8d9f7962009-01-24 20:17:12 +00001397 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1398}
1399
Douglas Gregor396f1142009-03-13 21:01:28 +00001400/// \brief Build a sizeof or alignof expression given a type operand.
1401Action::OwningExprResult
1402Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1403 bool isSizeOf, SourceRange R) {
1404 if (T.isNull())
1405 return ExprError();
1406
1407 if (!T->isDependentType() &&
1408 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1409 return ExprError();
1410
1411 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1412 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1413 Context.getSizeType(), OpLoc,
1414 R.getEnd()));
1415}
1416
1417/// \brief Build a sizeof or alignof expression given an expression
1418/// operand.
1419Action::OwningExprResult
1420Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1421 bool isSizeOf, SourceRange R) {
1422 // Verify that the operand is valid.
1423 bool isInvalid = false;
1424 if (E->isTypeDependent()) {
1425 // Delay type-checking for type-dependent expressions.
1426 } else if (!isSizeOf) {
1427 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001428 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001429 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1430 isInvalid = true;
1431 } else {
1432 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1433 }
1434
1435 if (isInvalid)
1436 return ExprError();
1437
1438 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1439 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1440 Context.getSizeType(), OpLoc,
1441 R.getEnd()));
1442}
1443
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001444/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1445/// the same for @c alignof and @c __alignof
1446/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001447Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001448Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1449 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001450 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001451 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001452
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001453 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001454 // FIXME: Preserve type source info.
1455 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001456 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1457 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001458
Douglas Gregor396f1142009-03-13 21:01:28 +00001459 // Get the end location.
1460 Expr *ArgEx = (Expr *)TyOrEx;
1461 Action::OwningExprResult Result
1462 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1463
1464 if (Result.isInvalid())
1465 DeleteExpr(ArgEx);
1466
1467 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001468}
1469
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001470QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001471 if (V->isTypeDependent())
1472 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001473
Chris Lattnera16e42d2007-08-26 05:39:26 +00001474 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001475 if (const ComplexType *CT = V->getType()->getAsComplexType())
1476 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001477
1478 // Otherwise they pass through real integer and floating point types here.
1479 if (V->getType()->isArithmeticType())
1480 return V->getType();
1481
1482 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001483 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1484 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001485 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001486}
1487
1488
Chris Lattner4b009652007-07-25 00:24:17 +00001489
Sebastian Redl8b769972009-01-19 00:08:26 +00001490Action::OwningExprResult
1491Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1492 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001493 // Since this might be a postfix expression, get rid of ParenListExprs.
1494 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001495 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001496
Chris Lattner4b009652007-07-25 00:24:17 +00001497 UnaryOperator::Opcode Opc;
1498 switch (Kind) {
1499 default: assert(0 && "Unknown unary op!");
1500 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1501 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1502 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001503
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001504 if (getLangOptions().CPlusPlus &&
1505 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1506 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001507 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001508 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1509
1510 // C++ [over.inc]p1:
1511 //
1512 // [...] If the function is a member function with one
1513 // parameter (which shall be of type int) or a non-member
1514 // function with two parameters (the second of which shall be
1515 // of type int), it defines the postfix increment operator ++
1516 // for objects of that type. When the postfix increment is
1517 // called as a result of using the ++ operator, the int
1518 // argument will have value zero.
1519 Expr *Args[2] = {
1520 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001521 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1522 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001523 };
1524
1525 // Build the candidate set for overloading
1526 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001527 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001528
1529 // Perform overload resolution.
1530 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001531 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001532 case OR_Success: {
1533 // We found a built-in operator or an overloaded operator.
1534 FunctionDecl *FnDecl = Best->Function;
1535
1536 if (FnDecl) {
1537 // We matched an overloaded operator. Build a call to that
1538 // operator.
1539
1540 // Convert the arguments.
1541 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1542 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001544 } else {
1545 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001546 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001547 FnDecl->getParamDecl(0)->getType(),
1548 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001549 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001550 }
1551
1552 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001553 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001554 = FnDecl->getType()->getAsFunctionType()->getResultType();
1555 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001556
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001557 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001558 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001559 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001560 UsualUnaryConversions(FnExpr);
1561
Sebastian Redl8b769972009-01-19 00:08:26 +00001562 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001563 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001564 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1565 Args, 2, ResultTy,
1566 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001567 } else {
1568 // We matched a built-in operator. Convert the arguments, then
1569 // break out so that we will build the appropriate built-in
1570 // operator node.
1571 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1572 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001573 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001574
1575 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001576 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001577 }
1578
1579 case OR_No_Viable_Function:
1580 // No viable function; fall through to handling this as a
1581 // built-in operator, which will produce an error message for us.
1582 break;
1583
1584 case OR_Ambiguous:
1585 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1586 << UnaryOperator::getOpcodeStr(Opc)
1587 << Arg->getSourceRange();
1588 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001589 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001590
1591 case OR_Deleted:
1592 Diag(OpLoc, diag::err_ovl_deleted_oper)
1593 << Best->Function->isDeleted()
1594 << UnaryOperator::getOpcodeStr(Opc)
1595 << Arg->getSourceRange();
1596 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1597 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001598 }
1599
1600 // Either we found no viable overloaded operator or we matched a
1601 // built-in operator. In either case, fall through to trying to
1602 // build a built-in operation.
1603 }
1604
Eli Friedman94d30952009-07-22 23:24:42 +00001605 Input.release();
1606 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001607 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001608}
1609
Sebastian Redl8b769972009-01-19 00:08:26 +00001610Action::OwningExprResult
1611Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1612 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001613 // Since this might be a postfix expression, get rid of ParenListExprs.
1614 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1615
Sebastian Redl8b769972009-01-19 00:08:26 +00001616 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1617 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001618
Douglas Gregor80723c52008-11-19 17:17:41 +00001619 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001620 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1621 Base.release();
1622 Idx.release();
1623 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1624 Context.DependentTy, RLoc));
1625 }
1626
1627 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001628 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001629 LHSExp->getType()->isEnumeralType() ||
1630 RHSExp->getType()->isRecordType() ||
1631 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001632 // Add the appropriate overloaded operators (C++ [over.match.oper])
1633 // to the candidate set.
1634 OverloadCandidateSet CandidateSet;
1635 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001636 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1637 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001638
Douglas Gregor80723c52008-11-19 17:17:41 +00001639 // Perform overload resolution.
1640 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001641 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001642 case OR_Success: {
1643 // We found a built-in operator or an overloaded operator.
1644 FunctionDecl *FnDecl = Best->Function;
1645
1646 if (FnDecl) {
1647 // We matched an overloaded operator. Build a call to that
1648 // operator.
1649
1650 // Convert the arguments.
1651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1652 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1653 PerformCopyInitialization(RHSExp,
1654 FnDecl->getParamDecl(0)->getType(),
1655 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001657 } else {
1658 // Convert the arguments.
1659 if (PerformCopyInitialization(LHSExp,
1660 FnDecl->getParamDecl(0)->getType(),
1661 "passing") ||
1662 PerformCopyInitialization(RHSExp,
1663 FnDecl->getParamDecl(1)->getType(),
1664 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001665 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001666 }
1667
1668 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001669 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001670 = FnDecl->getType()->getAsFunctionType()->getResultType();
1671 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001672
Douglas Gregor80723c52008-11-19 17:17:41 +00001673 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001674 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1675 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001676 UsualUnaryConversions(FnExpr);
1677
Sebastian Redl8b769972009-01-19 00:08:26 +00001678 Base.release();
1679 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001680 Args[0] = LHSExp;
1681 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001682 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1683 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001684 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001685 } else {
1686 // We matched a built-in operator. Convert the arguments, then
1687 // break out so that we will build the appropriate built-in
1688 // operator node.
1689 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1690 "passing") ||
1691 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1692 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001694
1695 break;
1696 }
1697 }
1698
1699 case OR_No_Viable_Function:
1700 // No viable function; fall through to handling this as a
1701 // built-in operator, which will produce an error message for us.
1702 break;
1703
1704 case OR_Ambiguous:
1705 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1706 << "[]"
1707 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1708 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001709 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001710
1711 case OR_Deleted:
1712 Diag(LLoc, diag::err_ovl_deleted_oper)
1713 << Best->Function->isDeleted()
1714 << "[]"
1715 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1716 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1717 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001718 }
1719
1720 // Either we found no viable overloaded operator or we matched a
1721 // built-in operator. In either case, fall through to trying to
1722 // build a built-in operation.
1723 }
1724
Chris Lattner4b009652007-07-25 00:24:17 +00001725 // Perform default conversions.
1726 DefaultFunctionArrayConversion(LHSExp);
1727 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001728
Chris Lattner4b009652007-07-25 00:24:17 +00001729 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1730
1731 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001732 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001733 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001734 // and index from the expression types.
1735 Expr *BaseExpr, *IndexExpr;
1736 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001737 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1738 BaseExpr = LHSExp;
1739 IndexExpr = RHSExp;
1740 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001741 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001742 BaseExpr = LHSExp;
1743 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001744 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001745 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001746 // Handle the uncommon case of "123[Ptr]".
1747 BaseExpr = RHSExp;
1748 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001749 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001750 } else if (const ObjCObjectPointerType *PTy =
1751 LHSTy->getAsObjCObjectPointerType()) {
1752 BaseExpr = LHSExp;
1753 IndexExpr = RHSExp;
1754 ResultType = PTy->getPointeeType();
1755 } else if (const ObjCObjectPointerType *PTy =
1756 RHSTy->getAsObjCObjectPointerType()) {
1757 // Handle the uncommon case of "123[Ptr]".
1758 BaseExpr = RHSExp;
1759 IndexExpr = LHSExp;
1760 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001761 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1762 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001763 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001764
Chris Lattner4b009652007-07-25 00:24:17 +00001765 // FIXME: need to deal with const...
1766 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001767 } else if (LHSTy->isArrayType()) {
1768 // If we see an array that wasn't promoted by
1769 // DefaultFunctionArrayConversion, it must be an array that
1770 // wasn't promoted because of the C90 rule that doesn't
1771 // allow promoting non-lvalue arrays. Warn, then
1772 // force the promotion here.
1773 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1774 LHSExp->getSourceRange();
1775 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1776 LHSTy = LHSExp->getType();
1777
1778 BaseExpr = LHSExp;
1779 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001780 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001781 } else if (RHSTy->isArrayType()) {
1782 // Same as previous, except for 123[f().a] case
1783 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1784 RHSExp->getSourceRange();
1785 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1786 RHSTy = RHSExp->getType();
1787
1788 BaseExpr = RHSExp;
1789 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001790 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001791 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001792 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1793 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001794 }
Chris Lattner4b009652007-07-25 00:24:17 +00001795 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001796 if (!(IndexExpr->getType()->isIntegerType() &&
1797 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001798 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1799 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001800
Douglas Gregor05e28f62009-03-24 19:52:54 +00001801 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1802 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1803 // type. Note that Functions are not objects, and that (in C99 parlance)
1804 // incomplete types are not object types.
1805 if (ResultType->isFunctionType()) {
1806 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1807 << ResultType << BaseExpr->getSourceRange();
1808 return ExprError();
1809 }
Chris Lattner95933c12009-04-24 00:30:45 +00001810
Douglas Gregor05e28f62009-03-24 19:52:54 +00001811 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001812 RequireCompleteType(LLoc, ResultType,
1813 PDiag(diag::err_subscript_incomplete_type)
1814 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001815 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001816
1817 // Diagnose bad cases where we step over interface counts.
1818 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1819 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1820 << ResultType << BaseExpr->getSourceRange();
1821 return ExprError();
1822 }
1823
Sebastian Redl8b769972009-01-19 00:08:26 +00001824 Base.release();
1825 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001826 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001827 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001828}
1829
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001830QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001831CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001832 const IdentifierInfo *CompName,
1833 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001834 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001835
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001836 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001837 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001838
Mike Stump9afab102009-02-19 03:04:26 +00001839 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001840 // special names that indicate a subset of exactly half the elements are
1841 // to be selected.
1842 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001843
Nate Begeman1486b502009-01-18 01:47:54 +00001844 // This flag determines whether or not CompName has an 's' char prefix,
1845 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001846 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001847
1848 // Check that we've found one of the special components, or that the component
1849 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001850 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001851 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1852 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001853 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001854 do
1855 compStr++;
1856 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001857 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001858 do
1859 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001860 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001861 }
Nate Begeman1486b502009-01-18 01:47:54 +00001862
Mike Stump9afab102009-02-19 03:04:26 +00001863 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001864 // We didn't get to the end of the string. This means the component names
1865 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001866 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1867 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001868 return QualType();
1869 }
Mike Stump9afab102009-02-19 03:04:26 +00001870
Nate Begeman1486b502009-01-18 01:47:54 +00001871 // Ensure no component accessor exceeds the width of the vector type it
1872 // operates on.
1873 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001874 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001875
1876 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001877 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001878
1879 while (*compStr) {
1880 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1881 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1882 << baseType << SourceRange(CompLoc);
1883 return QualType();
1884 }
1885 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001886 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001887
Nate Begeman1486b502009-01-18 01:47:54 +00001888 // If this is a halving swizzle, verify that the base type has an even
1889 // number of elements.
1890 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001891 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001892 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001893 return QualType();
1894 }
Mike Stump9afab102009-02-19 03:04:26 +00001895
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001896 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001897 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001898 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001899 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001900 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001901 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001902 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001903 if (HexSwizzle)
1904 CompSize--;
1905
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001906 if (CompSize == 1)
1907 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001908
Nate Begemanaf6ed502008-04-18 23:10:10 +00001909 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001910 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001911 // diagostics look bad. We want extended vector types to appear built-in.
1912 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1913 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1914 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001915 }
1916 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001917}
1918
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001919static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001920 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001921 const Selector &Sel,
1922 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001923
Anders Carlsson9935ab92009-08-26 18:25:21 +00001924 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001925 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001926 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001927 return OMD;
1928
1929 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1930 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001931 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1932 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001933 return D;
1934 }
1935 return 0;
1936}
1937
Steve Naroffc75c1a82009-06-17 22:40:22 +00001938static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001939 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001940 const Selector &Sel,
1941 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001942 // Check protocols on qualified interfaces.
1943 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001944 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001945 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001946 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001947 GDecl = PD;
1948 break;
1949 }
1950 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001951 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001952 GDecl = OMD;
1953 break;
1954 }
1955 }
1956 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001957 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001958 E = QIdTy->qual_end(); I != E; ++I) {
1959 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001960 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001961 if (GDecl)
1962 return GDecl;
1963 }
1964 }
1965 return GDecl;
1966}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001967
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001968/// FindMethodInNestedImplementations - Look up a method in current and
1969/// all base class implementations.
1970///
1971ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1972 const ObjCInterfaceDecl *IFace,
1973 const Selector &Sel) {
1974 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001975 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001976 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001977
1978 if (!Method && IFace->getSuperClass())
1979 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1980 return Method;
1981}
Douglas Gregore399ad42009-08-26 22:36:53 +00001982
Anders Carlsson9935ab92009-08-26 18:25:21 +00001983Action::OwningExprResult
1984Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001985 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001986 DeclarationName MemberName,
Douglas Gregord33e3282009-09-01 00:37:14 +00001987 bool HasExplicitTemplateArgs,
1988 SourceLocation LAngleLoc,
1989 const TemplateArgument *ExplicitTemplateArgs,
1990 unsigned NumExplicitTemplateArgs,
1991 SourceLocation RAngleLoc,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001992 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001993 if (SS && SS->isInvalid())
1994 return ExprError();
1995
Nate Begemane85f43d2009-08-10 23:49:36 +00001996 // Since this might be a postfix expression, get rid of ParenListExprs.
1997 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1998
Anders Carlssonc154a722009-05-01 19:30:39 +00001999 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002000 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002001
Steve Naroff137e11d2007-12-16 21:42:28 +00002002 // Perform default conversions.
2003 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002004
Steve Naroff2cb66382007-07-26 03:11:44 +00002005 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002006 // If this is an Objective-C pseudo-builtin and a definition is provided then
2007 // use that.
2008 if (BaseType->isObjCIdType()) {
2009 // We have an 'id' type. Rather than fall through, we check if this
2010 // is a reference to 'isa'.
2011 if (BaseType != Context.ObjCIdRedefinitionType) {
2012 BaseType = Context.ObjCIdRedefinitionType;
2013 ImpCastExprToType(BaseExpr, BaseType);
2014 }
2015 } else if (BaseType->isObjCClassType() &&
Douglas Gregorcfa0a632009-08-31 21:16:32 +00002016 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall44663db2009-08-17 16:35:33 +00002017 BaseType = Context.ObjCClassRedefinitionType;
2018 ImpCastExprToType(BaseExpr, BaseType);
2019 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002020 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002021
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002022 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2023 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002024 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002025 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002026 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2027 BaseExpr, true,
2028 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002029 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002030 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002031 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002032 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002033 else if (BaseType->isObjCObjectPointerType())
2034 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002035 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002036 return ExprError(Diag(MemberLoc,
2037 diag::err_typecheck_member_reference_arrow)
2038 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002039 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002040 if (BaseType->isDependentType()) {
2041 // Require that the base type isn't a pointer type
2042 // (so we'll report an error for)
2043 // T* t;
2044 // t.f;
2045 //
2046 // In Obj-C++, however, the above expression is valid, since it could be
2047 // accessing the 'f' property if T is an Obj-C interface. The extra check
2048 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002049 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002050
2051 if (!PT || (getLangOptions().ObjC1 &&
2052 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002053 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2054 BaseExpr, false,
2055 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002056 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002057 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002058 }
Chris Lattner4b009652007-07-25 00:24:17 +00002059 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002060
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002061 // Handle field access to simple records. This also handles access to fields
2062 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002063 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002064 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002065 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002066 PDiag(diag::err_typecheck_incomplete_tag)
2067 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002068 return ExprError();
2069
Douglas Gregorda61ad22009-08-06 03:17:00 +00002070 DeclContext *DC = RDecl;
2071 if (SS && SS->isSet()) {
2072 // If the member name was a qualified-id, look into the
2073 // nested-name-specifier.
2074 DC = computeDeclContext(*SS, false);
2075
2076 // FIXME: If DC is not computable, we should build a
2077 // CXXUnresolvedMemberExpr.
2078 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2079 }
2080
Steve Naroff2cb66382007-07-26 03:11:44 +00002081 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002082 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002083 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002084
Douglas Gregor12431cb2009-08-06 05:28:30 +00002085 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002086 QualType BaseTypeCanon
2087 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2088 QualType MemberTypeCanon
2089 = Context.getCanonicalType(
2090 Context.getTypeDeclType(
2091 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2092
2093 if (BaseTypeCanon != MemberTypeCanon &&
2094 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2095 return ExprError(Diag(SS->getBeginLoc(),
2096 diag::err_not_direct_base_or_virtual)
2097 << MemberTypeCanon << BaseTypeCanon);
2098 }
2099
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002100 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002101 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002102 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002103 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002104 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2105 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002106 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002107 }
2108
2109 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002110
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002111 // If the decl being referenced had an error, return an error for this
2112 // sub-expr without emitting another error, in order to avoid cascading
2113 // error cases.
2114 if (MemberDecl->isInvalidDecl())
2115 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002116
Douglas Gregoraa57e862009-02-18 21:56:37 +00002117 // Check the use of this field
2118 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2119 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002120
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002121 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002122 // We may have found a field within an anonymous union or struct
2123 // (C++ [class.union]).
2124 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002125 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002126 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002127
Douglas Gregor82d44772008-12-20 23:49:58 +00002128 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002129 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002130 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002131 MemberType = Ref->getPointeeType();
2132 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002133 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002134 unsigned combinedQualifiers =
2135 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002136 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002137 combinedQualifiers &= ~QualType::Const;
2138 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002139 if (BaseAddrSpace != MemberType.getAddressSpace())
2140 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002141 }
Eli Friedman76b49832008-02-06 22:48:16 +00002142
Douglas Gregorcad27f62009-06-22 23:06:13 +00002143 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002144 if (PerformObjectMemberConversion(BaseExpr, FD))
2145 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002146 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2147 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002148 }
2149
Douglas Gregorcad27f62009-06-22 23:06:13 +00002150 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2151 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002152 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2153 Var, MemberLoc,
2154 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002155 }
2156 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2157 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002158 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2159 MemberFn, MemberLoc,
2160 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002161 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002162 if (FunctionTemplateDecl *FunTmpl
2163 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2164 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregord33e3282009-09-01 00:37:14 +00002165
2166 if (HasExplicitTemplateArgs)
2167 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2168 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2169 SS? SS->getRange() : SourceRange(),
2170 FunTmpl, MemberLoc, true,
2171 LAngleLoc, ExplicitTemplateArgs,
2172 NumExplicitTemplateArgs, RAngleLoc,
2173 Context.OverloadTy));
2174
Douglas Gregore399ad42009-08-26 22:36:53 +00002175 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2176 FunTmpl, MemberLoc,
2177 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002178 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002179 if (OverloadedFunctionDecl *Ovl
Douglas Gregord33e3282009-09-01 00:37:14 +00002180 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2181 if (HasExplicitTemplateArgs)
2182 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2183 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2184 SS? SS->getRange() : SourceRange(),
2185 Ovl, MemberLoc, true,
2186 LAngleLoc, ExplicitTemplateArgs,
2187 NumExplicitTemplateArgs, RAngleLoc,
2188 Context.OverloadTy));
2189
Douglas Gregore399ad42009-08-26 22:36:53 +00002190 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2191 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregord33e3282009-09-01 00:37:14 +00002192 }
Douglas Gregorcad27f62009-06-22 23:06:13 +00002193 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2194 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002195 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2196 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002197 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002198 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002199 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002200 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002201
Douglas Gregor82d44772008-12-20 23:49:58 +00002202 // We found a declaration kind that we didn't expect. This is a
2203 // generic error message that tells the user that she can't refer
2204 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002205 return ExprError(Diag(MemberLoc,
2206 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002207 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002208 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002209
Steve Naroff329ec222009-07-10 23:34:53 +00002210 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002211 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002212 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002213 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2214 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002215 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2216 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2217 ObjCMethodDecl *Getter;
2218 // FIXME: need to also look locally in the implementation.
2219 if ((Getter = IFace->lookupClassMethod(Sel))) {
2220 // Check the use of this method.
2221 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2222 return ExprError();
2223 }
2224 // If we found a getter then this may be a valid dot-reference, we
2225 // will look for the matching setter, in case it is needed.
2226 Selector SetterSel =
2227 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002228 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002229 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2230 if (!Setter) {
2231 // If this reference is in an @implementation, also check for 'private'
2232 // methods.
2233 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2234 }
2235 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002236 if (!Setter)
2237 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002238
2239 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2240 return ExprError();
2241
2242 if (Getter || Setter) {
2243 QualType PType;
2244
2245 if (Getter)
2246 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002247 else
2248 // Get the expression type from Setter's incoming parameter.
2249 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002250 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002251 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002252 Setter, MemberLoc, BaseExpr));
2253 }
2254 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002255 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002256 }
2257 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002258 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2259 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002260 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2261 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2262 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2263 const ObjCInterfaceType *IFaceT =
2264 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002265 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002266 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2267
Steve Naroff4e743962009-07-16 00:25:06 +00002268 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2269 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002270 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002271
2272 if (IV) {
2273 // If the decl being referenced had an error, return an error for this
2274 // sub-expr without emitting another error, in order to avoid cascading
2275 // error cases.
2276 if (IV->isInvalidDecl())
2277 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002278
Steve Naroff4e743962009-07-16 00:25:06 +00002279 // Check whether we can reference this field.
2280 if (DiagnoseUseOfDecl(IV, MemberLoc))
2281 return ExprError();
2282 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2283 IV->getAccessControl() != ObjCIvarDecl::Package) {
2284 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2285 if (ObjCMethodDecl *MD = getCurMethodDecl())
2286 ClassOfMethodDecl = MD->getClassInterface();
2287 else if (ObjCImpDecl && getCurFunctionDecl()) {
2288 // Case of a c-function declared inside an objc implementation.
2289 // FIXME: For a c-style function nested inside an objc implementation
2290 // class, there is no implementation context available, so we pass
2291 // down the context as argument to this routine. Ideally, this context
2292 // need be passed down in the AST node and somehow calculated from the
2293 // AST for a function decl.
2294 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2295 if (ObjCImplementationDecl *IMPD =
2296 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2297 ClassOfMethodDecl = IMPD->getClassInterface();
2298 else if (ObjCCategoryImplDecl* CatImplClass =
2299 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2300 ClassOfMethodDecl = CatImplClass->getClassInterface();
2301 }
2302
2303 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2304 if (ClassDeclared != IDecl ||
2305 ClassOfMethodDecl != ClassDeclared)
2306 Diag(MemberLoc, diag::error_private_ivar_access)
2307 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002308 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2309 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002310 Diag(MemberLoc, diag::error_protected_ivar_access)
2311 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002312 }
Steve Naroff4e743962009-07-16 00:25:06 +00002313
2314 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2315 MemberLoc, BaseExpr,
2316 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002317 }
Steve Naroff4e743962009-07-16 00:25:06 +00002318 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002319 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002320 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002321 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002322 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002323 // Handle properties on 'id' and qualified "id".
2324 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2325 BaseType->isObjCQualifiedIdType())) {
2326 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002327 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002328
Steve Naroff329ec222009-07-10 23:34:53 +00002329 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002330 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002331 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2332 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2333 // Check the use of this declaration
2334 if (DiagnoseUseOfDecl(PD, MemberLoc))
2335 return ExprError();
2336
2337 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2338 MemberLoc, BaseExpr));
2339 }
2340 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2341 // Check the use of this method.
2342 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2343 return ExprError();
2344
2345 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2346 OMD->getResultType(),
2347 OMD, OpLoc, MemberLoc,
2348 NULL, 0));
2349 }
2350 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002351
Steve Naroff329ec222009-07-10 23:34:53 +00002352 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002353 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002354 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002355 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2356 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002357 const ObjCObjectPointerType *OPT;
2358 if (OpKind == tok::period &&
2359 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2360 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2361 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002362 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002363
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002364 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002365 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002366 // Check whether we can reference this property.
2367 if (DiagnoseUseOfDecl(PD, MemberLoc))
2368 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002369 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002370 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002371 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002372 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2373 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002374 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002375 MemberLoc, BaseExpr));
2376 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002377 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002378 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2379 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002380 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002381 // Check whether we can reference this property.
2382 if (DiagnoseUseOfDecl(PD, MemberLoc))
2383 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002384
Steve Naroff774e4152009-01-21 00:14:39 +00002385 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002386 MemberLoc, BaseExpr));
2387 }
Steve Naroff329ec222009-07-10 23:34:53 +00002388 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2389 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002390 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002391 // Check whether we can reference this property.
2392 if (DiagnoseUseOfDecl(PD, MemberLoc))
2393 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002394
Steve Naroff329ec222009-07-10 23:34:53 +00002395 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2396 MemberLoc, BaseExpr));
2397 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002398 // If that failed, look for an "implicit" property by seeing if the nullary
2399 // selector is implemented.
2400
2401 // FIXME: The logic for looking up nullary and unary selectors should be
2402 // shared with the code in ActOnInstanceMessage.
2403
Anders Carlsson9935ab92009-08-26 18:25:21 +00002404 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002405 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002406
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002407 // If this reference is in an @implementation, check for 'private' methods.
2408 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002409 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002410
Steve Naroff04151f32008-10-22 19:16:27 +00002411 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002412 if (!Getter)
2413 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002414 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002415 // Check if we can reference this property.
2416 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2417 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002418 }
2419 // If we found a getter then this may be a valid dot-reference, we
2420 // will look for the matching setter, in case it is needed.
2421 Selector SetterSel =
2422 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002423 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002424 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002425 if (!Setter) {
2426 // If this reference is in an @implementation, also check for 'private'
2427 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002428 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002429 }
2430 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002431 if (!Setter)
2432 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002433
Steve Naroffdede0c92009-03-11 13:48:17 +00002434 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2435 return ExprError();
2436
2437 if (Getter || Setter) {
2438 QualType PType;
2439
2440 if (Getter)
2441 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002442 else
2443 // Get the expression type from Setter's incoming parameter.
2444 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002445 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002446 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002447 Setter, MemberLoc, BaseExpr));
2448 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002449 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002450 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002451 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002452
Steve Naroff29d293b2009-07-24 17:54:45 +00002453 // Handle the following exceptional case (*Obj).isa.
2454 if (OpKind == tok::period &&
2455 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002456 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002457 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2458 Context.getObjCIdType()));
2459
Chris Lattnera57cf472008-07-21 04:28:12 +00002460 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002461 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002462 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002463 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2464 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002465 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002466 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002467 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002468 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002469
Douglas Gregor762da552009-03-27 06:00:30 +00002470 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2471 << BaseType << BaseExpr->getSourceRange();
2472
2473 // If the user is trying to apply -> or . to a function or function
2474 // pointer, it's probably because they forgot parentheses to call
2475 // the function. Suggest the addition of those parentheses.
2476 if (BaseType == Context.OverloadTy ||
2477 BaseType->isFunctionType() ||
2478 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002479 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002480 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2481 Diag(Loc, diag::note_member_reference_needs_call)
2482 << CodeModificationHint::CreateInsertion(Loc, "()");
2483 }
2484
2485 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002486}
2487
Anders Carlsson9935ab92009-08-26 18:25:21 +00002488Action::OwningExprResult
2489Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2490 tok::TokenKind OpKind, SourceLocation MemberLoc,
2491 IdentifierInfo &Member,
2492 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2493 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2494 DeclarationName(&Member), ObjCImpDecl, SS);
2495}
2496
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002497Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2498 FunctionDecl *FD,
2499 ParmVarDecl *Param) {
2500 if (Param->hasUnparsedDefaultArg()) {
2501 Diag (CallLoc,
2502 diag::err_use_of_default_argument_to_function_declared_later) <<
2503 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2504 Diag(UnparsedDefaultArgLocs[Param],
2505 diag::note_default_argument_declared_here);
2506 } else {
2507 if (Param->hasUninstantiatedDefaultArg()) {
2508 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2509
2510 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002511 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002512
2513 // FIXME: We should really make a new InstantiatingTemplate ctor
2514 // that has a better message - right now we're just piggy-backing
2515 // off the "default template argument" error message.
2516 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002517 ArgList.getInnermost().getFlatArgumentList(),
2518 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002519
John McCall0ba26ee2009-08-25 22:02:44 +00002520 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002521 if (Result.isInvalid())
2522 return ExprError();
2523
2524 if (SetParamDefaultArgument(Param, move(Result),
2525 /*FIXME:EqualLoc*/
2526 UninstExpr->getSourceRange().getBegin()))
2527 return ExprError();
2528 }
2529
2530 Expr *DefaultExpr = Param->getDefaultArg();
2531
2532 // If the default expression creates temporaries, we need to
2533 // push them to the current stack of expression temporaries so they'll
2534 // be properly destroyed.
2535 if (CXXExprWithTemporaries *E
2536 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2537 assert(!E->shouldDestroyTemporaries() &&
2538 "Can't destroy temporaries in a default argument expr!");
2539 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2540 ExprTemporaries.push_back(E->getTemporary(I));
2541 }
2542 }
2543
2544 // We already type-checked the argument, so we know it works.
2545 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2546}
2547
Douglas Gregor3257fb52008-12-22 05:46:06 +00002548/// ConvertArgumentsForCall - Converts the arguments specified in
2549/// Args/NumArgs to the parameter types of the function FDecl with
2550/// function prototype Proto. Call is the call expression itself, and
2551/// Fn is the function expression. For a C++ member function, this
2552/// routine does not attempt to convert the object argument. Returns
2553/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002554bool
2555Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002556 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002557 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002558 Expr **Args, unsigned NumArgs,
2559 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002560 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002561 // assignment, to the types of the corresponding parameter, ...
2562 unsigned NumArgsInProto = Proto->getNumArgs();
2563 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002564 bool Invalid = false;
2565
Douglas Gregor3257fb52008-12-22 05:46:06 +00002566 // If too few arguments are available (and we don't have default
2567 // arguments for the remaining parameters), don't make the call.
2568 if (NumArgs < NumArgsInProto) {
2569 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2570 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2571 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2572 // Use default arguments for missing arguments
2573 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002574 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002575 }
2576
2577 // If too many are passed and not variadic, error on the extras and drop
2578 // them.
2579 if (NumArgs > NumArgsInProto) {
2580 if (!Proto->isVariadic()) {
2581 Diag(Args[NumArgsInProto]->getLocStart(),
2582 diag::err_typecheck_call_too_many_args)
2583 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2584 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2585 Args[NumArgs-1]->getLocEnd());
2586 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002587 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002588 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002589 }
2590 NumArgsToCheck = NumArgsInProto;
2591 }
Mike Stump9afab102009-02-19 03:04:26 +00002592
Douglas Gregor3257fb52008-12-22 05:46:06 +00002593 // Continue to check argument types (even if we have too few/many args).
2594 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2595 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002596
Douglas Gregor3257fb52008-12-22 05:46:06 +00002597 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002598 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002599 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002600
Eli Friedman83dec9e2009-03-22 22:00:50 +00002601 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2602 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002603 PDiag(diag::err_call_incomplete_argument)
2604 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002605 return true;
2606
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002607 // Pass the argument.
2608 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2609 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002610 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002611 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002612
2613 OwningExprResult ArgExpr =
2614 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2615 FDecl, Param);
2616 if (ArgExpr.isInvalid())
2617 return true;
2618
2619 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002620 }
2621
Douglas Gregor3257fb52008-12-22 05:46:06 +00002622 Call->setArg(i, Arg);
2623 }
Mike Stump9afab102009-02-19 03:04:26 +00002624
Douglas Gregor3257fb52008-12-22 05:46:06 +00002625 // If this is a variadic call, handle args passed through "...".
2626 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002627 VariadicCallType CallType = VariadicFunction;
2628 if (Fn->getType()->isBlockPointerType())
2629 CallType = VariadicBlock; // Block
2630 else if (isa<MemberExpr>(Fn))
2631 CallType = VariadicMethod;
2632
Douglas Gregor3257fb52008-12-22 05:46:06 +00002633 // Promote the arguments (C99 6.5.2.2p7).
2634 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2635 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002636 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002637 Call->setArg(i, Arg);
2638 }
2639 }
2640
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002641 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002642}
2643
Steve Naroff87d58b42007-09-16 03:34:24 +00002644/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002645/// This provides the location of the left/right parens and a list of comma
2646/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002647Action::OwningExprResult
2648Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2649 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002650 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002651 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002652
2653 // Since this might be a postfix expression, get rid of ParenListExprs.
2654 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2655
Anders Carlssonc154a722009-05-01 19:30:39 +00002656 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002657 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002658 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002659 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002660 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002661 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002662
Douglas Gregor3257fb52008-12-22 05:46:06 +00002663 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002664 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002665 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002666 // FIXME: Will need to cache the results of name lookup (including ADL) in
2667 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002668 bool Dependent = false;
2669 if (Fn->isTypeDependent())
2670 Dependent = true;
2671 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2672 Dependent = true;
2673
2674 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002675 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002676 Context.DependentTy, RParenLoc));
2677
2678 // Determine whether this is a call to an object (C++ [over.call.object]).
2679 if (Fn->getType()->isRecordType())
2680 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2681 CommaLocs, RParenLoc));
2682
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002683 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002684 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2685 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2686 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2687 isa<CXXMethodDecl>(MemDecl) ||
2688 (isa<FunctionTemplateDecl>(MemDecl) &&
2689 isa<CXXMethodDecl>(
2690 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002691 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2692 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002693 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002694 }
2695
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002696 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002697 // Also, in C++, keep track of whether we should perform argument-dependent
2698 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002699 Expr *FnExpr = Fn;
2700 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002701 bool HasExplicitTemplateArgs = 0;
2702 const TemplateArgument *ExplicitTemplateArgs = 0;
2703 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002704 while (true) {
2705 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2706 FnExpr = IcExpr->getSubExpr();
2707 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002708 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002709 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002710 ADL = false;
2711 FnExpr = PExpr->getSubExpr();
2712 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002713 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002714 == UnaryOperator::AddrOf) {
2715 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002716 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002717 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2718 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002719 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002720 break;
Mike Stump9afab102009-02-19 03:04:26 +00002721 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002722 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2723 UnqualifiedName = DepName->getName();
2724 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002725 } else if (TemplateIdRefExpr *TemplateIdRef
2726 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2727 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002728 if (!NDecl)
2729 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002730 HasExplicitTemplateArgs = true;
2731 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2732 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2733
2734 // C++ [temp.arg.explicit]p6:
2735 // [Note: For simple function names, argument dependent lookup (3.4.2)
2736 // applies even when the function name is not visible within the
2737 // scope of the call. This is because the call still has the syntactic
2738 // form of a function call (3.4.1). But when a function template with
2739 // explicit template arguments is used, the call does not have the
2740 // correct syntactic form unless there is a function template with
2741 // that name visible at the point of the call. If no such name is
2742 // visible, the call is not syntactically well-formed and
2743 // argument-dependent lookup does not apply. If some such name is
2744 // visible, argument dependent lookup applies and additional function
2745 // templates may be found in other namespaces.
2746 //
2747 // The summary of this paragraph is that, if we get to this point and the
2748 // template-id was not a qualified name, then argument-dependent lookup
2749 // is still possible.
2750 if (TemplateIdRef->getQualifier())
2751 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002752 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002753 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002754 // Any kind of name that does not refer to a declaration (or
2755 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2756 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002757 break;
2758 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002759 }
Mike Stump9afab102009-02-19 03:04:26 +00002760
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002761 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002762 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002763 if (NDecl) {
2764 FDecl = dyn_cast<FunctionDecl>(NDecl);
2765 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002766 FDecl = FunctionTemplate->getTemplatedDecl();
2767 else
Douglas Gregor28857752009-06-30 22:34:41 +00002768 FDecl = dyn_cast<FunctionDecl>(NDecl);
2769 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002770 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002771
Douglas Gregorb60eb752009-06-25 22:08:12 +00002772 if (Ovl || FunctionTemplate ||
2773 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002774 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002775 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002776 ADL = false;
2777
Douglas Gregorfcb19192009-02-11 23:02:49 +00002778 // We don't perform ADL in C.
2779 if (!getLangOptions().CPlusPlus)
2780 ADL = false;
2781
Douglas Gregorb60eb752009-06-25 22:08:12 +00002782 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002783 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2784 HasExplicitTemplateArgs,
2785 ExplicitTemplateArgs,
2786 NumExplicitTemplateArgs,
2787 LParenLoc, Args, NumArgs, CommaLocs,
2788 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002789 if (!FDecl)
2790 return ExprError();
2791
2792 // Update Fn to refer to the actual function selected.
2793 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002794 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002795 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002796 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2797 QDRExpr->getLocation(),
2798 false, false,
2799 QDRExpr->getQualifierRange(),
2800 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002801 else
Mike Stump9afab102009-02-19 03:04:26 +00002802 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002803 Fn->getSourceRange().getBegin());
2804 Fn->Destroy(Context);
2805 Fn = NewFn;
2806 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002807 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002808
2809 // Promote the function operand.
2810 UsualUnaryConversions(Fn);
2811
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002812 // Make the call expr early, before semantic checks. This guarantees cleanup
2813 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002814 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2815 Args, NumArgs,
2816 Context.BoolTy,
2817 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002818
Steve Naroffd6163f32008-09-05 22:11:13 +00002819 const FunctionType *FuncT;
2820 if (!Fn->getType()->isBlockPointerType()) {
2821 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2822 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002823 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002824 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002825 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2826 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002827 FuncT = PT->getPointeeType()->getAsFunctionType();
2828 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002829 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002830 getAsFunctionType();
2831 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002832 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002833 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2834 << Fn->getType() << Fn->getSourceRange());
2835
Eli Friedman83dec9e2009-03-22 22:00:50 +00002836 // Check for a valid return type
2837 if (!FuncT->getResultType()->isVoidType() &&
2838 RequireCompleteType(Fn->getSourceRange().getBegin(),
2839 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002840 PDiag(diag::err_call_incomplete_return)
2841 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002842 return ExprError();
2843
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002844 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002845 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002846
Douglas Gregor4fa58902009-02-26 23:50:07 +00002847 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002848 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002849 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002850 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002851 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002852 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002853
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002854 if (FDecl) {
2855 // Check if we have too few/too many template arguments, based
2856 // on our knowledge of the function definition.
2857 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002858 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002859 const FunctionProtoType *Proto =
2860 Def->getType()->getAsFunctionProtoType();
2861 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2862 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2863 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2864 }
2865 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002866 }
2867
Steve Naroffdb65e052007-08-28 23:30:39 +00002868 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002869 for (unsigned i = 0; i != NumArgs; i++) {
2870 Expr *Arg = Args[i];
2871 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002872 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2873 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002874 PDiag(diag::err_call_incomplete_argument)
2875 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002876 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002877 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002878 }
Chris Lattner4b009652007-07-25 00:24:17 +00002879 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002880
Douglas Gregor3257fb52008-12-22 05:46:06 +00002881 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2882 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002883 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2884 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002885
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002886 // Check for sentinels
2887 if (NDecl)
2888 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002889
Chris Lattner2e64c072007-08-10 20:18:51 +00002890 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002891 if (FDecl) {
2892 if (CheckFunctionCall(FDecl, TheCall.get()))
2893 return ExprError();
2894
2895 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2896 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2897 } else if (NDecl) {
2898 if (CheckBlockCall(NDecl, TheCall.get()))
2899 return ExprError();
2900 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002901
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002902 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002903}
2904
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002905Action::OwningExprResult
2906Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2907 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002908 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002909 //FIXME: Preserve type source info.
2910 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002911 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002912 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002913 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002914
Eli Friedman8c2173d2008-05-20 05:22:08 +00002915 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002916 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002917 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2918 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002919 } else if (!literalType->isDependentType() &&
2920 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002921 PDiag(diag::err_typecheck_decl_incomplete_type)
2922 << SourceRange(LParenLoc,
2923 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002924 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002925
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002926 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002927 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002928 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002929
Chris Lattnere5cb5862008-12-04 23:50:19 +00002930 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002931 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002932 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002933 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002934 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002935 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002936 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002937 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002938}
2939
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002940Action::OwningExprResult
2941Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002942 SourceLocation RBraceLoc) {
2943 unsigned NumInit = initlist.size();
2944 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002945
Steve Naroff0acc9c92007-09-15 18:49:24 +00002946 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002947 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002948
Mike Stump9afab102009-02-19 03:04:26 +00002949 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002950 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002951 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002952 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002953}
2954
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002955/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002956bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002957 CastExpr::CastKind& Kind,
2958 CXXMethodDecl *& ConversionDecl,
2959 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002960 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002961 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2962 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002963
Eli Friedman01e0f652009-08-15 19:02:19 +00002964 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002965
2966 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2967 // type needs to be scalar.
2968 if (castType->isVoidType()) {
2969 // Cast to void allows any expr type.
2970 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002971 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2972 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2973 (castType->isStructureType() || castType->isUnionType())) {
2974 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002975 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002976 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2977 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002978 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002979 } else if (castType->isUnionType()) {
2980 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002981 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002982 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002983 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002984 Field != FieldEnd; ++Field) {
2985 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2986 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2987 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2988 << castExpr->getSourceRange();
2989 break;
2990 }
2991 }
2992 if (Field == FieldEnd)
2993 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2994 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002995 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002996 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002997 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002998 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002999 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003000 }
Mike Stump9afab102009-02-19 03:04:26 +00003001 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003002 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003003 return Diag(castExpr->getLocStart(),
3004 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003005 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003006 } else if (castType->isExtVectorType()) {
3007 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003008 return true;
3009 } else if (castType->isVectorType()) {
3010 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3011 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003012 } else if (castExpr->getType()->isVectorType()) {
3013 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3014 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003015 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003016 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003017 } else if (!castType->isArithmeticType()) {
3018 QualType castExprType = castExpr->getType();
3019 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3020 return Diag(castExpr->getLocStart(),
3021 diag::err_cast_pointer_from_non_pointer_int)
3022 << castExprType << castExpr->getSourceRange();
3023 } else if (!castExpr->getType()->isArithmeticType()) {
3024 if (!castType->isIntegralType() && castType->isArithmeticType())
3025 return Diag(castExpr->getLocStart(),
3026 diag::err_cast_pointer_to_non_pointer_int)
3027 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003028 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003029 if (isa<ObjCSelectorExpr>(castExpr))
3030 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003031 return false;
3032}
3033
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003034bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003035 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003036
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003037 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003038 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003039 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003040 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003041 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003042 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003043 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003044 } else
3045 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003046 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003047 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003048
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003049 return false;
3050}
3051
Nate Begemanbd42e022009-06-26 00:50:28 +00003052bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3053 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3054
Nate Begeman9e063702009-06-27 22:05:55 +00003055 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3056 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003057 if (SrcTy->isVectorType()) {
3058 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3059 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3060 << DestTy << SrcTy << R;
3061 return false;
3062 }
3063
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003064 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003065 // conversion will take place first from scalar to elt type, and then
3066 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003067 if (SrcTy->isPointerType())
3068 return Diag(R.getBegin(),
3069 diag::err_invalid_conversion_between_vector_and_scalar)
3070 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003071 return false;
3072}
3073
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003074Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003075Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003076 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003077 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3078
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003079 assert((Ty != 0) && (Op.get() != 0) &&
3080 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003081
Nate Begemane85f43d2009-08-10 23:49:36 +00003082 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003083 //FIXME: Preserve type source info.
3084 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003085
3086 // If the Expr being casted is a ParenListExpr, handle it specially.
3087 if (isa<ParenListExpr>(castExpr))
3088 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003089 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003090 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003091 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003092 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003093 if (ConversionDecl) {
3094 // encounterred a c-style cast requiring a conversion function.
3095 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3096 castExpr =
3097 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3098 castType, LParenLoc,
3099 CastExpr::CK_UserDefinedConversion,
3100 castExpr, CD,
3101 RParenLoc);
3102 Kind = CastExpr::CK_UserDefinedConversion;
3103 }
3104 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3105 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003106
3107 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003108 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003109 Kind, castExpr, castType,
3110 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003111}
3112
Nate Begemane85f43d2009-08-10 23:49:36 +00003113/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3114/// of comma binary operators.
3115Action::OwningExprResult
3116Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3117 Expr *expr = EA.takeAs<Expr>();
3118 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3119 if (!E)
3120 return Owned(expr);
3121
3122 OwningExprResult Result(*this, E->getExpr(0));
3123
3124 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3125 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3126 Owned(E->getExpr(i)));
3127
3128 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3129}
3130
3131Action::OwningExprResult
3132Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3133 SourceLocation RParenLoc, ExprArg Op,
3134 QualType Ty) {
3135 ParenListExpr *PE = (ParenListExpr *)Op.get();
3136
3137 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3138 // then handle it as such.
3139 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3140 if (PE->getNumExprs() == 0) {
3141 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3142 return ExprError();
3143 }
3144
3145 llvm::SmallVector<Expr *, 8> initExprs;
3146 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3147 initExprs.push_back(PE->getExpr(i));
3148
3149 // FIXME: This means that pretty-printing the final AST will produce curly
3150 // braces instead of the original commas.
3151 Op.release();
3152 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3153 initExprs.size(), RParenLoc);
3154 E->setType(Ty);
3155 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3156 Owned(E));
3157 } else {
3158 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3159 // sequence of BinOp comma operators.
3160 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3161 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3162 }
3163}
3164
3165Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3166 SourceLocation R,
3167 MultiExprArg Val) {
3168 unsigned nexprs = Val.size();
3169 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3170 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3171 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3172 return Owned(expr);
3173}
3174
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003175/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3176/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003177/// C99 6.5.15
3178QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3179 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003180 // C++ is sufficiently different to merit its own checker.
3181 if (getLangOptions().CPlusPlus)
3182 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3183
Chris Lattnere2897262009-02-18 04:28:32 +00003184 UsualUnaryConversions(Cond);
3185 UsualUnaryConversions(LHS);
3186 UsualUnaryConversions(RHS);
3187 QualType CondTy = Cond->getType();
3188 QualType LHSTy = LHS->getType();
3189 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003190
3191 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003192 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3193 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3194 << CondTy;
3195 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003196 }
Mike Stump9afab102009-02-19 03:04:26 +00003197
Chris Lattner992ae932008-01-06 22:42:25 +00003198 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003199 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3200 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003201
Chris Lattner992ae932008-01-06 22:42:25 +00003202 // If both operands have arithmetic type, do the usual arithmetic conversions
3203 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003204 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3205 UsualArithmeticConversions(LHS, RHS);
3206 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003207 }
Mike Stump9afab102009-02-19 03:04:26 +00003208
Chris Lattner992ae932008-01-06 22:42:25 +00003209 // If both operands are the same structure or union type, the result is that
3210 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003211 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3212 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003213 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003214 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003215 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003216 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003217 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003218 }
Mike Stump9afab102009-02-19 03:04:26 +00003219
Chris Lattner992ae932008-01-06 22:42:25 +00003220 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003221 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003222 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3223 if (!LHSTy->isVoidType())
3224 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3225 << RHS->getSourceRange();
3226 if (!RHSTy->isVoidType())
3227 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3228 << LHS->getSourceRange();
3229 ImpCastExprToType(LHS, Context.VoidTy);
3230 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003231 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003232 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003233 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3234 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003235 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003236 RHS->isNullPointerConstant(Context)) {
3237 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3238 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003239 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003240 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003241 LHS->isNullPointerConstant(Context)) {
3242 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3243 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003244 }
David Chisnall44663db2009-08-17 16:35:33 +00003245 // Handle things like Class and struct objc_class*. Here we case the result
3246 // to the pseudo-builtin, because that will be implicitly cast back to the
3247 // redefinition type if an attempt is made to access its fields.
3248 if (LHSTy->isObjCClassType() &&
3249 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3250 ImpCastExprToType(RHS, LHSTy);
3251 return LHSTy;
3252 }
3253 if (RHSTy->isObjCClassType() &&
3254 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3255 ImpCastExprToType(LHS, RHSTy);
3256 return RHSTy;
3257 }
3258 // And the same for struct objc_object* / id
3259 if (LHSTy->isObjCIdType() &&
3260 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3261 ImpCastExprToType(RHS, LHSTy);
3262 return LHSTy;
3263 }
3264 if (RHSTy->isObjCIdType() &&
3265 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3266 ImpCastExprToType(LHS, RHSTy);
3267 return RHSTy;
3268 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003269 // Handle block pointer types.
3270 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3271 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3272 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3273 QualType destType = Context.getPointerType(Context.VoidTy);
3274 ImpCastExprToType(LHS, destType);
3275 ImpCastExprToType(RHS, destType);
3276 return destType;
3277 }
3278 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3279 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3280 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003281 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003282 // We have 2 block pointer types.
3283 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3284 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003285 return LHSTy;
3286 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003287 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003288 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3289 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003290
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003291 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3292 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003293 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3294 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3295 // In this situation, we assume void* type. No especially good
3296 // reason, but this is what gcc does, and we do have to pick
3297 // to get a consistent AST.
3298 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3299 ImpCastExprToType(LHS, incompatTy);
3300 ImpCastExprToType(RHS, incompatTy);
3301 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003302 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003303 // The block pointer types are compatible.
3304 ImpCastExprToType(LHS, LHSTy);
3305 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003306 return LHSTy;
3307 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003308 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003309 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003310
3311 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3312 // Two identical object pointer types are always compatible.
3313 return LHSTy;
3314 }
Steve Naroff329ec222009-07-10 23:34:53 +00003315 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3316 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003317 QualType compositeType = LHSTy;
3318
3319 // If both operands are interfaces and either operand can be
3320 // assigned to the other, use that type as the composite
3321 // type. This allows
3322 // xxx ? (A*) a : (B*) b
3323 // where B is a subclass of A.
3324 //
3325 // Additionally, as for assignment, if either type is 'id'
3326 // allow silent coercion. Finally, if the types are
3327 // incompatible then make sure to use 'id' as the composite
3328 // type so the result is acceptable for sending messages to.
3329
3330 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3331 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003332 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003333 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003334 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003335 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003336 } else if ((LHSTy->isObjCQualifiedIdType() ||
3337 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003338 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003339 // Need to handle "id<xx>" explicitly.
3340 // GCC allows qualified id and any Objective-C type to devolve to
3341 // id. Currently localizing to here until clear this should be
3342 // part of ObjCQualifiedIdTypesAreCompatible.
3343 compositeType = Context.getObjCIdType();
3344 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003345 compositeType = Context.getObjCIdType();
3346 } else {
3347 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3348 << LHSTy << RHSTy
3349 << LHS->getSourceRange() << RHS->getSourceRange();
3350 QualType incompatTy = Context.getObjCIdType();
3351 ImpCastExprToType(LHS, incompatTy);
3352 ImpCastExprToType(RHS, incompatTy);
3353 return incompatTy;
3354 }
3355 // The object pointer types are compatible.
3356 ImpCastExprToType(LHS, compositeType);
3357 ImpCastExprToType(RHS, compositeType);
3358 return compositeType;
3359 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003360 // Check Objective-C object pointer types and 'void *'
3361 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003362 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003363 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3364 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3365 QualType destType = Context.getPointerType(destPointee);
3366 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3367 ImpCastExprToType(RHS, destType); // promote to void*
3368 return destType;
3369 }
3370 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3371 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003372 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003373 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3374 QualType destType = Context.getPointerType(destPointee);
3375 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3376 ImpCastExprToType(LHS, destType); // promote to void*
3377 return destType;
3378 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003379 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3380 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3381 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003382 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3383 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003384
3385 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3386 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3387 // Figure out necessary qualifiers (C99 6.5.15p6)
3388 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3389 QualType destType = Context.getPointerType(destPointee);
3390 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3391 ImpCastExprToType(RHS, destType); // promote to void*
3392 return destType;
3393 }
3394 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3395 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3396 QualType destType = Context.getPointerType(destPointee);
3397 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3398 ImpCastExprToType(RHS, destType); // promote to void*
3399 return destType;
3400 }
3401
3402 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3403 // Two identical pointer types are always compatible.
3404 return LHSTy;
3405 }
3406 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3407 rhptee.getUnqualifiedType())) {
3408 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3409 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3410 // In this situation, we assume void* type. No especially good
3411 // reason, but this is what gcc does, and we do have to pick
3412 // to get a consistent AST.
3413 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3414 ImpCastExprToType(LHS, incompatTy);
3415 ImpCastExprToType(RHS, incompatTy);
3416 return incompatTy;
3417 }
3418 // The pointer types are compatible.
3419 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3420 // differently qualified versions of compatible types, the result type is
3421 // a pointer to an appropriately qualified version of the *composite*
3422 // type.
3423 // FIXME: Need to calculate the composite type.
3424 // FIXME: Need to add qualifiers
3425 ImpCastExprToType(LHS, LHSTy);
3426 ImpCastExprToType(RHS, LHSTy);
3427 return LHSTy;
3428 }
3429
3430 // GCC compatibility: soften pointer/integer mismatch.
3431 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3432 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3433 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3434 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3435 return RHSTy;
3436 }
3437 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3438 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3439 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3440 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3441 return LHSTy;
3442 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003443
Chris Lattner992ae932008-01-06 22:42:25 +00003444 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003445 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3446 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003447 return QualType();
3448}
3449
Steve Naroff87d58b42007-09-16 03:34:24 +00003450/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003451/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003452Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3453 SourceLocation ColonLoc,
3454 ExprArg Cond, ExprArg LHS,
3455 ExprArg RHS) {
3456 Expr *CondExpr = (Expr *) Cond.get();
3457 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003458
3459 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3460 // was the condition.
3461 bool isLHSNull = LHSExpr == 0;
3462 if (isLHSNull)
3463 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003464
3465 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003466 RHSExpr, QuestionLoc);
3467 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003468 return ExprError();
3469
3470 Cond.release();
3471 LHS.release();
3472 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003473 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003474 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003475 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003476}
3477
Chris Lattner4b009652007-07-25 00:24:17 +00003478// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003479// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003480// routine is it effectively iqnores the qualifiers on the top level pointee.
3481// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3482// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003483Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003484Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3485 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003486
David Chisnall44663db2009-08-17 16:35:33 +00003487 if ((lhsType->isObjCClassType() &&
3488 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3489 (rhsType->isObjCClassType() &&
3490 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3491 return Compatible;
3492 }
3493
Chris Lattner4b009652007-07-25 00:24:17 +00003494 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003495 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3496 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003497
Chris Lattner4b009652007-07-25 00:24:17 +00003498 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003499 lhptee = Context.getCanonicalType(lhptee);
3500 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003501
Chris Lattner005ed752008-01-04 18:04:52 +00003502 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003503
3504 // C99 6.5.16.1p1: This following citation is common to constraints
3505 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3506 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003507 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003508 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003509 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003510
Mike Stump9afab102009-02-19 03:04:26 +00003511 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3512 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003513 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003514 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003515 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003516 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003517
Chris Lattner4ca3d772008-01-03 22:56:36 +00003518 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003519 assert(rhptee->isFunctionType());
3520 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003521 }
Mike Stump9afab102009-02-19 03:04:26 +00003522
Chris Lattner4ca3d772008-01-03 22:56:36 +00003523 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003524 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003525 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003526
3527 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003528 assert(lhptee->isFunctionType());
3529 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003530 }
Mike Stump9afab102009-02-19 03:04:26 +00003531 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003532 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003533 lhptee = lhptee.getUnqualifiedType();
3534 rhptee = rhptee.getUnqualifiedType();
3535 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3536 // Check if the pointee types are compatible ignoring the sign.
3537 // We explicitly check for char so that we catch "char" vs
3538 // "unsigned char" on systems where "char" is unsigned.
3539 if (lhptee->isCharType()) {
3540 lhptee = Context.UnsignedCharTy;
3541 } else if (lhptee->isSignedIntegerType()) {
3542 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3543 }
3544 if (rhptee->isCharType()) {
3545 rhptee = Context.UnsignedCharTy;
3546 } else if (rhptee->isSignedIntegerType()) {
3547 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3548 }
3549 if (lhptee == rhptee) {
3550 // Types are compatible ignoring the sign. Qualifier incompatibility
3551 // takes priority over sign incompatibility because the sign
3552 // warning can be disabled.
3553 if (ConvTy != Compatible)
3554 return ConvTy;
3555 return IncompatiblePointerSign;
3556 }
3557 // General pointer incompatibility takes priority over qualifiers.
3558 return IncompatiblePointer;
3559 }
Chris Lattner005ed752008-01-04 18:04:52 +00003560 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003561}
3562
Steve Naroff3454b6c2008-09-04 15:10:53 +00003563/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3564/// block pointer types are compatible or whether a block and normal pointer
3565/// are compatible. It is more restrict than comparing two function pointer
3566// types.
Mike Stump9afab102009-02-19 03:04:26 +00003567Sema::AssignConvertType
3568Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003569 QualType rhsType) {
3570 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003571
Steve Naroff3454b6c2008-09-04 15:10:53 +00003572 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003573 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3574 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003575
Steve Naroff3454b6c2008-09-04 15:10:53 +00003576 // make sure we operate on the canonical type
3577 lhptee = Context.getCanonicalType(lhptee);
3578 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003579
Steve Naroff3454b6c2008-09-04 15:10:53 +00003580 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003581
Steve Naroff3454b6c2008-09-04 15:10:53 +00003582 // For blocks we enforce that qualifiers are identical.
3583 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3584 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003585
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003586 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003587 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003588 return ConvTy;
3589}
3590
Mike Stump9afab102009-02-19 03:04:26 +00003591/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3592/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003593/// pointers. Here are some objectionable examples that GCC considers warnings:
3594///
3595/// int a, *pint;
3596/// short *pshort;
3597/// struct foo *pfoo;
3598///
3599/// pint = pshort; // warning: assignment from incompatible pointer type
3600/// a = pint; // warning: assignment makes integer from pointer without a cast
3601/// pint = a; // warning: assignment makes pointer from integer without a cast
3602/// pint = pfoo; // warning: assignment from incompatible pointer type
3603///
3604/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003605/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003606///
Chris Lattner005ed752008-01-04 18:04:52 +00003607Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003608Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003609 // Get canonical types. We're not formatting these types, just comparing
3610 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003611 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3612 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003613
3614 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003615 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003616
David Chisnall44663db2009-08-17 16:35:33 +00003617 if ((lhsType->isObjCClassType() &&
3618 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3619 (rhsType->isObjCClassType() &&
3620 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3621 return Compatible;
3622 }
3623
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003624 // If the left-hand side is a reference type, then we are in a
3625 // (rare!) case where we've allowed the use of references in C,
3626 // e.g., as a parameter type in a built-in function. In this case,
3627 // just make sure that the type referenced is compatible with the
3628 // right-hand side type. The caller is responsible for adjusting
3629 // lhsType so that the resulting expression does not have reference
3630 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003631 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003632 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003633 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003634 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003635 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003636 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3637 // to the same ExtVector type.
3638 if (lhsType->isExtVectorType()) {
3639 if (rhsType->isExtVectorType())
3640 return lhsType == rhsType ? Compatible : Incompatible;
3641 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3642 return Compatible;
3643 }
3644
Nate Begemanc5f0f652008-07-14 18:02:46 +00003645 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003646 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003647 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003648 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003649 if (getLangOptions().LaxVectorConversions &&
3650 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003651 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003652 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003653 }
3654 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003655 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003656
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003657 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003658 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003659
Chris Lattner390564e2008-04-07 06:49:41 +00003660 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003661 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003662 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003663
Chris Lattner390564e2008-04-07 06:49:41 +00003664 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003665 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003666
Steve Naroff8194a542009-07-20 17:56:53 +00003667 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003668 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003669 if (lhsType->isVoidPointerType()) // an exception to the rule.
3670 return Compatible;
3671 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003672 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003673 if (rhsType->getAs<BlockPointerType>()) {
3674 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003675 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003676
3677 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003678 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003679 return Compatible;
3680 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003681 return Incompatible;
3682 }
3683
3684 if (isa<BlockPointerType>(lhsType)) {
3685 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003686 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003687
Steve Naroffa982c712008-09-29 18:10:17 +00003688 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003689 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003690 return Compatible;
3691
Steve Naroff3454b6c2008-09-04 15:10:53 +00003692 if (rhsType->isBlockPointerType())
3693 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003694
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003695 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003696 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003697 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003698 }
Chris Lattner1853da22008-01-04 23:18:45 +00003699 return Incompatible;
3700 }
3701
Steve Naroff329ec222009-07-10 23:34:53 +00003702 if (isa<ObjCObjectPointerType>(lhsType)) {
3703 if (rhsType->isIntegerType())
3704 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003705
3706 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003707 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003708 if (rhsType->isVoidPointerType()) // an exception to the rule.
3709 return Compatible;
3710 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003711 }
3712 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003713 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3714 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003715 if (Context.typesAreCompatible(lhsType, rhsType))
3716 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003717 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3718 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003719 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003720 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003721 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003722 if (RHSPT->getPointeeType()->isVoidType())
3723 return Compatible;
3724 }
3725 // Treat block pointers as objects.
3726 if (rhsType->isBlockPointerType())
3727 return Compatible;
3728 return Incompatible;
3729 }
Chris Lattner390564e2008-04-07 06:49:41 +00003730 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003731 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003732 if (lhsType == Context.BoolTy)
3733 return Compatible;
3734
3735 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003736 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003737
Mike Stump9afab102009-02-19 03:04:26 +00003738 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003739 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003740
3741 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003742 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003743 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003744 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003745 }
Steve Naroff329ec222009-07-10 23:34:53 +00003746 if (isa<ObjCObjectPointerType>(rhsType)) {
3747 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3748 if (lhsType == Context.BoolTy)
3749 return Compatible;
3750
3751 if (lhsType->isIntegerType())
3752 return PointerToInt;
3753
Steve Naroff8194a542009-07-20 17:56:53 +00003754 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003755 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003756 if (lhsType->isVoidPointerType()) // an exception to the rule.
3757 return Compatible;
3758 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003759 }
3760 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003761 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003762 return Compatible;
3763 return Incompatible;
3764 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003765
Chris Lattner1853da22008-01-04 23:18:45 +00003766 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003767 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003768 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003769 }
3770 return Incompatible;
3771}
3772
Douglas Gregor144b06c2009-04-29 22:16:16 +00003773/// \brief Constructs a transparent union from an expression that is
3774/// used to initialize the transparent union.
3775static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3776 QualType UnionType, FieldDecl *Field) {
3777 // Build an initializer list that designates the appropriate member
3778 // of the transparent union.
3779 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3780 &E, 1,
3781 SourceLocation());
3782 Initializer->setType(UnionType);
3783 Initializer->setInitializedFieldInUnion(Field);
3784
3785 // Build a compound literal constructing a value of the transparent
3786 // union type from this initializer list.
3787 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3788 false);
3789}
3790
3791Sema::AssignConvertType
3792Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3793 QualType FromType = rExpr->getType();
3794
3795 // If the ArgType is a Union type, we want to handle a potential
3796 // transparent_union GCC extension.
3797 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003798 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003799 return Incompatible;
3800
3801 // The field to initialize within the transparent union.
3802 RecordDecl *UD = UT->getDecl();
3803 FieldDecl *InitField = 0;
3804 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003805 for (RecordDecl::field_iterator it = UD->field_begin(),
3806 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003807 it != itend; ++it) {
3808 if (it->getType()->isPointerType()) {
3809 // If the transparent union contains a pointer type, we allow:
3810 // 1) void pointer
3811 // 2) null pointer constant
3812 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003813 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003814 ImpCastExprToType(rExpr, it->getType());
3815 InitField = *it;
3816 break;
3817 }
3818
3819 if (rExpr->isNullPointerConstant(Context)) {
3820 ImpCastExprToType(rExpr, it->getType());
3821 InitField = *it;
3822 break;
3823 }
3824 }
3825
3826 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3827 == Compatible) {
3828 InitField = *it;
3829 break;
3830 }
3831 }
3832
3833 if (!InitField)
3834 return Incompatible;
3835
3836 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3837 return Compatible;
3838}
3839
Chris Lattner005ed752008-01-04 18:04:52 +00003840Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003841Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003842 if (getLangOptions().CPlusPlus) {
3843 if (!lhsType->isRecordType()) {
3844 // C++ 5.17p3: If the left operand is not of class type, the
3845 // expression is implicitly converted (C++ 4) to the
3846 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003847 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3848 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003849 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003850 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003851 }
3852
3853 // FIXME: Currently, we fall through and treat C++ classes like C
3854 // structures.
3855 }
3856
Steve Naroffcdee22d2007-11-27 17:58:44 +00003857 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3858 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003859 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003860 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003861 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003862 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003863 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003864 return Compatible;
3865 }
Mike Stump9afab102009-02-19 03:04:26 +00003866
Chris Lattner5f505bf2007-10-16 02:55:40 +00003867 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003868 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003869 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003870 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003871 //
Mike Stump9afab102009-02-19 03:04:26 +00003872 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003873 if (!lhsType->isReferenceType())
3874 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003875
Chris Lattner005ed752008-01-04 18:04:52 +00003876 Sema::AssignConvertType result =
3877 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003878
Steve Naroff0f32f432007-08-24 22:33:52 +00003879 // C99 6.5.16.1p2: The value of the right operand is converted to the
3880 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003881 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3882 // so that we can use references in built-in functions even in C.
3883 // The getNonReferenceType() call makes sure that the resulting expression
3884 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003885 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003886 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003887 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003888}
3889
Chris Lattner1eafdea2008-11-18 01:30:42 +00003890QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003891 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003892 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003893 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003894 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003895}
3896
Mike Stump9afab102009-02-19 03:04:26 +00003897inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003898 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003899 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003900 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003901 QualType lhsType =
3902 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3903 QualType rhsType =
3904 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003905
Nate Begemanc5f0f652008-07-14 18:02:46 +00003906 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003907 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003908 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003909
Nate Begemanc5f0f652008-07-14 18:02:46 +00003910 // Handle the case of a vector & extvector type of the same size and element
3911 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003912 if (getLangOptions().LaxVectorConversions) {
3913 // FIXME: Should we warn here?
3914 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003915 if (const VectorType *RV = rhsType->getAsVectorType())
3916 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003917 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003918 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003919 }
3920 }
3921 }
Mike Stump9afab102009-02-19 03:04:26 +00003922
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003923 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3924 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3925 bool swapped = false;
3926 if (rhsType->isExtVectorType()) {
3927 swapped = true;
3928 std::swap(rex, lex);
3929 std::swap(rhsType, lhsType);
3930 }
3931
Nate Begemanf1695892009-06-28 19:12:57 +00003932 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003933 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3934 QualType EltTy = LV->getElementType();
3935 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3936 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003937 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003938 if (swapped) std::swap(rex, lex);
3939 return lhsType;
3940 }
3941 }
3942 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3943 rhsType->isRealFloatingType()) {
3944 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003945 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003946 if (swapped) std::swap(rex, lex);
3947 return lhsType;
3948 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003949 }
3950 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003951
Nate Begemanf1695892009-06-28 19:12:57 +00003952 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003953 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003954 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003955 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003956 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003957}
3958
Chris Lattner4b009652007-07-25 00:24:17 +00003959inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003960 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003961{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003962 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003963 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003964
Steve Naroff8f708362007-08-24 19:07:16 +00003965 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003966
Chris Lattner4b009652007-07-25 00:24:17 +00003967 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003968 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003969 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003970}
3971
3972inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003973 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003974{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003975 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3976 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3977 return CheckVectorOperands(Loc, lex, rex);
3978 return InvalidOperands(Loc, lex, rex);
3979 }
Chris Lattner4b009652007-07-25 00:24:17 +00003980
Steve Naroff8f708362007-08-24 19:07:16 +00003981 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003982
Chris Lattner4b009652007-07-25 00:24:17 +00003983 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003984 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003985 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003986}
3987
3988inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003989 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003990{
Eli Friedman3cd92882009-03-28 01:22:36 +00003991 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3992 QualType compType = CheckVectorOperands(Loc, lex, rex);
3993 if (CompLHSTy) *CompLHSTy = compType;
3994 return compType;
3995 }
Chris Lattner4b009652007-07-25 00:24:17 +00003996
Eli Friedman3cd92882009-03-28 01:22:36 +00003997 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003998
Chris Lattner4b009652007-07-25 00:24:17 +00003999 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004000 if (lex->getType()->isArithmeticType() &&
4001 rex->getType()->isArithmeticType()) {
4002 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004003 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004004 }
Chris Lattner4b009652007-07-25 00:24:17 +00004005
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004006 // Put any potential pointer into PExp
4007 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004008 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004009 std::swap(PExp, IExp);
4010
Steve Naroff79ae19a2009-07-14 18:25:06 +00004011 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004012
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004013 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004014 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004015
Chris Lattner184f92d2009-04-24 23:50:08 +00004016 // Check for arithmetic on pointers to incomplete types.
4017 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004018 if (getLangOptions().CPlusPlus) {
4019 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004020 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004021 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004022 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004023
4024 // GNU extension: arithmetic on pointer to void
4025 Diag(Loc, diag::ext_gnu_void_ptr)
4026 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004027 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004028 if (getLangOptions().CPlusPlus) {
4029 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4030 << lex->getType() << lex->getSourceRange();
4031 return QualType();
4032 }
4033
4034 // GNU extension: arithmetic on pointer to function
4035 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4036 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004037 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004038 // Check if we require a complete type.
4039 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004040 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004041 PExp->getType()->isObjCObjectPointerType()) &&
4042 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004043 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4044 << PExp->getSourceRange()
4045 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004046 return QualType();
4047 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004048 // Diagnose bad cases where we step over interface counts.
4049 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4050 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4051 << PointeeTy << PExp->getSourceRange();
4052 return QualType();
4053 }
4054
Eli Friedman3cd92882009-03-28 01:22:36 +00004055 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004056 QualType LHSTy = Context.isPromotableBitField(lex);
4057 if (LHSTy.isNull()) {
4058 LHSTy = lex->getType();
4059 if (LHSTy->isPromotableIntegerType())
4060 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004061 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004062 *CompLHSTy = LHSTy;
4063 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004064 return PExp->getType();
4065 }
4066 }
4067
Chris Lattner1eafdea2008-11-18 01:30:42 +00004068 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004069}
4070
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004071// C99 6.5.6
4072QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004073 SourceLocation Loc, QualType* CompLHSTy) {
4074 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4075 QualType compType = CheckVectorOperands(Loc, lex, rex);
4076 if (CompLHSTy) *CompLHSTy = compType;
4077 return compType;
4078 }
Mike Stump9afab102009-02-19 03:04:26 +00004079
Eli Friedman3cd92882009-03-28 01:22:36 +00004080 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004081
Chris Lattnerf6da2912007-12-09 21:53:25 +00004082 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004083
Chris Lattnerf6da2912007-12-09 21:53:25 +00004084 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004085 if (lex->getType()->isArithmeticType()
4086 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004087 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004088 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004089 }
Steve Naroff329ec222009-07-10 23:34:53 +00004090
Chris Lattnerf6da2912007-12-09 21:53:25 +00004091 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004092 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004093 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004094
Douglas Gregor05e28f62009-03-24 19:52:54 +00004095 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004096
Douglas Gregor05e28f62009-03-24 19:52:54 +00004097 bool ComplainAboutVoid = false;
4098 Expr *ComplainAboutFunc = 0;
4099 if (lpointee->isVoidType()) {
4100 if (getLangOptions().CPlusPlus) {
4101 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4102 << lex->getSourceRange() << rex->getSourceRange();
4103 return QualType();
4104 }
4105
4106 // GNU C extension: arithmetic on pointer to void
4107 ComplainAboutVoid = true;
4108 } else if (lpointee->isFunctionType()) {
4109 if (getLangOptions().CPlusPlus) {
4110 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004111 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004112 return QualType();
4113 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004114
4115 // GNU C extension: arithmetic on pointer to function
4116 ComplainAboutFunc = lex;
4117 } else if (!lpointee->isDependentType() &&
4118 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004119 PDiag(diag::err_typecheck_sub_ptr_object)
4120 << lex->getSourceRange()
4121 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004122 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004123
Chris Lattner184f92d2009-04-24 23:50:08 +00004124 // Diagnose bad cases where we step over interface counts.
4125 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4126 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4127 << lpointee << lex->getSourceRange();
4128 return QualType();
4129 }
4130
Chris Lattnerf6da2912007-12-09 21:53:25 +00004131 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004132 if (rex->getType()->isIntegerType()) {
4133 if (ComplainAboutVoid)
4134 Diag(Loc, diag::ext_gnu_void_ptr)
4135 << lex->getSourceRange() << rex->getSourceRange();
4136 if (ComplainAboutFunc)
4137 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4138 << ComplainAboutFunc->getType()
4139 << ComplainAboutFunc->getSourceRange();
4140
Eli Friedman3cd92882009-03-28 01:22:36 +00004141 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004142 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004143 }
Mike Stump9afab102009-02-19 03:04:26 +00004144
Chris Lattnerf6da2912007-12-09 21:53:25 +00004145 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004146 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004147 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004148
Douglas Gregor05e28f62009-03-24 19:52:54 +00004149 // RHS must be a completely-type object type.
4150 // Handle the GNU void* extension.
4151 if (rpointee->isVoidType()) {
4152 if (getLangOptions().CPlusPlus) {
4153 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4154 << lex->getSourceRange() << rex->getSourceRange();
4155 return QualType();
4156 }
Mike Stump9afab102009-02-19 03:04:26 +00004157
Douglas Gregor05e28f62009-03-24 19:52:54 +00004158 ComplainAboutVoid = true;
4159 } else if (rpointee->isFunctionType()) {
4160 if (getLangOptions().CPlusPlus) {
4161 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004162 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004163 return QualType();
4164 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004165
4166 // GNU extension: arithmetic on pointer to function
4167 if (!ComplainAboutFunc)
4168 ComplainAboutFunc = rex;
4169 } else if (!rpointee->isDependentType() &&
4170 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004171 PDiag(diag::err_typecheck_sub_ptr_object)
4172 << rex->getSourceRange()
4173 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004174 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004175
Eli Friedman143ddc92009-05-16 13:54:38 +00004176 if (getLangOptions().CPlusPlus) {
4177 // Pointee types must be the same: C++ [expr.add]
4178 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4179 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4180 << lex->getType() << rex->getType()
4181 << lex->getSourceRange() << rex->getSourceRange();
4182 return QualType();
4183 }
4184 } else {
4185 // Pointee types must be compatible C99 6.5.6p3
4186 if (!Context.typesAreCompatible(
4187 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4188 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4189 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4190 << lex->getType() << rex->getType()
4191 << lex->getSourceRange() << rex->getSourceRange();
4192 return QualType();
4193 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004194 }
Mike Stump9afab102009-02-19 03:04:26 +00004195
Douglas Gregor05e28f62009-03-24 19:52:54 +00004196 if (ComplainAboutVoid)
4197 Diag(Loc, diag::ext_gnu_void_ptr)
4198 << lex->getSourceRange() << rex->getSourceRange();
4199 if (ComplainAboutFunc)
4200 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4201 << ComplainAboutFunc->getType()
4202 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004203
4204 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004205 return Context.getPointerDiffType();
4206 }
4207 }
Mike Stump9afab102009-02-19 03:04:26 +00004208
Chris Lattner1eafdea2008-11-18 01:30:42 +00004209 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004210}
4211
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004212// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004213QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004214 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004215 // C99 6.5.7p2: Each of the operands shall have integer type.
4216 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004217 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004218
Chris Lattner2c8bff72007-12-12 05:47:28 +00004219 // Shifts don't perform usual arithmetic conversions, they just do integer
4220 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004221 QualType LHSTy = Context.isPromotableBitField(lex);
4222 if (LHSTy.isNull()) {
4223 LHSTy = lex->getType();
4224 if (LHSTy->isPromotableIntegerType())
4225 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004226 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004227 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004228 ImpCastExprToType(lex, LHSTy);
4229
Chris Lattner2c8bff72007-12-12 05:47:28 +00004230 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004231
Ryan Flynnf109fff2009-08-07 16:20:20 +00004232 // Sanity-check shift operands
4233 llvm::APSInt Right;
4234 // Check right/shifter operand
4235 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004236 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004237 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4238 else {
4239 llvm::APInt LeftBits(Right.getBitWidth(),
4240 Context.getTypeSize(lex->getType()));
4241 if (Right.uge(LeftBits))
4242 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4243 }
4244 }
4245
Chris Lattner2c8bff72007-12-12 05:47:28 +00004246 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004247 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004248}
4249
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004250// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004251QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004252 unsigned OpaqueOpc, bool isRelational) {
4253 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4254
Nate Begemanc5f0f652008-07-14 18:02:46 +00004255 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004256 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004257
Chris Lattner254f3bc2007-08-26 01:18:55 +00004258 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004259 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4260 UsualArithmeticConversions(lex, rex);
4261 else {
4262 UsualUnaryConversions(lex);
4263 UsualUnaryConversions(rex);
4264 }
Chris Lattner4b009652007-07-25 00:24:17 +00004265 QualType lType = lex->getType();
4266 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004267
Mike Stumpea3d74e2009-05-07 18:43:07 +00004268 if (!lType->isFloatingType()
4269 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004270 // For non-floating point types, check for self-comparisons of the form
4271 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4272 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004273 // NOTE: Don't warn about comparisons of enum constants. These can arise
4274 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004275 Expr *LHSStripped = lex->IgnoreParens();
4276 Expr *RHSStripped = rex->IgnoreParens();
4277 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4278 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004279 if (DRL->getDecl() == DRR->getDecl() &&
4280 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004281 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004282
4283 if (isa<CastExpr>(LHSStripped))
4284 LHSStripped = LHSStripped->IgnoreParenCasts();
4285 if (isa<CastExpr>(RHSStripped))
4286 RHSStripped = RHSStripped->IgnoreParenCasts();
4287
4288 // Warn about comparisons against a string constant (unless the other
4289 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004290 Expr *literalString = 0;
4291 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004292 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004293 !RHSStripped->isNullPointerConstant(Context)) {
4294 literalString = lex;
4295 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004296 } else if ((isa<StringLiteral>(RHSStripped) ||
4297 isa<ObjCEncodeExpr>(RHSStripped)) &&
4298 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004299 literalString = rex;
4300 literalStringStripped = RHSStripped;
4301 }
4302
4303 if (literalString) {
4304 std::string resultComparison;
4305 switch (Opc) {
4306 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4307 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4308 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4309 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4310 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4311 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4312 default: assert(false && "Invalid comparison operator");
4313 }
4314 Diag(Loc, diag::warn_stringcompare)
4315 << isa<ObjCEncodeExpr>(literalStringStripped)
4316 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004317 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4318 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4319 "strcmp(")
4320 << CodeModificationHint::CreateInsertion(
4321 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004322 resultComparison);
4323 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004324 }
Mike Stump9afab102009-02-19 03:04:26 +00004325
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004326 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004327 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004328
Chris Lattner254f3bc2007-08-26 01:18:55 +00004329 if (isRelational) {
4330 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004331 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004332 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004333 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004334 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004335 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004336 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004337 }
Mike Stump9afab102009-02-19 03:04:26 +00004338
Chris Lattner254f3bc2007-08-26 01:18:55 +00004339 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004340 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004341 }
Mike Stump9afab102009-02-19 03:04:26 +00004342
Chris Lattner22be8422007-08-26 01:10:14 +00004343 bool LHSIsNull = lex->isNullPointerConstant(Context);
4344 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004345
Chris Lattner254f3bc2007-08-26 01:18:55 +00004346 // All of the following pointer related warnings are GCC extensions, except
4347 // when handling null pointer constants. One day, we can consider making them
4348 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004349 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004350 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004351 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004352 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004353 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004354
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004355 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004356 if (LCanPointeeTy == RCanPointeeTy)
4357 return ResultTy;
4358
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004359 // C++ [expr.rel]p2:
4360 // [...] Pointer conversions (4.10) and qualification
4361 // conversions (4.4) are performed on pointer operands (or on
4362 // a pointer operand and a null pointer constant) to bring
4363 // them to their composite pointer type. [...]
4364 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004365 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004366 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004367 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004368 if (T.isNull()) {
4369 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4370 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4371 return QualType();
4372 }
4373
4374 ImpCastExprToType(lex, T);
4375 ImpCastExprToType(rex, T);
4376 return ResultTy;
4377 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004378 // C99 6.5.9p2 and C99 6.5.8p2
4379 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4380 RCanPointeeTy.getUnqualifiedType())) {
4381 // Valid unless a relational comparison of function pointers
4382 if (isRelational && LCanPointeeTy->isFunctionType()) {
4383 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4384 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4385 }
4386 } else if (!isRelational &&
4387 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4388 // Valid unless comparison between non-null pointer and function pointer
4389 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4390 && !LHSIsNull && !RHSIsNull) {
4391 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4392 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4393 }
4394 } else {
4395 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004396 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004397 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004398 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004399 if (LCanPointeeTy != RCanPointeeTy)
4400 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004401 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004402 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004403
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004404 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004405 // Comparison of pointers with null pointer constants and equality
4406 // comparisons of member pointers to null pointer constants.
4407 if (RHSIsNull &&
4408 (lType->isPointerType() ||
4409 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004410 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004411 return ResultTy;
4412 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004413 if (LHSIsNull &&
4414 (rType->isPointerType() ||
4415 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004416 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004417 return ResultTy;
4418 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004419
4420 // Comparison of member pointers.
4421 if (!isRelational &&
4422 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4423 // C++ [expr.eq]p2:
4424 // In addition, pointers to members can be compared, or a pointer to
4425 // member and a null pointer constant. Pointer to member conversions
4426 // (4.11) and qualification conversions (4.4) are performed to bring
4427 // them to a common type. If one operand is a null pointer constant,
4428 // the common type is the type of the other operand. Otherwise, the
4429 // common type is a pointer to member type similar (4.4) to the type
4430 // of one of the operands, with a cv-qualification signature (4.4)
4431 // that is the union of the cv-qualification signatures of the operand
4432 // types.
4433 QualType T = FindCompositePointerType(lex, rex);
4434 if (T.isNull()) {
4435 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4436 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4437 return QualType();
4438 }
4439
4440 ImpCastExprToType(lex, T);
4441 ImpCastExprToType(rex, T);
4442 return ResultTy;
4443 }
4444
4445 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004446 if (lType->isNullPtrType() && rType->isNullPtrType())
4447 return ResultTy;
4448 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004449
Steve Naroff3454b6c2008-09-04 15:10:53 +00004450 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004451 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004452 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4453 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004454
Steve Naroff3454b6c2008-09-04 15:10:53 +00004455 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004456 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004457 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004458 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004459 }
4460 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004461 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004462 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004463 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004464 if (!isRelational
4465 && ((lType->isBlockPointerType() && rType->isPointerType())
4466 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004467 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004468 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004469 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004470 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004471 ->getPointeeType()->isVoidType())))
4472 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4473 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004474 }
4475 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004476 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004477 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004478
Steve Naroff329ec222009-07-10 23:34:53 +00004479 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004480 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004481 const PointerType *LPT = lType->getAs<PointerType>();
4482 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004483 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004484 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004485 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004486 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004487
Steve Naroff030fcda2008-11-17 19:49:16 +00004488 if (!LPtrToVoid && !RPtrToVoid &&
4489 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004490 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004491 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004492 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004493 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004494 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004495 }
Steve Naroff329ec222009-07-10 23:34:53 +00004496 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004497 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004498 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4499 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004500 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004501 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004502 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004503 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004504 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004505 unsigned DiagID = 0;
4506 if (RHSIsNull) {
4507 if (isRelational)
4508 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4509 } else if (isRelational)
4510 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4511 else
4512 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4513
4514 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004515 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004516 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004517 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004518 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004519 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004520 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004521 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004522 unsigned DiagID = 0;
4523 if (LHSIsNull) {
4524 if (isRelational)
4525 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4526 } else if (isRelational)
4527 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4528 else
4529 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004530
Chris Lattner124569f2009-08-23 00:03:44 +00004531 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004532 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004533 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004534 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004535 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004536 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004537 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004538 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004539 if (!isRelational && RHSIsNull
4540 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004541 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004542 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004543 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004544 if (!isRelational && LHSIsNull
4545 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004546 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004547 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004548 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004549 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004550}
4551
Nate Begemanc5f0f652008-07-14 18:02:46 +00004552/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004553/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004554/// like a scalar comparison, a vector comparison produces a vector of integer
4555/// types.
4556QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004557 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004558 bool isRelational) {
4559 // Check to make sure we're operating on vectors of the same type and width,
4560 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004561 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004562 if (vType.isNull())
4563 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004564
Nate Begemanc5f0f652008-07-14 18:02:46 +00004565 QualType lType = lex->getType();
4566 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004567
Nate Begemanc5f0f652008-07-14 18:02:46 +00004568 // For non-floating point types, check for self-comparisons of the form
4569 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4570 // often indicate logic errors in the program.
4571 if (!lType->isFloatingType()) {
4572 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4573 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4574 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004575 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004576 }
Mike Stump9afab102009-02-19 03:04:26 +00004577
Nate Begemanc5f0f652008-07-14 18:02:46 +00004578 // Check for comparisons of floating point operands using != and ==.
4579 if (!isRelational && lType->isFloatingType()) {
4580 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004581 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004582 }
Mike Stump9afab102009-02-19 03:04:26 +00004583
Nate Begemanc5f0f652008-07-14 18:02:46 +00004584 // Return the type for the comparison, which is the same as vector type for
4585 // integer vectors, or an integer type of identical size and number of
4586 // elements for floating point vectors.
4587 if (lType->isIntegerType())
4588 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004589
Nate Begemanc5f0f652008-07-14 18:02:46 +00004590 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004591 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004592 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004593 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004594 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004595 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4596
Mike Stump9afab102009-02-19 03:04:26 +00004597 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004598 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004599 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4600}
4601
Chris Lattner4b009652007-07-25 00:24:17 +00004602inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004603 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004604{
4605 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004606 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004607
Steve Naroff8f708362007-08-24 19:07:16 +00004608 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004609
Chris Lattner4b009652007-07-25 00:24:17 +00004610 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004611 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004612 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004613}
4614
4615inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004616 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004617{
4618 UsualUnaryConversions(lex);
4619 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004620
Eli Friedmanbea3f842008-05-13 20:16:47 +00004621 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004622 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004623 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004624}
4625
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004626/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4627/// is a read-only property; return true if so. A readonly property expression
4628/// depends on various declarations and thus must be treated specially.
4629///
Mike Stump9afab102009-02-19 03:04:26 +00004630static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004631{
4632 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4633 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4634 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4635 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004636 if (const ObjCObjectPointerType *OPT =
4637 BaseType->getAsObjCInterfacePointerType())
4638 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4639 if (S.isPropertyReadonly(PDecl, IFace))
4640 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004641 }
4642 }
4643 return false;
4644}
4645
Chris Lattner4c2642c2008-11-18 01:22:49 +00004646/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4647/// emit an error and return true. If so, return false.
4648static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004649 SourceLocation OrigLoc = Loc;
4650 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4651 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004652 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4653 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004654 if (IsLV == Expr::MLV_Valid)
4655 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004656
Chris Lattner4c2642c2008-11-18 01:22:49 +00004657 unsigned Diag = 0;
4658 bool NeedType = false;
4659 switch (IsLV) { // C99 6.5.16p2
4660 default: assert(0 && "Unknown result from isModifiableLvalue!");
4661 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004662 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004663 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4664 NeedType = true;
4665 break;
Mike Stump9afab102009-02-19 03:04:26 +00004666 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004667 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4668 NeedType = true;
4669 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004670 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004671 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4672 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004673 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004674 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4675 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004676 case Expr::MLV_IncompleteType:
4677 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004678 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004679 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4680 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004681 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004682 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4683 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004684 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004685 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4686 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004687 case Expr::MLV_ReadonlyProperty:
4688 Diag = diag::error_readonly_property_assignment;
4689 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004690 case Expr::MLV_NoSetterProperty:
4691 Diag = diag::error_nosetter_property_assignment;
4692 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004693 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004694
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004695 SourceRange Assign;
4696 if (Loc != OrigLoc)
4697 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004698 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004699 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004700 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004701 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004702 return true;
4703}
4704
4705
4706
4707// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004708QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4709 SourceLocation Loc,
4710 QualType CompoundType) {
4711 // Verify that LHS is a modifiable lvalue, and emit error if not.
4712 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004713 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004714
4715 QualType LHSType = LHS->getType();
4716 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004717
Chris Lattner005ed752008-01-04 18:04:52 +00004718 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004719 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004720 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004721 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004722 // Special case of NSObject attributes on c-style pointer types.
4723 if (ConvTy == IncompatiblePointer &&
4724 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004725 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004726 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004727 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004728 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004729
Chris Lattner34c85082008-08-21 18:04:13 +00004730 // If the RHS is a unary plus or minus, check to see if they = and + are
4731 // right next to each other. If so, the user may have typo'd "x =+ 4"
4732 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004733 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004734 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4735 RHSCheck = ICE->getSubExpr();
4736 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4737 if ((UO->getOpcode() == UnaryOperator::Plus ||
4738 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004739 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004740 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004741 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4742 // And there is a space or other character before the subexpr of the
4743 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004744 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4745 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004746 Diag(Loc, diag::warn_not_compound_assign)
4747 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4748 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004749 }
Chris Lattner34c85082008-08-21 18:04:13 +00004750 }
4751 } else {
4752 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004753 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004754 }
Chris Lattner005ed752008-01-04 18:04:52 +00004755
Chris Lattner1eafdea2008-11-18 01:30:42 +00004756 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4757 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004758 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004759
Chris Lattner4b009652007-07-25 00:24:17 +00004760 // C99 6.5.16p3: The type of an assignment expression is the type of the
4761 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004762 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004763 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4764 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004765 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004766 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004767 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004768}
4769
Chris Lattner1eafdea2008-11-18 01:30:42 +00004770// C99 6.5.17
4771QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004772 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004773 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004774
4775 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4776 // incomplete in C++).
4777
Chris Lattner1eafdea2008-11-18 01:30:42 +00004778 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004779}
4780
4781/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4782/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004783QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4784 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004785 if (Op->isTypeDependent())
4786 return Context.DependentTy;
4787
Chris Lattnere65182c2008-11-21 07:05:48 +00004788 QualType ResType = Op->getType();
4789 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004790
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004791 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4792 // Decrement of bool is not allowed.
4793 if (!isInc) {
4794 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4795 return QualType();
4796 }
4797 // Increment of bool sets it to true, but is deprecated.
4798 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4799 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004800 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004801 } else if (ResType->isAnyPointerType()) {
4802 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004803
Chris Lattnere65182c2008-11-21 07:05:48 +00004804 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004805 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004806 if (getLangOptions().CPlusPlus) {
4807 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4808 << Op->getSourceRange();
4809 return QualType();
4810 }
4811
4812 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004813 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004814 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004815 if (getLangOptions().CPlusPlus) {
4816 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4817 << Op->getType() << Op->getSourceRange();
4818 return QualType();
4819 }
4820
4821 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004822 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004823 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004824 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4825 << Op->getSourceRange()
4826 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004827 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004828 // Diagnose bad cases where we step over interface counts.
4829 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4830 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4831 << PointeeTy << Op->getSourceRange();
4832 return QualType();
4833 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004834 } else if (ResType->isComplexType()) {
4835 // C99 does not support ++/-- on complex types, we allow as an extension.
4836 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004837 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004838 } else {
4839 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004840 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004841 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004842 }
Mike Stump9afab102009-02-19 03:04:26 +00004843 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004844 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004845 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004846 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004847 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004848}
4849
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004850/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004851/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004852/// where the declaration is needed for type checking. We only need to
4853/// handle cases when the expression references a function designator
4854/// or is an lvalue. Here are some examples:
4855/// - &(x) => x
4856/// - &*****f => f for f a function designator.
4857/// - &s.xx => s
4858/// - &s.zz[1].yy -> s, if zz is an array
4859/// - *(x + 1) -> x, if x is an array
4860/// - &"123"[2] -> 0
4861/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004862static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004863 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004864 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004865 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004866 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004867 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004868 // If this is an arrow operator, the address is an offset from
4869 // the base's value, so the object the base refers to is
4870 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004871 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004872 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004873 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004874 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004875 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004876 // FIXME: This code shouldn't be necessary! We should catch the implicit
4877 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004878 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4879 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4880 if (ICE->getSubExpr()->getType()->isArrayType())
4881 return getPrimaryDecl(ICE->getSubExpr());
4882 }
4883 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004884 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004885 case Stmt::UnaryOperatorClass: {
4886 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004887
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004888 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004889 case UnaryOperator::Real:
4890 case UnaryOperator::Imag:
4891 case UnaryOperator::Extension:
4892 return getPrimaryDecl(UO->getSubExpr());
4893 default:
4894 return 0;
4895 }
4896 }
Chris Lattner4b009652007-07-25 00:24:17 +00004897 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004898 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004899 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004900 // If the result of an implicit cast is an l-value, we care about
4901 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004902 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004903 default:
4904 return 0;
4905 }
4906}
4907
4908/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004909/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004910/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004911/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004912/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004913/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004914/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004915QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004916 // Make sure to ignore parentheses in subsequent checks
4917 op = op->IgnoreParens();
4918
Douglas Gregore6be68a2008-12-17 22:52:20 +00004919 if (op->isTypeDependent())
4920 return Context.DependentTy;
4921
Steve Naroff9c6c3592008-01-13 17:10:08 +00004922 if (getLangOptions().C99) {
4923 // Implement C99-only parts of addressof rules.
4924 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4925 if (uOp->getOpcode() == UnaryOperator::Deref)
4926 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4927 // (assuming the deref expression is valid).
4928 return uOp->getSubExpr()->getType();
4929 }
4930 // Technically, there should be a check for array subscript
4931 // expressions here, but the result of one is always an lvalue anyway.
4932 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004933 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004934 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004935
Eli Friedman14ab4c42009-05-16 23:27:50 +00004936 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4937 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004938 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004939 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004940 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004941 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4942 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004943 return QualType();
4944 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004945 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004946 // The operand cannot be a bit-field
4947 Diag(OpLoc, diag::err_typecheck_address_of)
4948 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004949 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004950 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4951 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004952 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004953 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004954 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004955 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004956 } else if (isa<ObjCPropertyRefExpr>(op)) {
4957 // cannot take address of a property expression.
4958 Diag(OpLoc, diag::err_typecheck_address_of)
4959 << "property expression" << op->getSourceRange();
4960 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004961 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004962 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004963 // with the register storage-class specifier.
4964 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4965 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004966 Diag(OpLoc, diag::err_typecheck_address_of)
4967 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004968 return QualType();
4969 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004970 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4971 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004972 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004973 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004974 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004975 // Could be a pointer to member, though, if there is an explicit
4976 // scope qualifier for the class.
4977 if (isa<QualifiedDeclRefExpr>(op)) {
4978 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004979 if (Ctx && Ctx->isRecord()) {
4980 if (FD->getType()->isReferenceType()) {
4981 Diag(OpLoc,
4982 diag::err_cannot_form_pointer_to_member_of_reference_type)
4983 << FD->getDeclName() << FD->getType();
4984 return QualType();
4985 }
4986
Sebastian Redl0c9da212009-02-03 20:19:35 +00004987 return Context.getMemberPointerType(op->getType(),
4988 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004989 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004990 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004991 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004992 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004993 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004994 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4995 return Context.getMemberPointerType(op->getType(),
4996 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4997 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004998 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004999 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00005000
Eli Friedman14ab4c42009-05-16 23:27:50 +00005001 if (lval == Expr::LV_IncompleteVoidType) {
5002 // Taking the address of a void variable is technically illegal, but we
5003 // allow it in cases which are otherwise valid.
5004 // Example: "extern void x; void* y = &x;".
5005 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5006 }
5007
Chris Lattner4b009652007-07-25 00:24:17 +00005008 // If the operand has type "type", the result has type "pointer to type".
5009 return Context.getPointerType(op->getType());
5010}
5011
Chris Lattnerda5c0872008-11-23 09:13:29 +00005012QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005013 if (Op->isTypeDependent())
5014 return Context.DependentTy;
5015
Chris Lattnerda5c0872008-11-23 09:13:29 +00005016 UsualUnaryConversions(Op);
5017 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005018
Chris Lattnerda5c0872008-11-23 09:13:29 +00005019 // Note that per both C89 and C99, this is always legal, even if ptype is an
5020 // incomplete type or void. It would be possible to warn about dereferencing
5021 // a void pointer, but it's completely well-defined, and such a warning is
5022 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005023 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005024 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005025
Fariborz Jahanian81699d92009-09-03 00:43:07 +00005026 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5027 return OPT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00005028
Chris Lattner77d52da2008-11-20 06:06:08 +00005029 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005030 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005031 return QualType();
5032}
5033
5034static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5035 tok::TokenKind Kind) {
5036 BinaryOperator::Opcode Opc;
5037 switch (Kind) {
5038 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005039 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5040 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005041 case tok::star: Opc = BinaryOperator::Mul; break;
5042 case tok::slash: Opc = BinaryOperator::Div; break;
5043 case tok::percent: Opc = BinaryOperator::Rem; break;
5044 case tok::plus: Opc = BinaryOperator::Add; break;
5045 case tok::minus: Opc = BinaryOperator::Sub; break;
5046 case tok::lessless: Opc = BinaryOperator::Shl; break;
5047 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5048 case tok::lessequal: Opc = BinaryOperator::LE; break;
5049 case tok::less: Opc = BinaryOperator::LT; break;
5050 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5051 case tok::greater: Opc = BinaryOperator::GT; break;
5052 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5053 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5054 case tok::amp: Opc = BinaryOperator::And; break;
5055 case tok::caret: Opc = BinaryOperator::Xor; break;
5056 case tok::pipe: Opc = BinaryOperator::Or; break;
5057 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5058 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5059 case tok::equal: Opc = BinaryOperator::Assign; break;
5060 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5061 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5062 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5063 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5064 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5065 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5066 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5067 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5068 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5069 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5070 case tok::comma: Opc = BinaryOperator::Comma; break;
5071 }
5072 return Opc;
5073}
5074
5075static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5076 tok::TokenKind Kind) {
5077 UnaryOperator::Opcode Opc;
5078 switch (Kind) {
5079 default: assert(0 && "Unknown unary op!");
5080 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5081 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5082 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5083 case tok::star: Opc = UnaryOperator::Deref; break;
5084 case tok::plus: Opc = UnaryOperator::Plus; break;
5085 case tok::minus: Opc = UnaryOperator::Minus; break;
5086 case tok::tilde: Opc = UnaryOperator::Not; break;
5087 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005088 case tok::kw___real: Opc = UnaryOperator::Real; break;
5089 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5090 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5091 }
5092 return Opc;
5093}
5094
Douglas Gregord7f915e2008-11-06 23:29:22 +00005095/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5096/// operator @p Opc at location @c TokLoc. This routine only supports
5097/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005098Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5099 unsigned Op,
5100 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005101 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005102 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005103 // The following two variables are used for compound assignment operators
5104 QualType CompLHSTy; // Type of LHS after promotions for computation
5105 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005106
5107 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005108 case BinaryOperator::Assign:
5109 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5110 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005111 case BinaryOperator::PtrMemD:
5112 case BinaryOperator::PtrMemI:
5113 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5114 Opc == BinaryOperator::PtrMemI);
5115 break;
5116 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005117 case BinaryOperator::Div:
5118 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5119 break;
5120 case BinaryOperator::Rem:
5121 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5122 break;
5123 case BinaryOperator::Add:
5124 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5125 break;
5126 case BinaryOperator::Sub:
5127 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5128 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005129 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005130 case BinaryOperator::Shr:
5131 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5132 break;
5133 case BinaryOperator::LE:
5134 case BinaryOperator::LT:
5135 case BinaryOperator::GE:
5136 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005137 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005138 break;
5139 case BinaryOperator::EQ:
5140 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005141 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005142 break;
5143 case BinaryOperator::And:
5144 case BinaryOperator::Xor:
5145 case BinaryOperator::Or:
5146 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5147 break;
5148 case BinaryOperator::LAnd:
5149 case BinaryOperator::LOr:
5150 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5151 break;
5152 case BinaryOperator::MulAssign:
5153 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005154 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5155 CompLHSTy = CompResultTy;
5156 if (!CompResultTy.isNull())
5157 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005158 break;
5159 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005160 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5161 CompLHSTy = CompResultTy;
5162 if (!CompResultTy.isNull())
5163 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005164 break;
5165 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005166 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5167 if (!CompResultTy.isNull())
5168 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005169 break;
5170 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005171 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5172 if (!CompResultTy.isNull())
5173 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005174 break;
5175 case BinaryOperator::ShlAssign:
5176 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005177 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5178 CompLHSTy = CompResultTy;
5179 if (!CompResultTy.isNull())
5180 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005181 break;
5182 case BinaryOperator::AndAssign:
5183 case BinaryOperator::XorAssign:
5184 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005185 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5186 CompLHSTy = CompResultTy;
5187 if (!CompResultTy.isNull())
5188 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005189 break;
5190 case BinaryOperator::Comma:
5191 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5192 break;
5193 }
5194 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005195 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005196 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005197 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5198 else
5199 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005200 CompLHSTy, CompResultTy,
5201 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005202}
5203
Chris Lattner4b009652007-07-25 00:24:17 +00005204// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005205Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5206 tok::TokenKind Kind,
5207 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005208 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005209 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005210
Steve Naroff87d58b42007-09-16 03:34:24 +00005211 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5212 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005213
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005214 if (getLangOptions().CPlusPlus &&
5215 (lhs->getType()->isOverloadableType() ||
5216 rhs->getType()->isOverloadableType())) {
5217 // Find all of the overloaded operators visible from this
5218 // point. We perform both an operator-name lookup from the local
5219 // scope and an argument-dependent lookup based on the types of
5220 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005221 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005222 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5223 if (OverOp != OO_None) {
5224 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5225 Functions);
5226 Expr *Args[2] = { lhs, rhs };
5227 DeclarationName OpName
5228 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5229 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005230 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005231
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005232 // Build the (potentially-overloaded, potentially-dependent)
5233 // binary operation.
5234 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005235 }
5236
Douglas Gregord7f915e2008-11-06 23:29:22 +00005237 // Build a built-in binary operation.
5238 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005239}
5240
Douglas Gregorc78182d2009-03-13 23:49:33 +00005241Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5242 unsigned OpcIn,
5243 ExprArg InputArg) {
5244 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005245
Mike Stumpe127ae32009-05-16 07:39:55 +00005246 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005247 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005248 QualType resultType;
5249 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005250 case UnaryOperator::OffsetOf:
5251 assert(false && "Invalid unary operator");
5252 break;
5253
Chris Lattner4b009652007-07-25 00:24:17 +00005254 case UnaryOperator::PreInc:
5255 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005256 case UnaryOperator::PostInc:
5257 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005258 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005259 Opc == UnaryOperator::PreInc ||
5260 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005261 break;
Mike Stump9afab102009-02-19 03:04:26 +00005262 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005263 resultType = CheckAddressOfOperand(Input, OpLoc);
5264 break;
Mike Stump9afab102009-02-19 03:04:26 +00005265 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005266 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005267 resultType = CheckIndirectionOperand(Input, OpLoc);
5268 break;
5269 case UnaryOperator::Plus:
5270 case UnaryOperator::Minus:
5271 UsualUnaryConversions(Input);
5272 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005273 if (resultType->isDependentType())
5274 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005275 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5276 break;
5277 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5278 resultType->isEnumeralType())
5279 break;
5280 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5281 Opc == UnaryOperator::Plus &&
5282 resultType->isPointerType())
5283 break;
5284
Sebastian Redl8b769972009-01-19 00:08:26 +00005285 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5286 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005287 case UnaryOperator::Not: // bitwise complement
5288 UsualUnaryConversions(Input);
5289 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005290 if (resultType->isDependentType())
5291 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005292 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5293 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5294 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005295 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005296 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005297 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005298 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5299 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005300 break;
5301 case UnaryOperator::LNot: // logical negation
5302 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5303 DefaultFunctionArrayConversion(Input);
5304 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005305 if (resultType->isDependentType())
5306 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005307 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005308 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5309 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005310 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005311 // In C++, it's bool. C++ 5.3.1p8
5312 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005313 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005314 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005315 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005316 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005317 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005318 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005319 resultType = Input->getType();
5320 break;
5321 }
5322 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005323 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005324
5325 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005326 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005327}
5328
Douglas Gregorc78182d2009-03-13 23:49:33 +00005329// Unary Operators. 'Tok' is the token for the operator.
5330Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5331 tok::TokenKind Op, ExprArg input) {
5332 Expr *Input = (Expr*)input.get();
5333 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5334
5335 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5336 // Find all of the overloaded operators visible from this
5337 // point. We perform both an operator-name lookup from the local
5338 // scope and an argument-dependent lookup based on the types of
5339 // the arguments.
5340 FunctionSet Functions;
5341 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5342 if (OverOp != OO_None) {
5343 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5344 Functions);
5345 DeclarationName OpName
5346 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5347 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5348 }
5349
5350 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5351 }
5352
5353 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5354}
5355
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005356/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005357Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5358 SourceLocation LabLoc,
5359 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005360 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005361 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005362
Daniel Dunbar879788d2008-08-04 16:51:22 +00005363 // If we haven't seen this label yet, create a forward reference. It
5364 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005365 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005366 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005367
Chris Lattner4b009652007-07-25 00:24:17 +00005368 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005369 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5370 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005371}
5372
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005373Sema::OwningExprResult
5374Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5375 SourceLocation RPLoc) { // "({..})"
5376 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005377 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5378 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5379
Eli Friedmanbc941e12009-01-24 23:09:00 +00005380 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005381 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005382 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005383
Chris Lattner4b009652007-07-25 00:24:17 +00005384 // FIXME: there are a variety of strange constraints to enforce here, for
5385 // example, it is not possible to goto into a stmt expression apparently.
5386 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005387
Chris Lattner4b009652007-07-25 00:24:17 +00005388 // If there are sub stmts in the compound stmt, take the type of the last one
5389 // as the type of the stmtexpr.
5390 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005391
Chris Lattner200964f2008-07-26 19:51:01 +00005392 if (!Compound->body_empty()) {
5393 Stmt *LastStmt = Compound->body_back();
5394 // If LastStmt is a label, skip down through into the body.
5395 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5396 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005397
Chris Lattner200964f2008-07-26 19:51:01 +00005398 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005399 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005400 }
Mike Stump9afab102009-02-19 03:04:26 +00005401
Eli Friedman2b128322009-03-23 00:24:07 +00005402 // FIXME: Check that expression type is complete/non-abstract; statement
5403 // expressions are not lvalues.
5404
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005405 substmt.release();
5406 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005407}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005408
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005409Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5410 SourceLocation BuiltinLoc,
5411 SourceLocation TypeLoc,
5412 TypeTy *argty,
5413 OffsetOfComponent *CompPtr,
5414 unsigned NumComponents,
5415 SourceLocation RPLoc) {
5416 // FIXME: This function leaks all expressions in the offset components on
5417 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005418 // FIXME: Preserve type source info.
5419 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005420 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005421
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005422 bool Dependent = ArgTy->isDependentType();
5423
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005424 // We must have at least one component that refers to the type, and the first
5425 // one is known to be a field designator. Verify that the ArgTy represents
5426 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005427 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005428 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005429
Eli Friedman2b128322009-03-23 00:24:07 +00005430 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5431 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005432
Eli Friedman342d9432009-02-27 06:44:11 +00005433 // Otherwise, create a null pointer as the base, and iteratively process
5434 // the offsetof designators.
5435 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5436 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005437 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005438 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005439
Chris Lattnerb37522e2007-08-31 21:49:13 +00005440 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5441 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005442 // FIXME: This diagnostic isn't actually visible because the location is in
5443 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005444 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005445 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5446 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005447
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005448 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005449 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005450
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005451 // FIXME: Dependent case loses a lot of information here. And probably
5452 // leaks like a sieve.
5453 for (unsigned i = 0; i != NumComponents; ++i) {
5454 const OffsetOfComponent &OC = CompPtr[i];
5455 if (OC.isBrackets) {
5456 // Offset of an array sub-field. TODO: Should we allow vector elements?
5457 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5458 if (!AT) {
5459 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005460 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5461 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005462 }
5463
5464 // FIXME: C++: Verify that operator[] isn't overloaded.
5465
Eli Friedman342d9432009-02-27 06:44:11 +00005466 // Promote the array so it looks more like a normal array subscript
5467 // expression.
5468 DefaultFunctionArrayConversion(Res);
5469
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005470 // C99 6.5.2.1p1
5471 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005472 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005473 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005474 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005475 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005476 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005477
5478 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5479 OC.LocEnd);
5480 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005481 }
Mike Stump9afab102009-02-19 03:04:26 +00005482
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005483 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005484 if (!RC) {
5485 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005486 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5487 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005488 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005489
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005490 // Get the decl corresponding to this.
5491 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005492 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005493 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005494 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5495 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5496 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005497 DidWarnAboutNonPOD = true;
5498 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005499 }
5500
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005501 FieldDecl *MemberDecl
5502 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5503 LookupMemberName)
5504 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005505 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005506 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005507 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005508 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005509
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005510 // FIXME: C++: Verify that MemberDecl isn't a static field.
5511 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005512 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005513 Res = BuildAnonymousStructUnionMemberReference(
5514 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005515 } else {
5516 // MemberDecl->getType() doesn't get the right qualifiers, but it
5517 // doesn't matter here.
5518 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5519 MemberDecl->getType().getNonReferenceType());
5520 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005521 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005522 }
Mike Stump9afab102009-02-19 03:04:26 +00005523
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005524 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5525 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005526}
5527
5528
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005529Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5530 TypeTy *arg1,TypeTy *arg2,
5531 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005532 // FIXME: Preserve type source info.
5533 QualType argT1 = GetTypeFromParser(arg1);
5534 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005535
Steve Naroff63bad2d2007-08-01 22:05:33 +00005536 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005537
Douglas Gregore6211502009-05-19 22:28:02 +00005538 if (getLangOptions().CPlusPlus) {
5539 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5540 << SourceRange(BuiltinLoc, RPLoc);
5541 return ExprError();
5542 }
5543
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005544 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5545 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005546}
5547
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005548Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5549 ExprArg cond,
5550 ExprArg expr1, ExprArg expr2,
5551 SourceLocation RPLoc) {
5552 Expr *CondExpr = static_cast<Expr*>(cond.get());
5553 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5554 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005555
Steve Naroff93c53012007-08-03 21:21:27 +00005556 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5557
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005558 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005559 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005560 resType = Context.DependentTy;
5561 } else {
5562 // The conditional expression is required to be a constant expression.
5563 llvm::APSInt condEval(32);
5564 SourceLocation ExpLoc;
5565 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005566 return ExprError(Diag(ExpLoc,
5567 diag::err_typecheck_choose_expr_requires_constant)
5568 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005569
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005570 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5571 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5572 }
5573
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005574 cond.release(); expr1.release(); expr2.release();
5575 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5576 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005577}
5578
Steve Naroff52a81c02008-09-03 18:15:37 +00005579//===----------------------------------------------------------------------===//
5580// Clang Extensions.
5581//===----------------------------------------------------------------------===//
5582
5583/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005584void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005585 // Analyze block parameters.
5586 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005587
Steve Naroff52a81c02008-09-03 18:15:37 +00005588 // Add BSI to CurBlock.
5589 BSI->PrevBlockInfo = CurBlock;
5590 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005591
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005592 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005593 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005594 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005595 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005596 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5597 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005598
Steve Naroff52059382008-10-10 01:28:17 +00005599 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005600 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005601}
5602
Mike Stumpc1fddff2009-02-04 22:31:32 +00005603void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005604 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005605
5606 if (ParamInfo.getNumTypeObjects() == 0
5607 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005608 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005609 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5610
Mike Stump458287d2009-04-28 01:10:27 +00005611 if (T->isArrayType()) {
5612 Diag(ParamInfo.getSourceRange().getBegin(),
5613 diag::err_block_returns_array);
5614 return;
5615 }
5616
Mike Stumpc1fddff2009-02-04 22:31:32 +00005617 // The parameter list is optional, if there was none, assume ().
5618 if (!T->isFunctionType())
5619 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5620
5621 CurBlock->hasPrototype = true;
5622 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005623 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005624 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005625 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005626 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005627 // FIXME: remove the attribute.
5628 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005629 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5630
5631 // Do not allow returning a objc interface by-value.
5632 if (RetTy->isObjCInterfaceType()) {
5633 Diag(ParamInfo.getSourceRange().getBegin(),
5634 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5635 return;
5636 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005637 return;
5638 }
5639
Steve Naroff52a81c02008-09-03 18:15:37 +00005640 // Analyze arguments to block.
5641 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5642 "Not a function declarator!");
5643 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005644
Steve Naroff52059382008-10-10 01:28:17 +00005645 CurBlock->hasPrototype = FTI.hasPrototype;
5646 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005647
Steve Naroff52a81c02008-09-03 18:15:37 +00005648 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5649 // no arguments, not a function that takes a single void argument.
5650 if (FTI.hasPrototype &&
5651 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005652 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5653 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005654 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005655 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005656 } else if (FTI.hasPrototype) {
5657 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005658 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005659 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005660 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005661 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005662 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005663 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005664 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005665 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5666 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5667 // If this has an identifier, add it to the scope stack.
5668 if ((*AI)->getIdentifier())
5669 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005670
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005671 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005672 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005673 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005674 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005675 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005676 // FIXME: remove the attribute.
5677 }
5678
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005679 // Analyze the return type.
5680 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5681 QualType RetTy = T->getAsFunctionType()->getResultType();
5682
5683 // Do not allow returning a objc interface by-value.
5684 if (RetTy->isObjCInterfaceType()) {
5685 Diag(ParamInfo.getSourceRange().getBegin(),
5686 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5687 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005688 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005689}
5690
5691/// ActOnBlockError - If there is an error parsing a block, this callback
5692/// is invoked to pop the information about the block from the action impl.
5693void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5694 // Ensure that CurBlock is deleted.
5695 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005696
Chris Lattnere7765e12009-04-19 05:28:12 +00005697 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5698
Steve Naroff52a81c02008-09-03 18:15:37 +00005699 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005700 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005701 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005702 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005703}
5704
5705/// ActOnBlockStmtExpr - This is called when the body of a block statement
5706/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005707Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5708 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005709 // If blocks are disabled, emit an error.
5710 if (!LangOpts.Blocks)
5711 Diag(CaretLoc, diag::err_blocks_disable);
5712
Steve Naroff52a81c02008-09-03 18:15:37 +00005713 // Ensure that CurBlock is deleted.
5714 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005715
Steve Naroff52059382008-10-10 01:28:17 +00005716 PopDeclContext();
5717
Steve Naroff52a81c02008-09-03 18:15:37 +00005718 // Pop off CurBlock, handle nested blocks.
5719 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005720
Steve Naroff52a81c02008-09-03 18:15:37 +00005721 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005722 if (!BSI->ReturnType.isNull())
5723 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005724
Steve Naroff52a81c02008-09-03 18:15:37 +00005725 llvm::SmallVector<QualType, 8> ArgTypes;
5726 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5727 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005728
Mike Stump8e288f42009-07-28 22:04:01 +00005729 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005730 QualType BlockTy;
5731 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005732 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5733 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005734 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005735 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005736 BSI->isVariadic, 0, false, false, 0, 0,
5737 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005738
Eli Friedman2b128322009-03-23 00:24:07 +00005739 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005740 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005741 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005742
Chris Lattnere7765e12009-04-19 05:28:12 +00005743 // If needed, diagnose invalid gotos and switches in the block.
5744 if (CurFunctionNeedsScopeChecking)
5745 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5746 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5747
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005748 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005749 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005750 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5751 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005752}
5753
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005754Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5755 ExprArg expr, TypeTy *type,
5756 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005757 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005758 Expr *E = static_cast<Expr*>(expr.get());
5759 Expr *OrigExpr = E;
5760
Anders Carlsson36760332007-10-15 20:28:48 +00005761 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005762
5763 // Get the va_list type
5764 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005765 if (VaListType->isArrayType()) {
5766 // Deal with implicit array decay; for example, on x86-64,
5767 // va_list is an array, but it's supposed to decay to
5768 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005769 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005770 // Make sure the input expression also decays appropriately.
5771 UsualUnaryConversions(E);
5772 } else {
5773 // Otherwise, the va_list argument must be an l-value because
5774 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005775 if (!E->isTypeDependent() &&
5776 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005777 return ExprError();
5778 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005779
Douglas Gregor25990972009-05-19 23:10:31 +00005780 if (!E->isTypeDependent() &&
5781 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005782 return ExprError(Diag(E->getLocStart(),
5783 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005784 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005785 }
Mike Stump9afab102009-02-19 03:04:26 +00005786
Eli Friedman2b128322009-03-23 00:24:07 +00005787 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005788 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005789
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005790 expr.release();
5791 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5792 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005793}
5794
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005795Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005796 // The type of __null will be int or long, depending on the size of
5797 // pointers on the target.
5798 QualType Ty;
5799 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5800 Ty = Context.IntTy;
5801 else
5802 Ty = Context.LongTy;
5803
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005804 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005805}
5806
Chris Lattner005ed752008-01-04 18:04:52 +00005807bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5808 SourceLocation Loc,
5809 QualType DstType, QualType SrcType,
5810 Expr *SrcExpr, const char *Flavor) {
5811 // Decode the result (notice that AST's are still created for extensions).
5812 bool isInvalid = false;
5813 unsigned DiagKind;
5814 switch (ConvTy) {
5815 default: assert(0 && "Unknown conversion type");
5816 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005817 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005818 DiagKind = diag::ext_typecheck_convert_pointer_int;
5819 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005820 case IntToPointer:
5821 DiagKind = diag::ext_typecheck_convert_int_pointer;
5822 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005823 case IncompatiblePointer:
5824 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5825 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005826 case IncompatiblePointerSign:
5827 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5828 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005829 case FunctionVoidPointer:
5830 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5831 break;
5832 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005833 // If the qualifiers lost were because we were applying the
5834 // (deprecated) C++ conversion from a string literal to a char*
5835 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5836 // Ideally, this check would be performed in
5837 // CheckPointerTypesForAssignment. However, that would require a
5838 // bit of refactoring (so that the second argument is an
5839 // expression, rather than a type), which should be done as part
5840 // of a larger effort to fix CheckPointerTypesForAssignment for
5841 // C++ semantics.
5842 if (getLangOptions().CPlusPlus &&
5843 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5844 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005845 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5846 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005847 case IntToBlockPointer:
5848 DiagKind = diag::err_int_to_block_pointer;
5849 break;
5850 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005851 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005852 break;
Steve Naroff19608432008-10-14 22:18:38 +00005853 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005854 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005855 // it can give a more specific diagnostic.
5856 DiagKind = diag::warn_incompatible_qualified_id;
5857 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005858 case IncompatibleVectors:
5859 DiagKind = diag::warn_incompatible_vectors;
5860 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005861 case Incompatible:
5862 DiagKind = diag::err_typecheck_convert_incompatible;
5863 isInvalid = true;
5864 break;
5865 }
Mike Stump9afab102009-02-19 03:04:26 +00005866
Chris Lattner271d4c22008-11-24 05:29:24 +00005867 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5868 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005869 return isInvalid;
5870}
Anders Carlssond5201b92008-11-30 19:50:32 +00005871
Chris Lattnereec8ae22009-04-25 21:59:05 +00005872bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005873 llvm::APSInt ICEResult;
5874 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5875 if (Result)
5876 *Result = ICEResult;
5877 return false;
5878 }
5879
Anders Carlssond5201b92008-11-30 19:50:32 +00005880 Expr::EvalResult EvalResult;
5881
Mike Stump9afab102009-02-19 03:04:26 +00005882 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005883 EvalResult.HasSideEffects) {
5884 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5885
5886 if (EvalResult.Diag) {
5887 // We only show the note if it's not the usual "invalid subexpression"
5888 // or if it's actually in a subexpression.
5889 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5890 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5891 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5892 }
Mike Stump9afab102009-02-19 03:04:26 +00005893
Anders Carlssond5201b92008-11-30 19:50:32 +00005894 return true;
5895 }
5896
Eli Friedmance329412009-04-25 22:26:58 +00005897 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5898 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005899
Eli Friedmance329412009-04-25 22:26:58 +00005900 if (EvalResult.Diag &&
5901 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5902 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005903
Anders Carlssond5201b92008-11-30 19:50:32 +00005904 if (Result)
5905 *Result = EvalResult.Val.getInt();
5906 return false;
5907}
Douglas Gregor98189262009-06-19 23:52:42 +00005908
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005909Sema::ExpressionEvaluationContext
5910Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5911 // Introduce a new set of potentially referenced declarations to the stack.
5912 if (NewContext == PotentiallyPotentiallyEvaluated)
5913 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5914
5915 std::swap(ExprEvalContext, NewContext);
5916 return NewContext;
5917}
5918
5919void
5920Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5921 ExpressionEvaluationContext NewContext) {
5922 ExprEvalContext = NewContext;
5923
5924 if (OldContext == PotentiallyPotentiallyEvaluated) {
5925 // Mark any remaining declarations in the current position of the stack
5926 // as "referenced". If they were not meant to be referenced, semantic
5927 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5928 PotentiallyReferencedDecls RemainingDecls;
5929 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5930 PotentiallyReferencedDeclStack.pop_back();
5931
5932 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5933 IEnd = RemainingDecls.end();
5934 I != IEnd; ++I)
5935 MarkDeclarationReferenced(I->first, I->second);
5936 }
5937}
Douglas Gregor98189262009-06-19 23:52:42 +00005938
5939/// \brief Note that the given declaration was referenced in the source code.
5940///
5941/// This routine should be invoke whenever a given declaration is referenced
5942/// in the source code, and where that reference occurred. If this declaration
5943/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5944/// C99 6.9p3), then the declaration will be marked as used.
5945///
5946/// \param Loc the location where the declaration was referenced.
5947///
5948/// \param D the declaration that has been referenced by the source code.
5949void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5950 assert(D && "No declaration?");
5951
Douglas Gregorcad27f62009-06-22 23:06:13 +00005952 if (D->isUsed())
5953 return;
5954
Douglas Gregor98189262009-06-19 23:52:42 +00005955 // Mark a parameter declaration "used", regardless of whether we're in a
5956 // template or not.
5957 if (isa<ParmVarDecl>(D))
5958 D->setUsed(true);
5959
5960 // Do not mark anything as "used" within a dependent context; wait for
5961 // an instantiation.
5962 if (CurContext->isDependentContext())
5963 return;
5964
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005965 switch (ExprEvalContext) {
5966 case Unevaluated:
5967 // We are in an expression that is not potentially evaluated; do nothing.
5968 return;
5969
5970 case PotentiallyEvaluated:
5971 // We are in a potentially-evaluated expression, so this declaration is
5972 // "used"; handle this below.
5973 break;
5974
5975 case PotentiallyPotentiallyEvaluated:
5976 // We are in an expression that may be potentially evaluated; queue this
5977 // declaration reference until we know whether the expression is
5978 // potentially evaluated.
5979 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5980 return;
5981 }
5982
Douglas Gregor98189262009-06-19 23:52:42 +00005983 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005984 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005985 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005986 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5987 if (!Constructor->isUsed())
5988 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005989 } else if (Constructor->isImplicit() &&
5990 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005991 if (!Constructor->isUsed())
5992 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5993 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005994 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5995 if (Destructor->isImplicit() && !Destructor->isUsed())
5996 DefineImplicitDestructor(Loc, Destructor);
5997
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005998 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5999 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6000 MethodDecl->getOverloadedOperator() == OO_Equal) {
6001 if (!MethodDecl->isUsed())
6002 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6003 }
6004 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006005 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006006 // Implicit instantiation of function templates and member functions of
6007 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006008 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006009 // FIXME: distinguish between implicit instantiations of function
6010 // templates and explicit specializations (the latter don't get
6011 // instantiated, naturally).
6012 if (Function->getInstantiatedFromMemberFunction() ||
6013 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006014 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006015 }
6016
6017
Douglas Gregor98189262009-06-19 23:52:42 +00006018 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006019 Function->setUsed(true);
6020 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006021 }
Douglas Gregor98189262009-06-19 23:52:42 +00006022
6023 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006024 // Implicit instantiation of static data members of class templates.
6025 // FIXME: distinguish between implicit instantiations (which we need to
6026 // actually instantiate) and explicit specializations.
6027 if (Var->isStaticDataMember() &&
6028 Var->getInstantiatedFromStaticDataMember())
6029 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6030
Douglas Gregor98189262009-06-19 23:52:42 +00006031 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006032
Douglas Gregor98189262009-06-19 23:52:42 +00006033 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006034 return;
6035}
Douglas Gregor98189262009-06-19 23:52:42 +00006036}
6037