blob: 7d2e308349f9ee4e93a5eb0fb3cfc3fa867a9217 [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 Gregorbc2fb7f2009-09-03 21:38:09 +00001992 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1993 NamedDecl *FirstQualifierInScope) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001994 if (SS && SS->isInvalid())
1995 return ExprError();
1996
Nate Begemane85f43d2009-08-10 23:49:36 +00001997 // Since this might be a postfix expression, get rid of ParenListExprs.
1998 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1999
Anders Carlssonc154a722009-05-01 19:30:39 +00002000 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregor3e368512009-09-04 17:36:40 +00002001 assert(BaseExpr && "no base expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002002
Steve Naroff137e11d2007-12-16 21:42:28 +00002003 // Perform default conversions.
2004 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002005
Steve Naroff2cb66382007-07-26 03:11:44 +00002006 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002007 // If this is an Objective-C pseudo-builtin and a definition is provided then
2008 // use that.
2009 if (BaseType->isObjCIdType()) {
2010 // We have an 'id' type. Rather than fall through, we check if this
2011 // is a reference to 'isa'.
2012 if (BaseType != Context.ObjCIdRedefinitionType) {
2013 BaseType = Context.ObjCIdRedefinitionType;
2014 ImpCastExprToType(BaseExpr, BaseType);
2015 }
2016 } else if (BaseType->isObjCClassType() &&
Douglas Gregorcfa0a632009-08-31 21:16:32 +00002017 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall44663db2009-08-17 16:35:33 +00002018 BaseType = Context.ObjCClassRedefinitionType;
2019 ImpCastExprToType(BaseExpr, BaseType);
2020 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002021 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002022
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002023 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2024 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002025 if (OpKind == tok::arrow) {
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002026 if (BaseType->isDependentType()) {
2027 NestedNameSpecifier *Qualifier = 0;
2028 if (SS) {
2029 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2030 if (!FirstQualifierInScope)
2031 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2032 }
2033
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002034 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2035 BaseExpr, true,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002036 OpLoc,
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002037 Qualifier,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002038 SS? SS->getRange() : SourceRange(),
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002039 FirstQualifierInScope,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002040 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002041 MemberLoc));
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002042 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002043 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002044 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002045 else if (BaseType->isObjCObjectPointerType())
2046 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002047 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002048 return ExprError(Diag(MemberLoc,
2049 diag::err_typecheck_member_reference_arrow)
2050 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002051 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002052 if (BaseType->isDependentType()) {
2053 // Require that the base type isn't a pointer type
2054 // (so we'll report an error for)
2055 // T* t;
2056 // t.f;
2057 //
2058 // In Obj-C++, however, the above expression is valid, since it could be
2059 // accessing the 'f' property if T is an Obj-C interface. The extra check
2060 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002061 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002062
2063 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002064 !PT->getPointeeType()->isRecordType())) {
2065 NestedNameSpecifier *Qualifier = 0;
2066 if (SS) {
2067 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2068 if (!FirstQualifierInScope)
2069 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2070 }
2071
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002072 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2073 BaseExpr, false,
2074 OpLoc,
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002075 Qualifier,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002076 SS? SS->getRange() : SourceRange(),
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002077 FirstQualifierInScope,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002078 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002079 MemberLoc));
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002080 }
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002081 }
Chris Lattner4b009652007-07-25 00:24:17 +00002082 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002083
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002084 // Handle field access to simple records. This also handles access to fields
2085 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002086 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002087 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002088 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002089 PDiag(diag::err_typecheck_incomplete_tag)
2090 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002091 return ExprError();
2092
Douglas Gregorda61ad22009-08-06 03:17:00 +00002093 DeclContext *DC = RDecl;
2094 if (SS && SS->isSet()) {
2095 // If the member name was a qualified-id, look into the
2096 // nested-name-specifier.
2097 DC = computeDeclContext(*SS, false);
2098
2099 // FIXME: If DC is not computable, we should build a
2100 // CXXUnresolvedMemberExpr.
2101 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2102 }
2103
Steve Naroff2cb66382007-07-26 03:11:44 +00002104 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002105 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002106 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002107
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002108 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002109 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002110 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002111 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002112 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2113 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002114 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002115 }
2116
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002117 if (SS && SS->isSet()) {
2118 QualType BaseTypeCanon
2119 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2120 QualType MemberTypeCanon
2121 = Context.getCanonicalType(
2122 Context.getTypeDeclType(
2123 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2124
2125 if (BaseTypeCanon != MemberTypeCanon &&
2126 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2127 return ExprError(Diag(SS->getBeginLoc(),
2128 diag::err_not_direct_base_or_virtual)
2129 << MemberTypeCanon << BaseTypeCanon);
2130 }
2131
Chris Lattner84ad8332009-03-31 08:18:48 +00002132 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002133
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002134 // If the decl being referenced had an error, return an error for this
2135 // sub-expr without emitting another error, in order to avoid cascading
2136 // error cases.
2137 if (MemberDecl->isInvalidDecl())
2138 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002139
Douglas Gregoraa57e862009-02-18 21:56:37 +00002140 // Check the use of this field
2141 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2142 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002143
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002144 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002145 // We may have found a field within an anonymous union or struct
2146 // (C++ [class.union]).
2147 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002148 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002149 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002150
Douglas Gregor82d44772008-12-20 23:49:58 +00002151 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002152 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002153 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002154 MemberType = Ref->getPointeeType();
2155 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002156 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002157 unsigned combinedQualifiers =
2158 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002159 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002160 combinedQualifiers &= ~QualType::Const;
2161 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002162 if (BaseAddrSpace != MemberType.getAddressSpace())
2163 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002164 }
Eli Friedman76b49832008-02-06 22:48:16 +00002165
Douglas Gregorcad27f62009-06-22 23:06:13 +00002166 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002167 if (PerformObjectMemberConversion(BaseExpr, FD))
2168 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002169 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2170 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002171 }
2172
Douglas Gregorcad27f62009-06-22 23:06:13 +00002173 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2174 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002175 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2176 Var, MemberLoc,
2177 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002178 }
2179 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2180 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002181 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2182 MemberFn, MemberLoc,
2183 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002184 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002185 if (FunctionTemplateDecl *FunTmpl
2186 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2187 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregord33e3282009-09-01 00:37:14 +00002188
2189 if (HasExplicitTemplateArgs)
2190 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2191 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2192 SS? SS->getRange() : SourceRange(),
2193 FunTmpl, MemberLoc, true,
2194 LAngleLoc, ExplicitTemplateArgs,
2195 NumExplicitTemplateArgs, RAngleLoc,
2196 Context.OverloadTy));
2197
Douglas Gregore399ad42009-08-26 22:36:53 +00002198 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2199 FunTmpl, MemberLoc,
2200 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002201 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002202 if (OverloadedFunctionDecl *Ovl
Douglas Gregord33e3282009-09-01 00:37:14 +00002203 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2204 if (HasExplicitTemplateArgs)
2205 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2206 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2207 SS? SS->getRange() : SourceRange(),
2208 Ovl, MemberLoc, true,
2209 LAngleLoc, ExplicitTemplateArgs,
2210 NumExplicitTemplateArgs, RAngleLoc,
2211 Context.OverloadTy));
2212
Douglas Gregore399ad42009-08-26 22:36:53 +00002213 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2214 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregord33e3282009-09-01 00:37:14 +00002215 }
Douglas Gregorcad27f62009-06-22 23:06:13 +00002216 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2217 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002218 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2219 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002220 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002221 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002222 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002223 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002224
Douglas Gregor82d44772008-12-20 23:49:58 +00002225 // We found a declaration kind that we didn't expect. This is a
2226 // generic error message that tells the user that she can't refer
2227 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002228 return ExprError(Diag(MemberLoc,
2229 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002230 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002231 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002232
Douglas Gregor3e368512009-09-04 17:36:40 +00002233 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2234 // into a record type was handled above, any destructor we see here is a
2235 // pseudo-destructor.
2236 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2237 // C++ [expr.pseudo]p2:
2238 // The left hand side of the dot operator shall be of scalar type. The
2239 // left hand side of the arrow operator shall be of pointer to scalar
2240 // type.
2241 if (!BaseType->isScalarType())
2242 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2243 << BaseType << BaseExpr->getSourceRange());
2244
2245 // [...] The type designated by the pseudo-destructor-name shall be the
2246 // same as the object type.
2247 if (!MemberName.getCXXNameType()->isDependentType() &&
2248 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2249 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2250 << BaseType << MemberName.getCXXNameType()
2251 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2252
2253 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
2254 // the form
2255 //
2256 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2257 //
2258 // shall designate the same scalar type.
2259 //
2260 // FIXME: DPG can't see any way to trigger this particular clause, so it
2261 // isn't checked here.
2262
2263 // FIXME: We've lost the precise spelling of the type by going through
2264 // DeclarationName. Can we do better?
2265 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2266 OpKind == tok::arrow,
2267 OpLoc,
2268 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2269 SS? SS->getRange() : SourceRange(),
2270 MemberName.getCXXNameType(),
2271 MemberLoc));
2272 }
2273
Steve Naroff329ec222009-07-10 23:34:53 +00002274 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002275 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002276 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002277 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2278 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002279 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2280 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2281 ObjCMethodDecl *Getter;
2282 // FIXME: need to also look locally in the implementation.
2283 if ((Getter = IFace->lookupClassMethod(Sel))) {
2284 // Check the use of this method.
2285 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2286 return ExprError();
2287 }
2288 // If we found a getter then this may be a valid dot-reference, we
2289 // will look for the matching setter, in case it is needed.
2290 Selector SetterSel =
2291 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002292 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002293 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2294 if (!Setter) {
2295 // If this reference is in an @implementation, also check for 'private'
2296 // methods.
2297 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2298 }
2299 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002300 if (!Setter)
2301 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002302
2303 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2304 return ExprError();
2305
2306 if (Getter || Setter) {
2307 QualType PType;
2308
2309 if (Getter)
2310 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002311 else
2312 // Get the expression type from Setter's incoming parameter.
2313 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002314 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002315 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002316 Setter, MemberLoc, BaseExpr));
2317 }
2318 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002319 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002320 }
2321 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002322 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2323 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002324 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2325 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2326 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2327 const ObjCInterfaceType *IFaceT =
2328 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002329 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002330 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2331
Steve Naroff4e743962009-07-16 00:25:06 +00002332 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2333 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002334 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002335
2336 if (IV) {
2337 // If the decl being referenced had an error, return an error for this
2338 // sub-expr without emitting another error, in order to avoid cascading
2339 // error cases.
2340 if (IV->isInvalidDecl())
2341 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002342
Steve Naroff4e743962009-07-16 00:25:06 +00002343 // Check whether we can reference this field.
2344 if (DiagnoseUseOfDecl(IV, MemberLoc))
2345 return ExprError();
2346 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2347 IV->getAccessControl() != ObjCIvarDecl::Package) {
2348 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2349 if (ObjCMethodDecl *MD = getCurMethodDecl())
2350 ClassOfMethodDecl = MD->getClassInterface();
2351 else if (ObjCImpDecl && getCurFunctionDecl()) {
2352 // Case of a c-function declared inside an objc implementation.
2353 // FIXME: For a c-style function nested inside an objc implementation
2354 // class, there is no implementation context available, so we pass
2355 // down the context as argument to this routine. Ideally, this context
2356 // need be passed down in the AST node and somehow calculated from the
2357 // AST for a function decl.
2358 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2359 if (ObjCImplementationDecl *IMPD =
2360 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2361 ClassOfMethodDecl = IMPD->getClassInterface();
2362 else if (ObjCCategoryImplDecl* CatImplClass =
2363 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2364 ClassOfMethodDecl = CatImplClass->getClassInterface();
2365 }
2366
2367 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2368 if (ClassDeclared != IDecl ||
2369 ClassOfMethodDecl != ClassDeclared)
2370 Diag(MemberLoc, diag::error_private_ivar_access)
2371 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002372 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2373 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002374 Diag(MemberLoc, diag::error_protected_ivar_access)
2375 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002376 }
Steve Naroff4e743962009-07-16 00:25:06 +00002377
2378 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2379 MemberLoc, BaseExpr,
2380 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002381 }
Steve Naroff4e743962009-07-16 00:25:06 +00002382 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002383 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002384 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002385 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002386 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002387 // Handle properties on 'id' and qualified "id".
2388 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2389 BaseType->isObjCQualifiedIdType())) {
2390 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002391 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002392
Steve Naroff329ec222009-07-10 23:34:53 +00002393 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002394 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002395 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2396 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2397 // Check the use of this declaration
2398 if (DiagnoseUseOfDecl(PD, MemberLoc))
2399 return ExprError();
2400
2401 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2402 MemberLoc, BaseExpr));
2403 }
2404 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2405 // Check the use of this method.
2406 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2407 return ExprError();
2408
2409 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2410 OMD->getResultType(),
2411 OMD, OpLoc, MemberLoc,
2412 NULL, 0));
2413 }
2414 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002415
Steve Naroff329ec222009-07-10 23:34:53 +00002416 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002417 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002418 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002419 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2420 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002421 const ObjCObjectPointerType *OPT;
2422 if (OpKind == tok::period &&
2423 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2424 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2425 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002426 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002427
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002428 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002429 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002430 // Check whether we can reference this property.
2431 if (DiagnoseUseOfDecl(PD, MemberLoc))
2432 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002433 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002434 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002435 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002436 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2437 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002438 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002439 MemberLoc, BaseExpr));
2440 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002441 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002442 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2443 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002444 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002445 // Check whether we can reference this property.
2446 if (DiagnoseUseOfDecl(PD, MemberLoc))
2447 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002448
Steve Naroff774e4152009-01-21 00:14:39 +00002449 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002450 MemberLoc, BaseExpr));
2451 }
Steve Naroff329ec222009-07-10 23:34:53 +00002452 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2453 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002454 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002455 // Check whether we can reference this property.
2456 if (DiagnoseUseOfDecl(PD, MemberLoc))
2457 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002458
Steve Naroff329ec222009-07-10 23:34:53 +00002459 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2460 MemberLoc, BaseExpr));
2461 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002462 // If that failed, look for an "implicit" property by seeing if the nullary
2463 // selector is implemented.
2464
2465 // FIXME: The logic for looking up nullary and unary selectors should be
2466 // shared with the code in ActOnInstanceMessage.
2467
Anders Carlsson9935ab92009-08-26 18:25:21 +00002468 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002469 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002470
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002471 // If this reference is in an @implementation, check for 'private' methods.
2472 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002473 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002474
Steve Naroff04151f32008-10-22 19:16:27 +00002475 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002476 if (!Getter)
2477 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002478 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002479 // Check if we can reference this property.
2480 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2481 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002482 }
2483 // If we found a getter then this may be a valid dot-reference, we
2484 // will look for the matching setter, in case it is needed.
2485 Selector SetterSel =
2486 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002487 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002488 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002489 if (!Setter) {
2490 // If this reference is in an @implementation, also check for 'private'
2491 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002492 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002493 }
2494 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002495 if (!Setter)
2496 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002497
Steve Naroffdede0c92009-03-11 13:48:17 +00002498 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2499 return ExprError();
2500
2501 if (Getter || Setter) {
2502 QualType PType;
2503
2504 if (Getter)
2505 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002506 else
2507 // Get the expression type from Setter's incoming parameter.
2508 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002509 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002510 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002511 Setter, MemberLoc, BaseExpr));
2512 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002513 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002514 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002515 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002516
Steve Naroff29d293b2009-07-24 17:54:45 +00002517 // Handle the following exceptional case (*Obj).isa.
2518 if (OpKind == tok::period &&
2519 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002520 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002521 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2522 Context.getObjCIdType()));
2523
Chris Lattnera57cf472008-07-21 04:28:12 +00002524 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002525 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002526 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002527 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2528 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002529 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002530 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002531 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002532 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002533
Douglas Gregor762da552009-03-27 06:00:30 +00002534 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2535 << BaseType << BaseExpr->getSourceRange();
2536
2537 // If the user is trying to apply -> or . to a function or function
2538 // pointer, it's probably because they forgot parentheses to call
2539 // the function. Suggest the addition of those parentheses.
2540 if (BaseType == Context.OverloadTy ||
2541 BaseType->isFunctionType() ||
2542 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002543 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002544 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2545 Diag(Loc, diag::note_member_reference_needs_call)
2546 << CodeModificationHint::CreateInsertion(Loc, "()");
2547 }
2548
2549 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002550}
2551
Anders Carlsson9935ab92009-08-26 18:25:21 +00002552Action::OwningExprResult
2553Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2554 tok::TokenKind OpKind, SourceLocation MemberLoc,
2555 IdentifierInfo &Member,
2556 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2557 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2558 DeclarationName(&Member), ObjCImpDecl, SS);
2559}
2560
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002561Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2562 FunctionDecl *FD,
2563 ParmVarDecl *Param) {
2564 if (Param->hasUnparsedDefaultArg()) {
2565 Diag (CallLoc,
2566 diag::err_use_of_default_argument_to_function_declared_later) <<
2567 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2568 Diag(UnparsedDefaultArgLocs[Param],
2569 diag::note_default_argument_declared_here);
2570 } else {
2571 if (Param->hasUninstantiatedDefaultArg()) {
2572 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2573
2574 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002575 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson21d18f22009-09-05 05:14:19 +00002576
2577 InstantiatingTemplate Inst(*this, CallLoc, Param,
2578 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002579 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002580
John McCall0ba26ee2009-08-25 22:02:44 +00002581 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002582 if (Result.isInvalid())
2583 return ExprError();
2584
2585 if (SetParamDefaultArgument(Param, move(Result),
2586 /*FIXME:EqualLoc*/
2587 UninstExpr->getSourceRange().getBegin()))
2588 return ExprError();
2589 }
2590
2591 Expr *DefaultExpr = Param->getDefaultArg();
2592
2593 // If the default expression creates temporaries, we need to
2594 // push them to the current stack of expression temporaries so they'll
2595 // be properly destroyed.
2596 if (CXXExprWithTemporaries *E
2597 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2598 assert(!E->shouldDestroyTemporaries() &&
2599 "Can't destroy temporaries in a default argument expr!");
2600 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2601 ExprTemporaries.push_back(E->getTemporary(I));
2602 }
2603 }
2604
2605 // We already type-checked the argument, so we know it works.
2606 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2607}
2608
Douglas Gregor3257fb52008-12-22 05:46:06 +00002609/// ConvertArgumentsForCall - Converts the arguments specified in
2610/// Args/NumArgs to the parameter types of the function FDecl with
2611/// function prototype Proto. Call is the call expression itself, and
2612/// Fn is the function expression. For a C++ member function, this
2613/// routine does not attempt to convert the object argument. Returns
2614/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002615bool
2616Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002617 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002618 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002619 Expr **Args, unsigned NumArgs,
2620 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002621 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002622 // assignment, to the types of the corresponding parameter, ...
2623 unsigned NumArgsInProto = Proto->getNumArgs();
2624 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002625 bool Invalid = false;
2626
Douglas Gregor3257fb52008-12-22 05:46:06 +00002627 // If too few arguments are available (and we don't have default
2628 // arguments for the remaining parameters), don't make the call.
2629 if (NumArgs < NumArgsInProto) {
2630 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2631 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2632 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2633 // Use default arguments for missing arguments
2634 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002635 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002636 }
2637
2638 // If too many are passed and not variadic, error on the extras and drop
2639 // them.
2640 if (NumArgs > NumArgsInProto) {
2641 if (!Proto->isVariadic()) {
2642 Diag(Args[NumArgsInProto]->getLocStart(),
2643 diag::err_typecheck_call_too_many_args)
2644 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2645 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2646 Args[NumArgs-1]->getLocEnd());
2647 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002648 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002649 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002650 }
2651 NumArgsToCheck = NumArgsInProto;
2652 }
Mike Stump9afab102009-02-19 03:04:26 +00002653
Douglas Gregor3257fb52008-12-22 05:46:06 +00002654 // Continue to check argument types (even if we have too few/many args).
2655 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2656 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002657
Douglas Gregor3257fb52008-12-22 05:46:06 +00002658 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002659 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002660 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002661
Eli Friedman83dec9e2009-03-22 22:00:50 +00002662 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2663 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002664 PDiag(diag::err_call_incomplete_argument)
2665 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002666 return true;
2667
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002668 // Pass the argument.
2669 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2670 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002671 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002672 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002673
2674 OwningExprResult ArgExpr =
2675 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2676 FDecl, Param);
2677 if (ArgExpr.isInvalid())
2678 return true;
2679
2680 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002681 }
2682
Douglas Gregor3257fb52008-12-22 05:46:06 +00002683 Call->setArg(i, Arg);
2684 }
Mike Stump9afab102009-02-19 03:04:26 +00002685
Douglas Gregor3257fb52008-12-22 05:46:06 +00002686 // If this is a variadic call, handle args passed through "...".
2687 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002688 VariadicCallType CallType = VariadicFunction;
2689 if (Fn->getType()->isBlockPointerType())
2690 CallType = VariadicBlock; // Block
2691 else if (isa<MemberExpr>(Fn))
2692 CallType = VariadicMethod;
2693
Douglas Gregor3257fb52008-12-22 05:46:06 +00002694 // Promote the arguments (C99 6.5.2.2p7).
2695 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2696 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002697 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002698 Call->setArg(i, Arg);
2699 }
2700 }
2701
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002702 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002703}
2704
Steve Naroff87d58b42007-09-16 03:34:24 +00002705/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002706/// This provides the location of the left/right parens and a list of comma
2707/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002708Action::OwningExprResult
2709Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2710 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002711 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002712 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002713
2714 // Since this might be a postfix expression, get rid of ParenListExprs.
2715 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2716
Anders Carlssonc154a722009-05-01 19:30:39 +00002717 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002718 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002719 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002720 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002721 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002722 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002723
Douglas Gregor3257fb52008-12-22 05:46:06 +00002724 if (getLangOptions().CPlusPlus) {
Douglas Gregor3e368512009-09-04 17:36:40 +00002725 // If this is a pseudo-destructor expression, build the call immediately.
2726 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2727 if (NumArgs > 0) {
2728 // Pseudo-destructor calls should not have any arguments.
2729 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2730 << CodeModificationHint::CreateRemoval(
2731 SourceRange(Args[0]->getLocStart(),
2732 Args[NumArgs-1]->getLocEnd()));
2733
2734 for (unsigned I = 0; I != NumArgs; ++I)
2735 Args[I]->Destroy(Context);
2736
2737 NumArgs = 0;
2738 }
2739
2740 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2741 RParenLoc));
2742 }
2743
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002744 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002745 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002746 // FIXME: Will need to cache the results of name lookup (including ADL) in
2747 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002748 bool Dependent = false;
2749 if (Fn->isTypeDependent())
2750 Dependent = true;
2751 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2752 Dependent = true;
2753
2754 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002755 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002756 Context.DependentTy, RParenLoc));
2757
2758 // Determine whether this is a call to an object (C++ [over.call.object]).
2759 if (Fn->getType()->isRecordType())
2760 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2761 CommaLocs, RParenLoc));
2762
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002763 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002764 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2765 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2766 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2767 isa<CXXMethodDecl>(MemDecl) ||
2768 (isa<FunctionTemplateDecl>(MemDecl) &&
2769 isa<CXXMethodDecl>(
2770 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002771 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2772 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002773 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002774 }
2775
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002776 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002777 // Also, in C++, keep track of whether we should perform argument-dependent
2778 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002779 Expr *FnExpr = Fn;
2780 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002781 bool HasExplicitTemplateArgs = 0;
2782 const TemplateArgument *ExplicitTemplateArgs = 0;
2783 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002784 while (true) {
2785 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2786 FnExpr = IcExpr->getSubExpr();
2787 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002788 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002789 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002790 ADL = false;
2791 FnExpr = PExpr->getSubExpr();
2792 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002793 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002794 == UnaryOperator::AddrOf) {
2795 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002796 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002797 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2798 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002799 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002800 break;
Mike Stump9afab102009-02-19 03:04:26 +00002801 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002802 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2803 UnqualifiedName = DepName->getName();
2804 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002805 } else if (TemplateIdRefExpr *TemplateIdRef
2806 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2807 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002808 if (!NDecl)
2809 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002810 HasExplicitTemplateArgs = true;
2811 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2812 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2813
2814 // C++ [temp.arg.explicit]p6:
2815 // [Note: For simple function names, argument dependent lookup (3.4.2)
2816 // applies even when the function name is not visible within the
2817 // scope of the call. This is because the call still has the syntactic
2818 // form of a function call (3.4.1). But when a function template with
2819 // explicit template arguments is used, the call does not have the
2820 // correct syntactic form unless there is a function template with
2821 // that name visible at the point of the call. If no such name is
2822 // visible, the call is not syntactically well-formed and
2823 // argument-dependent lookup does not apply. If some such name is
2824 // visible, argument dependent lookup applies and additional function
2825 // templates may be found in other namespaces.
2826 //
2827 // The summary of this paragraph is that, if we get to this point and the
2828 // template-id was not a qualified name, then argument-dependent lookup
2829 // is still possible.
2830 if (TemplateIdRef->getQualifier())
2831 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002832 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002833 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002834 // Any kind of name that does not refer to a declaration (or
2835 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2836 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002837 break;
2838 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002839 }
Mike Stump9afab102009-02-19 03:04:26 +00002840
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002841 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002842 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002843 if (NDecl) {
2844 FDecl = dyn_cast<FunctionDecl>(NDecl);
2845 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002846 FDecl = FunctionTemplate->getTemplatedDecl();
2847 else
Douglas Gregor28857752009-06-30 22:34:41 +00002848 FDecl = dyn_cast<FunctionDecl>(NDecl);
2849 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002850 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002851
Douglas Gregorb60eb752009-06-25 22:08:12 +00002852 if (Ovl || FunctionTemplate ||
2853 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002854 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002855 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002856 ADL = false;
2857
Douglas Gregorfcb19192009-02-11 23:02:49 +00002858 // We don't perform ADL in C.
2859 if (!getLangOptions().CPlusPlus)
2860 ADL = false;
2861
Douglas Gregorb60eb752009-06-25 22:08:12 +00002862 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002863 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2864 HasExplicitTemplateArgs,
2865 ExplicitTemplateArgs,
2866 NumExplicitTemplateArgs,
2867 LParenLoc, Args, NumArgs, CommaLocs,
2868 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002869 if (!FDecl)
2870 return ExprError();
2871
2872 // Update Fn to refer to the actual function selected.
2873 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002874 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002875 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002876 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2877 QDRExpr->getLocation(),
2878 false, false,
2879 QDRExpr->getQualifierRange(),
2880 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002881 else
Mike Stump9afab102009-02-19 03:04:26 +00002882 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002883 Fn->getSourceRange().getBegin());
2884 Fn->Destroy(Context);
2885 Fn = NewFn;
2886 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002887 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002888
2889 // Promote the function operand.
2890 UsualUnaryConversions(Fn);
2891
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002892 // Make the call expr early, before semantic checks. This guarantees cleanup
2893 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002894 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2895 Args, NumArgs,
2896 Context.BoolTy,
2897 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002898
Steve Naroffd6163f32008-09-05 22:11:13 +00002899 const FunctionType *FuncT;
2900 if (!Fn->getType()->isBlockPointerType()) {
2901 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2902 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002903 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002904 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002905 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2906 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002907 FuncT = PT->getPointeeType()->getAsFunctionType();
2908 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002909 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002910 getAsFunctionType();
2911 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002912 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002913 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2914 << Fn->getType() << Fn->getSourceRange());
2915
Eli Friedman83dec9e2009-03-22 22:00:50 +00002916 // Check for a valid return type
2917 if (!FuncT->getResultType()->isVoidType() &&
2918 RequireCompleteType(Fn->getSourceRange().getBegin(),
2919 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002920 PDiag(diag::err_call_incomplete_return)
2921 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002922 return ExprError();
2923
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002924 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002925 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002926
Douglas Gregor4fa58902009-02-26 23:50:07 +00002927 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002928 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002929 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002930 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002931 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002932 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002933
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002934 if (FDecl) {
2935 // Check if we have too few/too many template arguments, based
2936 // on our knowledge of the function definition.
2937 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002938 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002939 const FunctionProtoType *Proto =
2940 Def->getType()->getAsFunctionProtoType();
2941 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2942 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2943 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2944 }
2945 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002946 }
2947
Steve Naroffdb65e052007-08-28 23:30:39 +00002948 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002949 for (unsigned i = 0; i != NumArgs; i++) {
2950 Expr *Arg = Args[i];
2951 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002952 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2953 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002954 PDiag(diag::err_call_incomplete_argument)
2955 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002956 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002957 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002958 }
Chris Lattner4b009652007-07-25 00:24:17 +00002959 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002960
Douglas Gregor3257fb52008-12-22 05:46:06 +00002961 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2962 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002963 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2964 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002965
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002966 // Check for sentinels
2967 if (NDecl)
2968 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002969
Chris Lattner2e64c072007-08-10 20:18:51 +00002970 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002971 if (FDecl) {
2972 if (CheckFunctionCall(FDecl, TheCall.get()))
2973 return ExprError();
2974
2975 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2976 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2977 } else if (NDecl) {
2978 if (CheckBlockCall(NDecl, TheCall.get()))
2979 return ExprError();
2980 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002981
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002982 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002983}
2984
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002985Action::OwningExprResult
2986Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2987 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002988 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002989 //FIXME: Preserve type source info.
2990 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002991 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002992 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002993 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002994
Eli Friedman8c2173d2008-05-20 05:22:08 +00002995 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002996 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002997 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2998 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002999 } else if (!literalType->isDependentType() &&
3000 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00003001 PDiag(diag::err_typecheck_decl_incomplete_type)
3002 << SourceRange(LParenLoc,
3003 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003004 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00003005
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003006 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003007 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003008 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00003009
Chris Lattnere5cb5862008-12-04 23:50:19 +00003010 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00003011 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00003012 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003013 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00003014 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003015 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00003016 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00003017 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00003018}
3019
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003020Action::OwningExprResult
3021Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003022 SourceLocation RBraceLoc) {
3023 unsigned NumInit = initlist.size();
3024 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00003025
Steve Naroff0acc9c92007-09-15 18:49:24 +00003026 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00003027 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003028
Mike Stump9afab102009-02-19 03:04:26 +00003029 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00003030 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00003031 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003032 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00003033}
3034
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003035/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00003036bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003037 CastExpr::CastKind& Kind,
3038 CXXMethodDecl *& ConversionDecl,
3039 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00003040 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003041 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3042 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00003043
Eli Friedman01e0f652009-08-15 19:02:19 +00003044 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003045
3046 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3047 // type needs to be scalar.
3048 if (castType->isVoidType()) {
3049 // Cast to void allows any expr type.
3050 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003051 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3052 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3053 (castType->isStructureType() || castType->isUnionType())) {
3054 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00003055 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003056 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3057 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003058 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003059 } else if (castType->isUnionType()) {
3060 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003061 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003062 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003063 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003064 Field != FieldEnd; ++Field) {
3065 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3066 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3067 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3068 << castExpr->getSourceRange();
3069 break;
3070 }
3071 }
3072 if (Field == FieldEnd)
3073 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3074 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003075 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003076 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003077 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003078 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003079 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003080 }
Mike Stump9afab102009-02-19 03:04:26 +00003081 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003082 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003083 return Diag(castExpr->getLocStart(),
3084 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003085 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003086 } else if (castType->isExtVectorType()) {
3087 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003088 return true;
3089 } else if (castType->isVectorType()) {
3090 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3091 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003092 } else if (castExpr->getType()->isVectorType()) {
3093 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3094 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003095 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003096 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003097 } else if (!castType->isArithmeticType()) {
3098 QualType castExprType = castExpr->getType();
3099 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3100 return Diag(castExpr->getLocStart(),
3101 diag::err_cast_pointer_from_non_pointer_int)
3102 << castExprType << castExpr->getSourceRange();
3103 } else if (!castExpr->getType()->isArithmeticType()) {
3104 if (!castType->isIntegralType() && castType->isArithmeticType())
3105 return Diag(castExpr->getLocStart(),
3106 diag::err_cast_pointer_to_non_pointer_int)
3107 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003108 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003109 if (isa<ObjCSelectorExpr>(castExpr))
3110 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003111 return false;
3112}
3113
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003114bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003115 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003116
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003117 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003118 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003119 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003120 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003121 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003122 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003123 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003124 } else
3125 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003126 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003127 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003128
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003129 return false;
3130}
3131
Nate Begemanbd42e022009-06-26 00:50:28 +00003132bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3133 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3134
Nate Begeman9e063702009-06-27 22:05:55 +00003135 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3136 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003137 if (SrcTy->isVectorType()) {
3138 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3139 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3140 << DestTy << SrcTy << R;
3141 return false;
3142 }
3143
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003144 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003145 // conversion will take place first from scalar to elt type, and then
3146 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003147 if (SrcTy->isPointerType())
3148 return Diag(R.getBegin(),
3149 diag::err_invalid_conversion_between_vector_and_scalar)
3150 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003151 return false;
3152}
3153
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003154Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003155Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003156 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003157 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3158
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003159 assert((Ty != 0) && (Op.get() != 0) &&
3160 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003161
Nate Begemane85f43d2009-08-10 23:49:36 +00003162 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003163 //FIXME: Preserve type source info.
3164 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003165
3166 // If the Expr being casted is a ParenListExpr, handle it specially.
3167 if (isa<ParenListExpr>(castExpr))
3168 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003169 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003170 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003171 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003172 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003173 if (ConversionDecl) {
3174 // encounterred a c-style cast requiring a conversion function.
3175 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3176 castExpr =
3177 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3178 castType, LParenLoc,
3179 CastExpr::CK_UserDefinedConversion,
3180 castExpr, CD,
3181 RParenLoc);
3182 Kind = CastExpr::CK_UserDefinedConversion;
3183 }
3184 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3185 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003186
3187 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003188 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003189 Kind, castExpr, castType,
3190 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003191}
3192
Nate Begemane85f43d2009-08-10 23:49:36 +00003193/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3194/// of comma binary operators.
3195Action::OwningExprResult
3196Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3197 Expr *expr = EA.takeAs<Expr>();
3198 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3199 if (!E)
3200 return Owned(expr);
3201
3202 OwningExprResult Result(*this, E->getExpr(0));
3203
3204 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3205 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3206 Owned(E->getExpr(i)));
3207
3208 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3209}
3210
3211Action::OwningExprResult
3212Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3213 SourceLocation RParenLoc, ExprArg Op,
3214 QualType Ty) {
3215 ParenListExpr *PE = (ParenListExpr *)Op.get();
3216
3217 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3218 // then handle it as such.
3219 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3220 if (PE->getNumExprs() == 0) {
3221 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3222 return ExprError();
3223 }
3224
3225 llvm::SmallVector<Expr *, 8> initExprs;
3226 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3227 initExprs.push_back(PE->getExpr(i));
3228
3229 // FIXME: This means that pretty-printing the final AST will produce curly
3230 // braces instead of the original commas.
3231 Op.release();
3232 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3233 initExprs.size(), RParenLoc);
3234 E->setType(Ty);
3235 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3236 Owned(E));
3237 } else {
3238 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3239 // sequence of BinOp comma operators.
3240 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3241 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3242 }
3243}
3244
3245Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3246 SourceLocation R,
3247 MultiExprArg Val) {
3248 unsigned nexprs = Val.size();
3249 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3250 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3251 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3252 return Owned(expr);
3253}
3254
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003255/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3256/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003257/// C99 6.5.15
3258QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3259 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003260 // C++ is sufficiently different to merit its own checker.
3261 if (getLangOptions().CPlusPlus)
3262 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3263
Chris Lattnere2897262009-02-18 04:28:32 +00003264 UsualUnaryConversions(Cond);
3265 UsualUnaryConversions(LHS);
3266 UsualUnaryConversions(RHS);
3267 QualType CondTy = Cond->getType();
3268 QualType LHSTy = LHS->getType();
3269 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003270
3271 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003272 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3273 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3274 << CondTy;
3275 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003276 }
Mike Stump9afab102009-02-19 03:04:26 +00003277
Chris Lattner992ae932008-01-06 22:42:25 +00003278 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003279 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3280 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003281
Chris Lattner992ae932008-01-06 22:42:25 +00003282 // If both operands have arithmetic type, do the usual arithmetic conversions
3283 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003284 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3285 UsualArithmeticConversions(LHS, RHS);
3286 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003287 }
Mike Stump9afab102009-02-19 03:04:26 +00003288
Chris Lattner992ae932008-01-06 22:42:25 +00003289 // If both operands are the same structure or union type, the result is that
3290 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003291 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3292 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003293 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003294 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003295 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003296 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003297 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003298 }
Mike Stump9afab102009-02-19 03:04:26 +00003299
Chris Lattner992ae932008-01-06 22:42:25 +00003300 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003301 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003302 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3303 if (!LHSTy->isVoidType())
3304 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3305 << RHS->getSourceRange();
3306 if (!RHSTy->isVoidType())
3307 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3308 << LHS->getSourceRange();
3309 ImpCastExprToType(LHS, Context.VoidTy);
3310 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003311 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003312 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003313 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3314 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003315 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003316 RHS->isNullPointerConstant(Context)) {
3317 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3318 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003319 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003320 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003321 LHS->isNullPointerConstant(Context)) {
3322 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3323 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003324 }
David Chisnall44663db2009-08-17 16:35:33 +00003325 // Handle things like Class and struct objc_class*. Here we case the result
3326 // to the pseudo-builtin, because that will be implicitly cast back to the
3327 // redefinition type if an attempt is made to access its fields.
3328 if (LHSTy->isObjCClassType() &&
3329 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3330 ImpCastExprToType(RHS, LHSTy);
3331 return LHSTy;
3332 }
3333 if (RHSTy->isObjCClassType() &&
3334 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3335 ImpCastExprToType(LHS, RHSTy);
3336 return RHSTy;
3337 }
3338 // And the same for struct objc_object* / id
3339 if (LHSTy->isObjCIdType() &&
3340 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3341 ImpCastExprToType(RHS, LHSTy);
3342 return LHSTy;
3343 }
3344 if (RHSTy->isObjCIdType() &&
3345 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3346 ImpCastExprToType(LHS, RHSTy);
3347 return RHSTy;
3348 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003349 // Handle block pointer types.
3350 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3351 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3352 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3353 QualType destType = Context.getPointerType(Context.VoidTy);
3354 ImpCastExprToType(LHS, destType);
3355 ImpCastExprToType(RHS, destType);
3356 return destType;
3357 }
3358 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3359 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3360 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003361 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003362 // We have 2 block pointer types.
3363 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3364 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003365 return LHSTy;
3366 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003367 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003368 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3369 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003370
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003371 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3372 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003373 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3374 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3375 // In this situation, we assume void* type. No especially good
3376 // reason, but this is what gcc does, and we do have to pick
3377 // to get a consistent AST.
3378 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3379 ImpCastExprToType(LHS, incompatTy);
3380 ImpCastExprToType(RHS, incompatTy);
3381 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003382 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003383 // The block pointer types are compatible.
3384 ImpCastExprToType(LHS, LHSTy);
3385 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003386 return LHSTy;
3387 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003388 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003389 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003390
3391 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3392 // Two identical object pointer types are always compatible.
3393 return LHSTy;
3394 }
Steve Naroff329ec222009-07-10 23:34:53 +00003395 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3396 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003397 QualType compositeType = LHSTy;
3398
3399 // If both operands are interfaces and either operand can be
3400 // assigned to the other, use that type as the composite
3401 // type. This allows
3402 // xxx ? (A*) a : (B*) b
3403 // where B is a subclass of A.
3404 //
3405 // Additionally, as for assignment, if either type is 'id'
3406 // allow silent coercion. Finally, if the types are
3407 // incompatible then make sure to use 'id' as the composite
3408 // type so the result is acceptable for sending messages to.
3409
3410 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3411 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003412 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003413 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003414 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003415 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003416 } else if ((LHSTy->isObjCQualifiedIdType() ||
3417 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003418 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003419 // Need to handle "id<xx>" explicitly.
3420 // GCC allows qualified id and any Objective-C type to devolve to
3421 // id. Currently localizing to here until clear this should be
3422 // part of ObjCQualifiedIdTypesAreCompatible.
3423 compositeType = Context.getObjCIdType();
3424 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003425 compositeType = Context.getObjCIdType();
3426 } else {
3427 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3428 << LHSTy << RHSTy
3429 << LHS->getSourceRange() << RHS->getSourceRange();
3430 QualType incompatTy = Context.getObjCIdType();
3431 ImpCastExprToType(LHS, incompatTy);
3432 ImpCastExprToType(RHS, incompatTy);
3433 return incompatTy;
3434 }
3435 // The object pointer types are compatible.
3436 ImpCastExprToType(LHS, compositeType);
3437 ImpCastExprToType(RHS, compositeType);
3438 return compositeType;
3439 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003440 // Check Objective-C object pointer types and 'void *'
3441 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003442 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003443 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3444 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3445 QualType destType = Context.getPointerType(destPointee);
3446 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3447 ImpCastExprToType(RHS, destType); // promote to void*
3448 return destType;
3449 }
3450 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3451 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003452 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003453 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3454 QualType destType = Context.getPointerType(destPointee);
3455 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3456 ImpCastExprToType(LHS, destType); // promote to void*
3457 return destType;
3458 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003459 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3460 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3461 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003462 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3463 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003464
3465 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3466 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3467 // Figure out necessary qualifiers (C99 6.5.15p6)
3468 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3469 QualType destType = Context.getPointerType(destPointee);
3470 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3471 ImpCastExprToType(RHS, destType); // promote to void*
3472 return destType;
3473 }
3474 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3475 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3476 QualType destType = Context.getPointerType(destPointee);
3477 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3478 ImpCastExprToType(RHS, destType); // promote to void*
3479 return destType;
3480 }
3481
3482 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3483 // Two identical pointer types are always compatible.
3484 return LHSTy;
3485 }
3486 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3487 rhptee.getUnqualifiedType())) {
3488 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3489 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3490 // In this situation, we assume void* type. No especially good
3491 // reason, but this is what gcc does, and we do have to pick
3492 // to get a consistent AST.
3493 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3494 ImpCastExprToType(LHS, incompatTy);
3495 ImpCastExprToType(RHS, incompatTy);
3496 return incompatTy;
3497 }
3498 // The pointer types are compatible.
3499 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3500 // differently qualified versions of compatible types, the result type is
3501 // a pointer to an appropriately qualified version of the *composite*
3502 // type.
3503 // FIXME: Need to calculate the composite type.
3504 // FIXME: Need to add qualifiers
3505 ImpCastExprToType(LHS, LHSTy);
3506 ImpCastExprToType(RHS, LHSTy);
3507 return LHSTy;
3508 }
3509
3510 // GCC compatibility: soften pointer/integer mismatch.
3511 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3512 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3513 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3514 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3515 return RHSTy;
3516 }
3517 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3518 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3519 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3520 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3521 return LHSTy;
3522 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003523
Chris Lattner992ae932008-01-06 22:42:25 +00003524 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003525 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3526 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003527 return QualType();
3528}
3529
Steve Naroff87d58b42007-09-16 03:34:24 +00003530/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003531/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003532Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3533 SourceLocation ColonLoc,
3534 ExprArg Cond, ExprArg LHS,
3535 ExprArg RHS) {
3536 Expr *CondExpr = (Expr *) Cond.get();
3537 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003538
3539 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3540 // was the condition.
3541 bool isLHSNull = LHSExpr == 0;
3542 if (isLHSNull)
3543 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003544
3545 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003546 RHSExpr, QuestionLoc);
3547 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003548 return ExprError();
3549
3550 Cond.release();
3551 LHS.release();
3552 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003553 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003554 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003555 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003556}
3557
Chris Lattner4b009652007-07-25 00:24:17 +00003558// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003559// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003560// routine is it effectively iqnores the qualifiers on the top level pointee.
3561// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3562// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003563Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003564Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3565 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003566
David Chisnall44663db2009-08-17 16:35:33 +00003567 if ((lhsType->isObjCClassType() &&
3568 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3569 (rhsType->isObjCClassType() &&
3570 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3571 return Compatible;
3572 }
3573
Chris Lattner4b009652007-07-25 00:24:17 +00003574 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003575 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3576 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003577
Chris Lattner4b009652007-07-25 00:24:17 +00003578 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003579 lhptee = Context.getCanonicalType(lhptee);
3580 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003581
Chris Lattner005ed752008-01-04 18:04:52 +00003582 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003583
3584 // C99 6.5.16.1p1: This following citation is common to constraints
3585 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3586 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003587 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003588 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003589 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003590
Mike Stump9afab102009-02-19 03:04:26 +00003591 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3592 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003593 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003594 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003595 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003596 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003597
Chris Lattner4ca3d772008-01-03 22:56:36 +00003598 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003599 assert(rhptee->isFunctionType());
3600 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003601 }
Mike Stump9afab102009-02-19 03:04:26 +00003602
Chris Lattner4ca3d772008-01-03 22:56:36 +00003603 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003604 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003605 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003606
3607 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003608 assert(lhptee->isFunctionType());
3609 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003610 }
Mike Stump9afab102009-02-19 03:04:26 +00003611 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003612 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003613 lhptee = lhptee.getUnqualifiedType();
3614 rhptee = rhptee.getUnqualifiedType();
3615 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3616 // Check if the pointee types are compatible ignoring the sign.
3617 // We explicitly check for char so that we catch "char" vs
3618 // "unsigned char" on systems where "char" is unsigned.
3619 if (lhptee->isCharType()) {
3620 lhptee = Context.UnsignedCharTy;
3621 } else if (lhptee->isSignedIntegerType()) {
3622 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3623 }
3624 if (rhptee->isCharType()) {
3625 rhptee = Context.UnsignedCharTy;
3626 } else if (rhptee->isSignedIntegerType()) {
3627 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3628 }
3629 if (lhptee == rhptee) {
3630 // Types are compatible ignoring the sign. Qualifier incompatibility
3631 // takes priority over sign incompatibility because the sign
3632 // warning can be disabled.
3633 if (ConvTy != Compatible)
3634 return ConvTy;
3635 return IncompatiblePointerSign;
3636 }
3637 // General pointer incompatibility takes priority over qualifiers.
3638 return IncompatiblePointer;
3639 }
Chris Lattner005ed752008-01-04 18:04:52 +00003640 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003641}
3642
Steve Naroff3454b6c2008-09-04 15:10:53 +00003643/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3644/// block pointer types are compatible or whether a block and normal pointer
3645/// are compatible. It is more restrict than comparing two function pointer
3646// types.
Mike Stump9afab102009-02-19 03:04:26 +00003647Sema::AssignConvertType
3648Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003649 QualType rhsType) {
3650 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003651
Steve Naroff3454b6c2008-09-04 15:10:53 +00003652 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003653 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3654 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003655
Steve Naroff3454b6c2008-09-04 15:10:53 +00003656 // make sure we operate on the canonical type
3657 lhptee = Context.getCanonicalType(lhptee);
3658 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003659
Steve Naroff3454b6c2008-09-04 15:10:53 +00003660 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003661
Steve Naroff3454b6c2008-09-04 15:10:53 +00003662 // For blocks we enforce that qualifiers are identical.
3663 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3664 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003665
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003666 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003667 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003668 return ConvTy;
3669}
3670
Mike Stump9afab102009-02-19 03:04:26 +00003671/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3672/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003673/// pointers. Here are some objectionable examples that GCC considers warnings:
3674///
3675/// int a, *pint;
3676/// short *pshort;
3677/// struct foo *pfoo;
3678///
3679/// pint = pshort; // warning: assignment from incompatible pointer type
3680/// a = pint; // warning: assignment makes integer from pointer without a cast
3681/// pint = a; // warning: assignment makes pointer from integer without a cast
3682/// pint = pfoo; // warning: assignment from incompatible pointer type
3683///
3684/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003685/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003686///
Chris Lattner005ed752008-01-04 18:04:52 +00003687Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003688Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003689 // Get canonical types. We're not formatting these types, just comparing
3690 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003691 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3692 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003693
3694 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003695 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003696
David Chisnall44663db2009-08-17 16:35:33 +00003697 if ((lhsType->isObjCClassType() &&
3698 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3699 (rhsType->isObjCClassType() &&
3700 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3701 return Compatible;
3702 }
3703
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003704 // If the left-hand side is a reference type, then we are in a
3705 // (rare!) case where we've allowed the use of references in C,
3706 // e.g., as a parameter type in a built-in function. In this case,
3707 // just make sure that the type referenced is compatible with the
3708 // right-hand side type. The caller is responsible for adjusting
3709 // lhsType so that the resulting expression does not have reference
3710 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003711 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003712 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003713 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003714 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003715 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003716 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3717 // to the same ExtVector type.
3718 if (lhsType->isExtVectorType()) {
3719 if (rhsType->isExtVectorType())
3720 return lhsType == rhsType ? Compatible : Incompatible;
3721 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3722 return Compatible;
3723 }
3724
Nate Begemanc5f0f652008-07-14 18:02:46 +00003725 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003726 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003727 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003728 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003729 if (getLangOptions().LaxVectorConversions &&
3730 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003731 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003732 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003733 }
3734 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003735 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003736
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003737 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003738 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003739
Chris Lattner390564e2008-04-07 06:49:41 +00003740 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003741 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003742 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003743
Chris Lattner390564e2008-04-07 06:49:41 +00003744 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003745 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003746
Steve Naroff8194a542009-07-20 17:56:53 +00003747 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003748 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003749 if (lhsType->isVoidPointerType()) // an exception to the rule.
3750 return Compatible;
3751 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003752 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003753 if (rhsType->getAs<BlockPointerType>()) {
3754 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003755 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003756
3757 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003758 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003759 return Compatible;
3760 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003761 return Incompatible;
3762 }
3763
3764 if (isa<BlockPointerType>(lhsType)) {
3765 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003766 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003767
Steve Naroffa982c712008-09-29 18:10:17 +00003768 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003769 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003770 return Compatible;
3771
Steve Naroff3454b6c2008-09-04 15:10:53 +00003772 if (rhsType->isBlockPointerType())
3773 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003774
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003775 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003776 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003777 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003778 }
Chris Lattner1853da22008-01-04 23:18:45 +00003779 return Incompatible;
3780 }
3781
Steve Naroff329ec222009-07-10 23:34:53 +00003782 if (isa<ObjCObjectPointerType>(lhsType)) {
3783 if (rhsType->isIntegerType())
3784 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003785
3786 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003787 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003788 if (rhsType->isVoidPointerType()) // an exception to the rule.
3789 return Compatible;
3790 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003791 }
3792 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003793 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3794 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003795 if (Context.typesAreCompatible(lhsType, rhsType))
3796 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003797 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3798 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003799 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003800 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003801 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003802 if (RHSPT->getPointeeType()->isVoidType())
3803 return Compatible;
3804 }
3805 // Treat block pointers as objects.
3806 if (rhsType->isBlockPointerType())
3807 return Compatible;
3808 return Incompatible;
3809 }
Chris Lattner390564e2008-04-07 06:49:41 +00003810 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003811 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003812 if (lhsType == Context.BoolTy)
3813 return Compatible;
3814
3815 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003816 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003817
Mike Stump9afab102009-02-19 03:04:26 +00003818 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003819 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003820
3821 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003822 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003823 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003824 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003825 }
Steve Naroff329ec222009-07-10 23:34:53 +00003826 if (isa<ObjCObjectPointerType>(rhsType)) {
3827 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3828 if (lhsType == Context.BoolTy)
3829 return Compatible;
3830
3831 if (lhsType->isIntegerType())
3832 return PointerToInt;
3833
Steve Naroff8194a542009-07-20 17:56:53 +00003834 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003835 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003836 if (lhsType->isVoidPointerType()) // an exception to the rule.
3837 return Compatible;
3838 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003839 }
3840 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003841 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003842 return Compatible;
3843 return Incompatible;
3844 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003845
Chris Lattner1853da22008-01-04 23:18:45 +00003846 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003847 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003848 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003849 }
3850 return Incompatible;
3851}
3852
Douglas Gregor144b06c2009-04-29 22:16:16 +00003853/// \brief Constructs a transparent union from an expression that is
3854/// used to initialize the transparent union.
3855static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3856 QualType UnionType, FieldDecl *Field) {
3857 // Build an initializer list that designates the appropriate member
3858 // of the transparent union.
3859 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3860 &E, 1,
3861 SourceLocation());
3862 Initializer->setType(UnionType);
3863 Initializer->setInitializedFieldInUnion(Field);
3864
3865 // Build a compound literal constructing a value of the transparent
3866 // union type from this initializer list.
3867 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3868 false);
3869}
3870
3871Sema::AssignConvertType
3872Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3873 QualType FromType = rExpr->getType();
3874
3875 // If the ArgType is a Union type, we want to handle a potential
3876 // transparent_union GCC extension.
3877 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003878 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003879 return Incompatible;
3880
3881 // The field to initialize within the transparent union.
3882 RecordDecl *UD = UT->getDecl();
3883 FieldDecl *InitField = 0;
3884 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003885 for (RecordDecl::field_iterator it = UD->field_begin(),
3886 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003887 it != itend; ++it) {
3888 if (it->getType()->isPointerType()) {
3889 // If the transparent union contains a pointer type, we allow:
3890 // 1) void pointer
3891 // 2) null pointer constant
3892 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003893 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003894 ImpCastExprToType(rExpr, it->getType());
3895 InitField = *it;
3896 break;
3897 }
3898
3899 if (rExpr->isNullPointerConstant(Context)) {
3900 ImpCastExprToType(rExpr, it->getType());
3901 InitField = *it;
3902 break;
3903 }
3904 }
3905
3906 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3907 == Compatible) {
3908 InitField = *it;
3909 break;
3910 }
3911 }
3912
3913 if (!InitField)
3914 return Incompatible;
3915
3916 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3917 return Compatible;
3918}
3919
Chris Lattner005ed752008-01-04 18:04:52 +00003920Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003921Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003922 if (getLangOptions().CPlusPlus) {
3923 if (!lhsType->isRecordType()) {
3924 // C++ 5.17p3: If the left operand is not of class type, the
3925 // expression is implicitly converted (C++ 4) to the
3926 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003927 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3928 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003929 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003930 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003931 }
3932
3933 // FIXME: Currently, we fall through and treat C++ classes like C
3934 // structures.
3935 }
3936
Steve Naroffcdee22d2007-11-27 17:58:44 +00003937 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3938 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003939 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003940 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003941 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003942 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003943 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003944 return Compatible;
3945 }
Mike Stump9afab102009-02-19 03:04:26 +00003946
Chris Lattner5f505bf2007-10-16 02:55:40 +00003947 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003948 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003949 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003950 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003951 //
Mike Stump9afab102009-02-19 03:04:26 +00003952 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003953 if (!lhsType->isReferenceType())
3954 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003955
Chris Lattner005ed752008-01-04 18:04:52 +00003956 Sema::AssignConvertType result =
3957 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003958
Steve Naroff0f32f432007-08-24 22:33:52 +00003959 // C99 6.5.16.1p2: The value of the right operand is converted to the
3960 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003961 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3962 // so that we can use references in built-in functions even in C.
3963 // The getNonReferenceType() call makes sure that the resulting expression
3964 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003965 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003966 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003967 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003968}
3969
Chris Lattner1eafdea2008-11-18 01:30:42 +00003970QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003971 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003972 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003973 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003974 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003975}
3976
Mike Stump9afab102009-02-19 03:04:26 +00003977inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003978 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003979 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003980 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003981 QualType lhsType =
3982 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3983 QualType rhsType =
3984 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003985
Nate Begemanc5f0f652008-07-14 18:02:46 +00003986 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003987 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003988 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003989
Nate Begemanc5f0f652008-07-14 18:02:46 +00003990 // Handle the case of a vector & extvector type of the same size and element
3991 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003992 if (getLangOptions().LaxVectorConversions) {
3993 // FIXME: Should we warn here?
3994 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003995 if (const VectorType *RV = rhsType->getAsVectorType())
3996 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003997 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003998 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003999 }
4000 }
4001 }
Mike Stump9afab102009-02-19 03:04:26 +00004002
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004003 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4004 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4005 bool swapped = false;
4006 if (rhsType->isExtVectorType()) {
4007 swapped = true;
4008 std::swap(rex, lex);
4009 std::swap(rhsType, lhsType);
4010 }
4011
Nate Begemanf1695892009-06-28 19:12:57 +00004012 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004013 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4014 QualType EltTy = LV->getElementType();
4015 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4016 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00004017 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004018 if (swapped) std::swap(rex, lex);
4019 return lhsType;
4020 }
4021 }
4022 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4023 rhsType->isRealFloatingType()) {
4024 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00004025 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004026 if (swapped) std::swap(rex, lex);
4027 return lhsType;
4028 }
Nate Begemanec2d1062007-12-30 02:59:45 +00004029 }
4030 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004031
Nate Begemanf1695892009-06-28 19:12:57 +00004032 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00004033 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004034 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00004035 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004036 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00004037}
4038
Chris Lattner4b009652007-07-25 00:24:17 +00004039inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004040 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004041{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00004042 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004043 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004044
Steve Naroff8f708362007-08-24 19:07:16 +00004045 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004046
Chris Lattner4b009652007-07-25 00:24:17 +00004047 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00004048 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004049 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004050}
4051
4052inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004053 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004054{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00004055 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4056 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4057 return CheckVectorOperands(Loc, lex, rex);
4058 return InvalidOperands(Loc, lex, rex);
4059 }
Chris Lattner4b009652007-07-25 00:24:17 +00004060
Steve Naroff8f708362007-08-24 19:07:16 +00004061 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004062
Chris Lattner4b009652007-07-25 00:24:17 +00004063 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004064 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004065 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004066}
4067
4068inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004069 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004070{
Eli Friedman3cd92882009-03-28 01:22:36 +00004071 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4072 QualType compType = CheckVectorOperands(Loc, lex, rex);
4073 if (CompLHSTy) *CompLHSTy = compType;
4074 return compType;
4075 }
Chris Lattner4b009652007-07-25 00:24:17 +00004076
Eli Friedman3cd92882009-03-28 01:22:36 +00004077 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004078
Chris Lattner4b009652007-07-25 00:24:17 +00004079 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004080 if (lex->getType()->isArithmeticType() &&
4081 rex->getType()->isArithmeticType()) {
4082 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004083 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004084 }
Chris Lattner4b009652007-07-25 00:24:17 +00004085
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004086 // Put any potential pointer into PExp
4087 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004088 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004089 std::swap(PExp, IExp);
4090
Steve Naroff79ae19a2009-07-14 18:25:06 +00004091 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004092
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004093 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004094 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004095
Chris Lattner184f92d2009-04-24 23:50:08 +00004096 // Check for arithmetic on pointers to incomplete types.
4097 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004098 if (getLangOptions().CPlusPlus) {
4099 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004100 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004101 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004102 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004103
4104 // GNU extension: arithmetic on pointer to void
4105 Diag(Loc, diag::ext_gnu_void_ptr)
4106 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004107 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004108 if (getLangOptions().CPlusPlus) {
4109 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4110 << lex->getType() << lex->getSourceRange();
4111 return QualType();
4112 }
4113
4114 // GNU extension: arithmetic on pointer to function
4115 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4116 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004117 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004118 // Check if we require a complete type.
4119 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004120 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004121 PExp->getType()->isObjCObjectPointerType()) &&
4122 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004123 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4124 << PExp->getSourceRange()
4125 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004126 return QualType();
4127 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004128 // Diagnose bad cases where we step over interface counts.
4129 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4130 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4131 << PointeeTy << PExp->getSourceRange();
4132 return QualType();
4133 }
4134
Eli Friedman3cd92882009-03-28 01:22:36 +00004135 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004136 QualType LHSTy = Context.isPromotableBitField(lex);
4137 if (LHSTy.isNull()) {
4138 LHSTy = lex->getType();
4139 if (LHSTy->isPromotableIntegerType())
4140 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004141 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004142 *CompLHSTy = LHSTy;
4143 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004144 return PExp->getType();
4145 }
4146 }
4147
Chris Lattner1eafdea2008-11-18 01:30:42 +00004148 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004149}
4150
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004151// C99 6.5.6
4152QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004153 SourceLocation Loc, QualType* CompLHSTy) {
4154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4155 QualType compType = CheckVectorOperands(Loc, lex, rex);
4156 if (CompLHSTy) *CompLHSTy = compType;
4157 return compType;
4158 }
Mike Stump9afab102009-02-19 03:04:26 +00004159
Eli Friedman3cd92882009-03-28 01:22:36 +00004160 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004161
Chris Lattnerf6da2912007-12-09 21:53:25 +00004162 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004163
Chris Lattnerf6da2912007-12-09 21:53:25 +00004164 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004165 if (lex->getType()->isArithmeticType()
4166 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004167 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004168 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004169 }
Steve Naroff329ec222009-07-10 23:34:53 +00004170
Chris Lattnerf6da2912007-12-09 21:53:25 +00004171 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004172 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004173 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004174
Douglas Gregor05e28f62009-03-24 19:52:54 +00004175 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004176
Douglas Gregor05e28f62009-03-24 19:52:54 +00004177 bool ComplainAboutVoid = false;
4178 Expr *ComplainAboutFunc = 0;
4179 if (lpointee->isVoidType()) {
4180 if (getLangOptions().CPlusPlus) {
4181 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4182 << lex->getSourceRange() << rex->getSourceRange();
4183 return QualType();
4184 }
4185
4186 // GNU C extension: arithmetic on pointer to void
4187 ComplainAboutVoid = true;
4188 } else if (lpointee->isFunctionType()) {
4189 if (getLangOptions().CPlusPlus) {
4190 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004191 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004192 return QualType();
4193 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004194
4195 // GNU C extension: arithmetic on pointer to function
4196 ComplainAboutFunc = lex;
4197 } else if (!lpointee->isDependentType() &&
4198 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004199 PDiag(diag::err_typecheck_sub_ptr_object)
4200 << lex->getSourceRange()
4201 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004202 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004203
Chris Lattner184f92d2009-04-24 23:50:08 +00004204 // Diagnose bad cases where we step over interface counts.
4205 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4206 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4207 << lpointee << lex->getSourceRange();
4208 return QualType();
4209 }
4210
Chris Lattnerf6da2912007-12-09 21:53:25 +00004211 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004212 if (rex->getType()->isIntegerType()) {
4213 if (ComplainAboutVoid)
4214 Diag(Loc, diag::ext_gnu_void_ptr)
4215 << lex->getSourceRange() << rex->getSourceRange();
4216 if (ComplainAboutFunc)
4217 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4218 << ComplainAboutFunc->getType()
4219 << ComplainAboutFunc->getSourceRange();
4220
Eli Friedman3cd92882009-03-28 01:22:36 +00004221 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004222 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004223 }
Mike Stump9afab102009-02-19 03:04:26 +00004224
Chris Lattnerf6da2912007-12-09 21:53:25 +00004225 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004226 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004227 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004228
Douglas Gregor05e28f62009-03-24 19:52:54 +00004229 // RHS must be a completely-type object type.
4230 // Handle the GNU void* extension.
4231 if (rpointee->isVoidType()) {
4232 if (getLangOptions().CPlusPlus) {
4233 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4234 << lex->getSourceRange() << rex->getSourceRange();
4235 return QualType();
4236 }
Mike Stump9afab102009-02-19 03:04:26 +00004237
Douglas Gregor05e28f62009-03-24 19:52:54 +00004238 ComplainAboutVoid = true;
4239 } else if (rpointee->isFunctionType()) {
4240 if (getLangOptions().CPlusPlus) {
4241 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004242 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004243 return QualType();
4244 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004245
4246 // GNU extension: arithmetic on pointer to function
4247 if (!ComplainAboutFunc)
4248 ComplainAboutFunc = rex;
4249 } else if (!rpointee->isDependentType() &&
4250 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004251 PDiag(diag::err_typecheck_sub_ptr_object)
4252 << rex->getSourceRange()
4253 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004254 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004255
Eli Friedman143ddc92009-05-16 13:54:38 +00004256 if (getLangOptions().CPlusPlus) {
4257 // Pointee types must be the same: C++ [expr.add]
4258 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4259 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4260 << lex->getType() << rex->getType()
4261 << lex->getSourceRange() << rex->getSourceRange();
4262 return QualType();
4263 }
4264 } else {
4265 // Pointee types must be compatible C99 6.5.6p3
4266 if (!Context.typesAreCompatible(
4267 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4268 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4269 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4270 << lex->getType() << rex->getType()
4271 << lex->getSourceRange() << rex->getSourceRange();
4272 return QualType();
4273 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004274 }
Mike Stump9afab102009-02-19 03:04:26 +00004275
Douglas Gregor05e28f62009-03-24 19:52:54 +00004276 if (ComplainAboutVoid)
4277 Diag(Loc, diag::ext_gnu_void_ptr)
4278 << lex->getSourceRange() << rex->getSourceRange();
4279 if (ComplainAboutFunc)
4280 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4281 << ComplainAboutFunc->getType()
4282 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004283
4284 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004285 return Context.getPointerDiffType();
4286 }
4287 }
Mike Stump9afab102009-02-19 03:04:26 +00004288
Chris Lattner1eafdea2008-11-18 01:30:42 +00004289 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004290}
4291
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004292// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004293QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004294 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004295 // C99 6.5.7p2: Each of the operands shall have integer type.
4296 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004297 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004298
Chris Lattner2c8bff72007-12-12 05:47:28 +00004299 // Shifts don't perform usual arithmetic conversions, they just do integer
4300 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004301 QualType LHSTy = Context.isPromotableBitField(lex);
4302 if (LHSTy.isNull()) {
4303 LHSTy = lex->getType();
4304 if (LHSTy->isPromotableIntegerType())
4305 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004306 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004307 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004308 ImpCastExprToType(lex, LHSTy);
4309
Chris Lattner2c8bff72007-12-12 05:47:28 +00004310 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004311
Ryan Flynnf109fff2009-08-07 16:20:20 +00004312 // Sanity-check shift operands
4313 llvm::APSInt Right;
4314 // Check right/shifter operand
4315 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004316 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004317 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4318 else {
4319 llvm::APInt LeftBits(Right.getBitWidth(),
4320 Context.getTypeSize(lex->getType()));
4321 if (Right.uge(LeftBits))
4322 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4323 }
4324 }
4325
Chris Lattner2c8bff72007-12-12 05:47:28 +00004326 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004327 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004328}
4329
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004330// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004331QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004332 unsigned OpaqueOpc, bool isRelational) {
4333 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4334
Nate Begemanc5f0f652008-07-14 18:02:46 +00004335 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004336 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004337
Chris Lattner254f3bc2007-08-26 01:18:55 +00004338 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004339 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4340 UsualArithmeticConversions(lex, rex);
4341 else {
4342 UsualUnaryConversions(lex);
4343 UsualUnaryConversions(rex);
4344 }
Chris Lattner4b009652007-07-25 00:24:17 +00004345 QualType lType = lex->getType();
4346 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004347
Mike Stumpea3d74e2009-05-07 18:43:07 +00004348 if (!lType->isFloatingType()
4349 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004350 // For non-floating point types, check for self-comparisons of the form
4351 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4352 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004353 // NOTE: Don't warn about comparisons of enum constants. These can arise
4354 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004355 Expr *LHSStripped = lex->IgnoreParens();
4356 Expr *RHSStripped = rex->IgnoreParens();
4357 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4358 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004359 if (DRL->getDecl() == DRR->getDecl() &&
4360 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004361 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004362
4363 if (isa<CastExpr>(LHSStripped))
4364 LHSStripped = LHSStripped->IgnoreParenCasts();
4365 if (isa<CastExpr>(RHSStripped))
4366 RHSStripped = RHSStripped->IgnoreParenCasts();
4367
4368 // Warn about comparisons against a string constant (unless the other
4369 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004370 Expr *literalString = 0;
4371 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004372 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004373 !RHSStripped->isNullPointerConstant(Context)) {
4374 literalString = lex;
4375 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004376 } else if ((isa<StringLiteral>(RHSStripped) ||
4377 isa<ObjCEncodeExpr>(RHSStripped)) &&
4378 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004379 literalString = rex;
4380 literalStringStripped = RHSStripped;
4381 }
4382
4383 if (literalString) {
4384 std::string resultComparison;
4385 switch (Opc) {
4386 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4387 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4388 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4389 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4390 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4391 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4392 default: assert(false && "Invalid comparison operator");
4393 }
4394 Diag(Loc, diag::warn_stringcompare)
4395 << isa<ObjCEncodeExpr>(literalStringStripped)
4396 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004397 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4398 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4399 "strcmp(")
4400 << CodeModificationHint::CreateInsertion(
4401 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004402 resultComparison);
4403 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004404 }
Mike Stump9afab102009-02-19 03:04:26 +00004405
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004406 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004407 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004408
Chris Lattner254f3bc2007-08-26 01:18:55 +00004409 if (isRelational) {
4410 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004411 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004412 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004413 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004414 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004415 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004416 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004417 }
Mike Stump9afab102009-02-19 03:04:26 +00004418
Chris Lattner254f3bc2007-08-26 01:18:55 +00004419 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004420 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004421 }
Mike Stump9afab102009-02-19 03:04:26 +00004422
Chris Lattner22be8422007-08-26 01:10:14 +00004423 bool LHSIsNull = lex->isNullPointerConstant(Context);
4424 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004425
Chris Lattner254f3bc2007-08-26 01:18:55 +00004426 // All of the following pointer related warnings are GCC extensions, except
4427 // when handling null pointer constants. One day, we can consider making them
4428 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004429 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004430 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004431 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004432 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004433 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004434
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004435 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004436 if (LCanPointeeTy == RCanPointeeTy)
4437 return ResultTy;
4438
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004439 // C++ [expr.rel]p2:
4440 // [...] Pointer conversions (4.10) and qualification
4441 // conversions (4.4) are performed on pointer operands (or on
4442 // a pointer operand and a null pointer constant) to bring
4443 // them to their composite pointer type. [...]
4444 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004445 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004446 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004447 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004448 if (T.isNull()) {
4449 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4450 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4451 return QualType();
4452 }
4453
4454 ImpCastExprToType(lex, T);
4455 ImpCastExprToType(rex, T);
4456 return ResultTy;
4457 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004458 // C99 6.5.9p2 and C99 6.5.8p2
4459 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4460 RCanPointeeTy.getUnqualifiedType())) {
4461 // Valid unless a relational comparison of function pointers
4462 if (isRelational && LCanPointeeTy->isFunctionType()) {
4463 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4464 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4465 }
4466 } else if (!isRelational &&
4467 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4468 // Valid unless comparison between non-null pointer and function pointer
4469 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4470 && !LHSIsNull && !RHSIsNull) {
4471 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4472 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4473 }
4474 } else {
4475 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004476 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004477 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004478 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004479 if (LCanPointeeTy != RCanPointeeTy)
4480 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004481 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004482 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004483
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004484 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004485 // Comparison of pointers with null pointer constants and equality
4486 // comparisons of member pointers to null pointer constants.
4487 if (RHSIsNull &&
4488 (lType->isPointerType() ||
4489 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004490 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004491 return ResultTy;
4492 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004493 if (LHSIsNull &&
4494 (rType->isPointerType() ||
4495 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004496 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004497 return ResultTy;
4498 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004499
4500 // Comparison of member pointers.
4501 if (!isRelational &&
4502 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4503 // C++ [expr.eq]p2:
4504 // In addition, pointers to members can be compared, or a pointer to
4505 // member and a null pointer constant. Pointer to member conversions
4506 // (4.11) and qualification conversions (4.4) are performed to bring
4507 // them to a common type. If one operand is a null pointer constant,
4508 // the common type is the type of the other operand. Otherwise, the
4509 // common type is a pointer to member type similar (4.4) to the type
4510 // of one of the operands, with a cv-qualification signature (4.4)
4511 // that is the union of the cv-qualification signatures of the operand
4512 // types.
4513 QualType T = FindCompositePointerType(lex, rex);
4514 if (T.isNull()) {
4515 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4516 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4517 return QualType();
4518 }
4519
4520 ImpCastExprToType(lex, T);
4521 ImpCastExprToType(rex, T);
4522 return ResultTy;
4523 }
4524
4525 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004526 if (lType->isNullPtrType() && rType->isNullPtrType())
4527 return ResultTy;
4528 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004529
Steve Naroff3454b6c2008-09-04 15:10:53 +00004530 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004531 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004532 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4533 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004534
Steve Naroff3454b6c2008-09-04 15:10:53 +00004535 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004536 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004537 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004538 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004539 }
4540 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004541 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004542 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004543 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004544 if (!isRelational
4545 && ((lType->isBlockPointerType() && rType->isPointerType())
4546 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004547 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004548 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004549 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004550 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004551 ->getPointeeType()->isVoidType())))
4552 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4553 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004554 }
4555 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004556 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004557 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004558
Steve Naroff329ec222009-07-10 23:34:53 +00004559 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004560 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004561 const PointerType *LPT = lType->getAs<PointerType>();
4562 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004563 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004564 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004565 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004566 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004567
Steve Naroff030fcda2008-11-17 19:49:16 +00004568 if (!LPtrToVoid && !RPtrToVoid &&
4569 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004570 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004571 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004572 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004573 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004574 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004575 }
Steve Naroff329ec222009-07-10 23:34:53 +00004576 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004577 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004578 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4579 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004580 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004581 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004582 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004583 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004584 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004585 unsigned DiagID = 0;
4586 if (RHSIsNull) {
4587 if (isRelational)
4588 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4589 } else if (isRelational)
4590 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4591 else
4592 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4593
4594 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004595 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004596 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004597 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004598 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004599 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004600 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004601 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004602 unsigned DiagID = 0;
4603 if (LHSIsNull) {
4604 if (isRelational)
4605 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4606 } else if (isRelational)
4607 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4608 else
4609 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004610
Chris Lattner124569f2009-08-23 00:03:44 +00004611 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004612 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004613 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004614 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004615 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004616 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004617 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004618 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004619 if (!isRelational && RHSIsNull
4620 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004621 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004622 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004623 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004624 if (!isRelational && LHSIsNull
4625 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004626 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004627 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004628 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004629 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004630}
4631
Nate Begemanc5f0f652008-07-14 18:02:46 +00004632/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004633/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004634/// like a scalar comparison, a vector comparison produces a vector of integer
4635/// types.
4636QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004637 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004638 bool isRelational) {
4639 // Check to make sure we're operating on vectors of the same type and width,
4640 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004641 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004642 if (vType.isNull())
4643 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004644
Nate Begemanc5f0f652008-07-14 18:02:46 +00004645 QualType lType = lex->getType();
4646 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004647
Nate Begemanc5f0f652008-07-14 18:02:46 +00004648 // For non-floating point types, check for self-comparisons of the form
4649 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4650 // often indicate logic errors in the program.
4651 if (!lType->isFloatingType()) {
4652 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4653 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4654 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004655 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004656 }
Mike Stump9afab102009-02-19 03:04:26 +00004657
Nate Begemanc5f0f652008-07-14 18:02:46 +00004658 // Check for comparisons of floating point operands using != and ==.
4659 if (!isRelational && lType->isFloatingType()) {
4660 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004661 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004662 }
Mike Stump9afab102009-02-19 03:04:26 +00004663
Nate Begemanc5f0f652008-07-14 18:02:46 +00004664 // Return the type for the comparison, which is the same as vector type for
4665 // integer vectors, or an integer type of identical size and number of
4666 // elements for floating point vectors.
4667 if (lType->isIntegerType())
4668 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004669
Nate Begemanc5f0f652008-07-14 18:02:46 +00004670 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004671 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004672 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004673 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004674 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004675 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4676
Mike Stump9afab102009-02-19 03:04:26 +00004677 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004678 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004679 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4680}
4681
Chris Lattner4b009652007-07-25 00:24:17 +00004682inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004683 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004684{
4685 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004686 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004687
Steve Naroff8f708362007-08-24 19:07:16 +00004688 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004689
Chris Lattner4b009652007-07-25 00:24:17 +00004690 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004691 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004692 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004693}
4694
4695inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004696 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004697{
4698 UsualUnaryConversions(lex);
4699 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004700
Eli Friedmanbea3f842008-05-13 20:16:47 +00004701 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004702 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004703 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004704}
4705
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004706/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4707/// is a read-only property; return true if so. A readonly property expression
4708/// depends on various declarations and thus must be treated specially.
4709///
Mike Stump9afab102009-02-19 03:04:26 +00004710static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004711{
4712 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4713 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4714 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4715 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004716 if (const ObjCObjectPointerType *OPT =
4717 BaseType->getAsObjCInterfacePointerType())
4718 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4719 if (S.isPropertyReadonly(PDecl, IFace))
4720 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004721 }
4722 }
4723 return false;
4724}
4725
Chris Lattner4c2642c2008-11-18 01:22:49 +00004726/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4727/// emit an error and return true. If so, return false.
4728static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004729 SourceLocation OrigLoc = Loc;
4730 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4731 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004732 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4733 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004734 if (IsLV == Expr::MLV_Valid)
4735 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004736
Chris Lattner4c2642c2008-11-18 01:22:49 +00004737 unsigned Diag = 0;
4738 bool NeedType = false;
4739 switch (IsLV) { // C99 6.5.16p2
4740 default: assert(0 && "Unknown result from isModifiableLvalue!");
4741 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004742 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004743 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4744 NeedType = true;
4745 break;
Mike Stump9afab102009-02-19 03:04:26 +00004746 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004747 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4748 NeedType = true;
4749 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004750 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004751 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4752 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004753 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004754 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4755 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004756 case Expr::MLV_IncompleteType:
4757 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004758 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004759 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4760 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004761 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004762 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4763 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004764 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004765 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4766 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004767 case Expr::MLV_ReadonlyProperty:
4768 Diag = diag::error_readonly_property_assignment;
4769 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004770 case Expr::MLV_NoSetterProperty:
4771 Diag = diag::error_nosetter_property_assignment;
4772 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004773 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004774
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004775 SourceRange Assign;
4776 if (Loc != OrigLoc)
4777 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004778 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004779 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004780 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004781 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004782 return true;
4783}
4784
4785
4786
4787// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004788QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4789 SourceLocation Loc,
4790 QualType CompoundType) {
4791 // Verify that LHS is a modifiable lvalue, and emit error if not.
4792 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004793 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004794
4795 QualType LHSType = LHS->getType();
4796 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004797
Chris Lattner005ed752008-01-04 18:04:52 +00004798 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004799 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004800 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004801 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004802 // Special case of NSObject attributes on c-style pointer types.
4803 if (ConvTy == IncompatiblePointer &&
4804 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004805 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004806 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004807 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004808 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004809
Chris Lattner34c85082008-08-21 18:04:13 +00004810 // If the RHS is a unary plus or minus, check to see if they = and + are
4811 // right next to each other. If so, the user may have typo'd "x =+ 4"
4812 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004813 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004814 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4815 RHSCheck = ICE->getSubExpr();
4816 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4817 if ((UO->getOpcode() == UnaryOperator::Plus ||
4818 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004819 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004820 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004821 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4822 // And there is a space or other character before the subexpr of the
4823 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004824 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4825 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004826 Diag(Loc, diag::warn_not_compound_assign)
4827 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4828 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004829 }
Chris Lattner34c85082008-08-21 18:04:13 +00004830 }
4831 } else {
4832 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004833 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004834 }
Chris Lattner005ed752008-01-04 18:04:52 +00004835
Chris Lattner1eafdea2008-11-18 01:30:42 +00004836 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4837 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004838 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004839
Chris Lattner4b009652007-07-25 00:24:17 +00004840 // C99 6.5.16p3: The type of an assignment expression is the type of the
4841 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004842 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004843 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4844 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004845 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004846 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004847 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004848}
4849
Chris Lattner1eafdea2008-11-18 01:30:42 +00004850// C99 6.5.17
4851QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004852 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004853 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004854
4855 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4856 // incomplete in C++).
4857
Chris Lattner1eafdea2008-11-18 01:30:42 +00004858 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004859}
4860
4861/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4862/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004863QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4864 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004865 if (Op->isTypeDependent())
4866 return Context.DependentTy;
4867
Chris Lattnere65182c2008-11-21 07:05:48 +00004868 QualType ResType = Op->getType();
4869 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004870
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004871 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4872 // Decrement of bool is not allowed.
4873 if (!isInc) {
4874 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4875 return QualType();
4876 }
4877 // Increment of bool sets it to true, but is deprecated.
4878 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4879 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004880 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004881 } else if (ResType->isAnyPointerType()) {
4882 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004883
Chris Lattnere65182c2008-11-21 07:05:48 +00004884 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004885 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004886 if (getLangOptions().CPlusPlus) {
4887 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4888 << Op->getSourceRange();
4889 return QualType();
4890 }
4891
4892 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004893 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004894 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004895 if (getLangOptions().CPlusPlus) {
4896 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4897 << Op->getType() << Op->getSourceRange();
4898 return QualType();
4899 }
4900
4901 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004902 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004903 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004904 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4905 << Op->getSourceRange()
4906 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004907 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004908 // Diagnose bad cases where we step over interface counts.
4909 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4910 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4911 << PointeeTy << Op->getSourceRange();
4912 return QualType();
4913 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004914 } else if (ResType->isComplexType()) {
4915 // C99 does not support ++/-- on complex types, we allow as an extension.
4916 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004917 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004918 } else {
4919 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004920 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004921 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004922 }
Mike Stump9afab102009-02-19 03:04:26 +00004923 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004924 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004925 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004926 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004927 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004928}
4929
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004930/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004931/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004932/// where the declaration is needed for type checking. We only need to
4933/// handle cases when the expression references a function designator
4934/// or is an lvalue. Here are some examples:
4935/// - &(x) => x
4936/// - &*****f => f for f a function designator.
4937/// - &s.xx => s
4938/// - &s.zz[1].yy -> s, if zz is an array
4939/// - *(x + 1) -> x, if x is an array
4940/// - &"123"[2] -> 0
4941/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004942static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004943 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004944 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004945 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004946 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004947 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004948 // If this is an arrow operator, the address is an offset from
4949 // the base's value, so the object the base refers to is
4950 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004951 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004952 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004953 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004954 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004955 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004956 // FIXME: This code shouldn't be necessary! We should catch the implicit
4957 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004958 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4959 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4960 if (ICE->getSubExpr()->getType()->isArrayType())
4961 return getPrimaryDecl(ICE->getSubExpr());
4962 }
4963 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004964 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004965 case Stmt::UnaryOperatorClass: {
4966 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004967
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004968 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004969 case UnaryOperator::Real:
4970 case UnaryOperator::Imag:
4971 case UnaryOperator::Extension:
4972 return getPrimaryDecl(UO->getSubExpr());
4973 default:
4974 return 0;
4975 }
4976 }
Chris Lattner4b009652007-07-25 00:24:17 +00004977 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004978 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004979 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004980 // If the result of an implicit cast is an l-value, we care about
4981 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004982 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004983 default:
4984 return 0;
4985 }
4986}
4987
4988/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004989/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004990/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004991/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004992/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004993/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004994/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004995QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004996 // Make sure to ignore parentheses in subsequent checks
4997 op = op->IgnoreParens();
4998
Douglas Gregore6be68a2008-12-17 22:52:20 +00004999 if (op->isTypeDependent())
5000 return Context.DependentTy;
5001
Steve Naroff9c6c3592008-01-13 17:10:08 +00005002 if (getLangOptions().C99) {
5003 // Implement C99-only parts of addressof rules.
5004 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5005 if (uOp->getOpcode() == UnaryOperator::Deref)
5006 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5007 // (assuming the deref expression is valid).
5008 return uOp->getSubExpr()->getType();
5009 }
5010 // Technically, there should be a check for array subscript
5011 // expressions here, but the result of one is always an lvalue anyway.
5012 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00005013 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00005014 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00005015
Eli Friedman14ab4c42009-05-16 23:27:50 +00005016 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5017 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00005018 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00005019 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00005020 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00005021 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5022 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005023 return QualType();
5024 }
Douglas Gregor531434b2009-05-02 02:18:30 +00005025 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00005026 // The operand cannot be a bit-field
5027 Diag(OpLoc, diag::err_typecheck_address_of)
5028 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00005029 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00005030 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5031 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00005032 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00005033 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00005034 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00005035 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00005036 } else if (isa<ObjCPropertyRefExpr>(op)) {
5037 // cannot take address of a property expression.
5038 Diag(OpLoc, diag::err_typecheck_address_of)
5039 << "property expression" << op->getSourceRange();
5040 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00005041 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00005042 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00005043 // with the register storage-class specifier.
5044 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5045 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00005046 Diag(OpLoc, diag::err_typecheck_address_of)
5047 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005048 return QualType();
5049 }
Douglas Gregor62f78762009-07-08 20:55:45 +00005050 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5051 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00005052 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00005053 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00005054 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00005055 // Could be a pointer to member, though, if there is an explicit
5056 // scope qualifier for the class.
5057 if (isa<QualifiedDeclRefExpr>(op)) {
5058 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00005059 if (Ctx && Ctx->isRecord()) {
5060 if (FD->getType()->isReferenceType()) {
5061 Diag(OpLoc,
5062 diag::err_cannot_form_pointer_to_member_of_reference_type)
5063 << FD->getDeclName() << FD->getType();
5064 return QualType();
5065 }
5066
Sebastian Redl0c9da212009-02-03 20:19:35 +00005067 return Context.getMemberPointerType(op->getType(),
5068 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00005069 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00005070 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005071 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00005072 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00005073 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005074 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5075 return Context.getMemberPointerType(op->getType(),
5076 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5077 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00005078 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00005079 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00005080
Eli Friedman14ab4c42009-05-16 23:27:50 +00005081 if (lval == Expr::LV_IncompleteVoidType) {
5082 // Taking the address of a void variable is technically illegal, but we
5083 // allow it in cases which are otherwise valid.
5084 // Example: "extern void x; void* y = &x;".
5085 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5086 }
5087
Chris Lattner4b009652007-07-25 00:24:17 +00005088 // If the operand has type "type", the result has type "pointer to type".
5089 return Context.getPointerType(op->getType());
5090}
5091
Chris Lattnerda5c0872008-11-23 09:13:29 +00005092QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005093 if (Op->isTypeDependent())
5094 return Context.DependentTy;
5095
Chris Lattnerda5c0872008-11-23 09:13:29 +00005096 UsualUnaryConversions(Op);
5097 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005098
Chris Lattnerda5c0872008-11-23 09:13:29 +00005099 // Note that per both C89 and C99, this is always legal, even if ptype is an
5100 // incomplete type or void. It would be possible to warn about dereferencing
5101 // a void pointer, but it's completely well-defined, and such a warning is
5102 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005103 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005104 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005105
Fariborz Jahanian81699d92009-09-03 00:43:07 +00005106 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5107 return OPT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00005108
Chris Lattner77d52da2008-11-20 06:06:08 +00005109 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005110 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005111 return QualType();
5112}
5113
5114static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5115 tok::TokenKind Kind) {
5116 BinaryOperator::Opcode Opc;
5117 switch (Kind) {
5118 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005119 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5120 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005121 case tok::star: Opc = BinaryOperator::Mul; break;
5122 case tok::slash: Opc = BinaryOperator::Div; break;
5123 case tok::percent: Opc = BinaryOperator::Rem; break;
5124 case tok::plus: Opc = BinaryOperator::Add; break;
5125 case tok::minus: Opc = BinaryOperator::Sub; break;
5126 case tok::lessless: Opc = BinaryOperator::Shl; break;
5127 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5128 case tok::lessequal: Opc = BinaryOperator::LE; break;
5129 case tok::less: Opc = BinaryOperator::LT; break;
5130 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5131 case tok::greater: Opc = BinaryOperator::GT; break;
5132 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5133 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5134 case tok::amp: Opc = BinaryOperator::And; break;
5135 case tok::caret: Opc = BinaryOperator::Xor; break;
5136 case tok::pipe: Opc = BinaryOperator::Or; break;
5137 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5138 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5139 case tok::equal: Opc = BinaryOperator::Assign; break;
5140 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5141 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5142 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5143 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5144 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5145 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5146 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5147 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5148 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5149 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5150 case tok::comma: Opc = BinaryOperator::Comma; break;
5151 }
5152 return Opc;
5153}
5154
5155static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5156 tok::TokenKind Kind) {
5157 UnaryOperator::Opcode Opc;
5158 switch (Kind) {
5159 default: assert(0 && "Unknown unary op!");
5160 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5161 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5162 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5163 case tok::star: Opc = UnaryOperator::Deref; break;
5164 case tok::plus: Opc = UnaryOperator::Plus; break;
5165 case tok::minus: Opc = UnaryOperator::Minus; break;
5166 case tok::tilde: Opc = UnaryOperator::Not; break;
5167 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005168 case tok::kw___real: Opc = UnaryOperator::Real; break;
5169 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5170 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5171 }
5172 return Opc;
5173}
5174
Douglas Gregord7f915e2008-11-06 23:29:22 +00005175/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5176/// operator @p Opc at location @c TokLoc. This routine only supports
5177/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005178Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5179 unsigned Op,
5180 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005181 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005182 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005183 // The following two variables are used for compound assignment operators
5184 QualType CompLHSTy; // Type of LHS after promotions for computation
5185 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005186
5187 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005188 case BinaryOperator::Assign:
5189 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5190 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005191 case BinaryOperator::PtrMemD:
5192 case BinaryOperator::PtrMemI:
5193 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5194 Opc == BinaryOperator::PtrMemI);
5195 break;
5196 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005197 case BinaryOperator::Div:
5198 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5199 break;
5200 case BinaryOperator::Rem:
5201 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5202 break;
5203 case BinaryOperator::Add:
5204 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5205 break;
5206 case BinaryOperator::Sub:
5207 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5208 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005209 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005210 case BinaryOperator::Shr:
5211 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5212 break;
5213 case BinaryOperator::LE:
5214 case BinaryOperator::LT:
5215 case BinaryOperator::GE:
5216 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005217 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005218 break;
5219 case BinaryOperator::EQ:
5220 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005221 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005222 break;
5223 case BinaryOperator::And:
5224 case BinaryOperator::Xor:
5225 case BinaryOperator::Or:
5226 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5227 break;
5228 case BinaryOperator::LAnd:
5229 case BinaryOperator::LOr:
5230 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5231 break;
5232 case BinaryOperator::MulAssign:
5233 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005234 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5235 CompLHSTy = CompResultTy;
5236 if (!CompResultTy.isNull())
5237 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005238 break;
5239 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005240 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5241 CompLHSTy = CompResultTy;
5242 if (!CompResultTy.isNull())
5243 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005244 break;
5245 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005246 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5247 if (!CompResultTy.isNull())
5248 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005249 break;
5250 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005251 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5252 if (!CompResultTy.isNull())
5253 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005254 break;
5255 case BinaryOperator::ShlAssign:
5256 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005257 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5258 CompLHSTy = CompResultTy;
5259 if (!CompResultTy.isNull())
5260 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005261 break;
5262 case BinaryOperator::AndAssign:
5263 case BinaryOperator::XorAssign:
5264 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005265 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5266 CompLHSTy = CompResultTy;
5267 if (!CompResultTy.isNull())
5268 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005269 break;
5270 case BinaryOperator::Comma:
5271 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5272 break;
5273 }
5274 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005275 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005276 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005277 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5278 else
5279 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005280 CompLHSTy, CompResultTy,
5281 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005282}
5283
Chris Lattner4b009652007-07-25 00:24:17 +00005284// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005285Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5286 tok::TokenKind Kind,
5287 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005288 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005289 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005290
Steve Naroff87d58b42007-09-16 03:34:24 +00005291 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5292 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005293
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005294 if (getLangOptions().CPlusPlus &&
5295 (lhs->getType()->isOverloadableType() ||
5296 rhs->getType()->isOverloadableType())) {
5297 // Find all of the overloaded operators visible from this
5298 // point. We perform both an operator-name lookup from the local
5299 // scope and an argument-dependent lookup based on the types of
5300 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005301 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005302 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5303 if (OverOp != OO_None) {
5304 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5305 Functions);
5306 Expr *Args[2] = { lhs, rhs };
5307 DeclarationName OpName
5308 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5309 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005310 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005311
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005312 // Build the (potentially-overloaded, potentially-dependent)
5313 // binary operation.
5314 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005315 }
5316
Douglas Gregord7f915e2008-11-06 23:29:22 +00005317 // Build a built-in binary operation.
5318 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005319}
5320
Douglas Gregorc78182d2009-03-13 23:49:33 +00005321Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5322 unsigned OpcIn,
5323 ExprArg InputArg) {
5324 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005325
Mike Stumpe127ae32009-05-16 07:39:55 +00005326 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005327 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005328 QualType resultType;
5329 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005330 case UnaryOperator::OffsetOf:
5331 assert(false && "Invalid unary operator");
5332 break;
5333
Chris Lattner4b009652007-07-25 00:24:17 +00005334 case UnaryOperator::PreInc:
5335 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005336 case UnaryOperator::PostInc:
5337 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005338 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005339 Opc == UnaryOperator::PreInc ||
5340 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005341 break;
Mike Stump9afab102009-02-19 03:04:26 +00005342 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005343 resultType = CheckAddressOfOperand(Input, OpLoc);
5344 break;
Mike Stump9afab102009-02-19 03:04:26 +00005345 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005346 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005347 resultType = CheckIndirectionOperand(Input, OpLoc);
5348 break;
5349 case UnaryOperator::Plus:
5350 case UnaryOperator::Minus:
5351 UsualUnaryConversions(Input);
5352 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005353 if (resultType->isDependentType())
5354 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005355 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5356 break;
5357 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5358 resultType->isEnumeralType())
5359 break;
5360 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5361 Opc == UnaryOperator::Plus &&
5362 resultType->isPointerType())
5363 break;
5364
Sebastian Redl8b769972009-01-19 00:08:26 +00005365 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5366 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005367 case UnaryOperator::Not: // bitwise complement
5368 UsualUnaryConversions(Input);
5369 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005370 if (resultType->isDependentType())
5371 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005372 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5373 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5374 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005375 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005376 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005377 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005378 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5379 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005380 break;
5381 case UnaryOperator::LNot: // logical negation
5382 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5383 DefaultFunctionArrayConversion(Input);
5384 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005385 if (resultType->isDependentType())
5386 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005387 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005388 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5389 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005390 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005391 // In C++, it's bool. C++ 5.3.1p8
5392 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005393 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005394 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005395 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005396 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005397 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005398 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005399 resultType = Input->getType();
5400 break;
5401 }
5402 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005403 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005404
5405 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005406 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005407}
5408
Douglas Gregorc78182d2009-03-13 23:49:33 +00005409// Unary Operators. 'Tok' is the token for the operator.
5410Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5411 tok::TokenKind Op, ExprArg input) {
5412 Expr *Input = (Expr*)input.get();
5413 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5414
5415 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5416 // Find all of the overloaded operators visible from this
5417 // point. We perform both an operator-name lookup from the local
5418 // scope and an argument-dependent lookup based on the types of
5419 // the arguments.
5420 FunctionSet Functions;
5421 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5422 if (OverOp != OO_None) {
5423 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5424 Functions);
5425 DeclarationName OpName
5426 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5427 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5428 }
5429
5430 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5431 }
5432
5433 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5434}
5435
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005436/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005437Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5438 SourceLocation LabLoc,
5439 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005440 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005441 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005442
Daniel Dunbar879788d2008-08-04 16:51:22 +00005443 // If we haven't seen this label yet, create a forward reference. It
5444 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005445 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005446 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005447
Chris Lattner4b009652007-07-25 00:24:17 +00005448 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005449 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5450 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005451}
5452
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005453Sema::OwningExprResult
5454Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5455 SourceLocation RPLoc) { // "({..})"
5456 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005457 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5458 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5459
Eli Friedmanbc941e12009-01-24 23:09:00 +00005460 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005461 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005462 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005463
Chris Lattner4b009652007-07-25 00:24:17 +00005464 // FIXME: there are a variety of strange constraints to enforce here, for
5465 // example, it is not possible to goto into a stmt expression apparently.
5466 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005467
Chris Lattner4b009652007-07-25 00:24:17 +00005468 // If there are sub stmts in the compound stmt, take the type of the last one
5469 // as the type of the stmtexpr.
5470 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005471
Chris Lattner200964f2008-07-26 19:51:01 +00005472 if (!Compound->body_empty()) {
5473 Stmt *LastStmt = Compound->body_back();
5474 // If LastStmt is a label, skip down through into the body.
5475 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5476 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005477
Chris Lattner200964f2008-07-26 19:51:01 +00005478 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005479 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005480 }
Mike Stump9afab102009-02-19 03:04:26 +00005481
Eli Friedman2b128322009-03-23 00:24:07 +00005482 // FIXME: Check that expression type is complete/non-abstract; statement
5483 // expressions are not lvalues.
5484
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005485 substmt.release();
5486 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005487}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005488
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005489Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5490 SourceLocation BuiltinLoc,
5491 SourceLocation TypeLoc,
5492 TypeTy *argty,
5493 OffsetOfComponent *CompPtr,
5494 unsigned NumComponents,
5495 SourceLocation RPLoc) {
5496 // FIXME: This function leaks all expressions in the offset components on
5497 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005498 // FIXME: Preserve type source info.
5499 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005500 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005501
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005502 bool Dependent = ArgTy->isDependentType();
5503
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005504 // We must have at least one component that refers to the type, and the first
5505 // one is known to be a field designator. Verify that the ArgTy represents
5506 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005507 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005508 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005509
Eli Friedman2b128322009-03-23 00:24:07 +00005510 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5511 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005512
Eli Friedman342d9432009-02-27 06:44:11 +00005513 // Otherwise, create a null pointer as the base, and iteratively process
5514 // the offsetof designators.
5515 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5516 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005517 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005518 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005519
Chris Lattnerb37522e2007-08-31 21:49:13 +00005520 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5521 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005522 // FIXME: This diagnostic isn't actually visible because the location is in
5523 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005524 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005525 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5526 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005527
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005528 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005529 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005530
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005531 // FIXME: Dependent case loses a lot of information here. And probably
5532 // leaks like a sieve.
5533 for (unsigned i = 0; i != NumComponents; ++i) {
5534 const OffsetOfComponent &OC = CompPtr[i];
5535 if (OC.isBrackets) {
5536 // Offset of an array sub-field. TODO: Should we allow vector elements?
5537 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5538 if (!AT) {
5539 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005540 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5541 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005542 }
5543
5544 // FIXME: C++: Verify that operator[] isn't overloaded.
5545
Eli Friedman342d9432009-02-27 06:44:11 +00005546 // Promote the array so it looks more like a normal array subscript
5547 // expression.
5548 DefaultFunctionArrayConversion(Res);
5549
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005550 // C99 6.5.2.1p1
5551 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005552 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005553 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005554 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005555 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005556 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005557
5558 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5559 OC.LocEnd);
5560 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005561 }
Mike Stump9afab102009-02-19 03:04:26 +00005562
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005563 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005564 if (!RC) {
5565 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005566 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5567 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005568 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005569
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005570 // Get the decl corresponding to this.
5571 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005572 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005573 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005574 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5575 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5576 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005577 DidWarnAboutNonPOD = true;
5578 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005579 }
5580
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005581 FieldDecl *MemberDecl
5582 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5583 LookupMemberName)
5584 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005585 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005586 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005587 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005588 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005589
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005590 // FIXME: C++: Verify that MemberDecl isn't a static field.
5591 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005592 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005593 Res = BuildAnonymousStructUnionMemberReference(
5594 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005595 } else {
5596 // MemberDecl->getType() doesn't get the right qualifiers, but it
5597 // doesn't matter here.
5598 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5599 MemberDecl->getType().getNonReferenceType());
5600 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005601 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005602 }
Mike Stump9afab102009-02-19 03:04:26 +00005603
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005604 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5605 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005606}
5607
5608
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005609Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5610 TypeTy *arg1,TypeTy *arg2,
5611 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005612 // FIXME: Preserve type source info.
5613 QualType argT1 = GetTypeFromParser(arg1);
5614 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005615
Steve Naroff63bad2d2007-08-01 22:05:33 +00005616 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005617
Douglas Gregore6211502009-05-19 22:28:02 +00005618 if (getLangOptions().CPlusPlus) {
5619 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5620 << SourceRange(BuiltinLoc, RPLoc);
5621 return ExprError();
5622 }
5623
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005624 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5625 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005626}
5627
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005628Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5629 ExprArg cond,
5630 ExprArg expr1, ExprArg expr2,
5631 SourceLocation RPLoc) {
5632 Expr *CondExpr = static_cast<Expr*>(cond.get());
5633 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5634 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005635
Steve Naroff93c53012007-08-03 21:21:27 +00005636 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5637
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005638 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005639 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005640 resType = Context.DependentTy;
5641 } else {
5642 // The conditional expression is required to be a constant expression.
5643 llvm::APSInt condEval(32);
5644 SourceLocation ExpLoc;
5645 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005646 return ExprError(Diag(ExpLoc,
5647 diag::err_typecheck_choose_expr_requires_constant)
5648 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005649
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005650 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5651 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5652 }
5653
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005654 cond.release(); expr1.release(); expr2.release();
5655 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5656 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005657}
5658
Steve Naroff52a81c02008-09-03 18:15:37 +00005659//===----------------------------------------------------------------------===//
5660// Clang Extensions.
5661//===----------------------------------------------------------------------===//
5662
5663/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005664void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005665 // Analyze block parameters.
5666 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005667
Steve Naroff52a81c02008-09-03 18:15:37 +00005668 // Add BSI to CurBlock.
5669 BSI->PrevBlockInfo = CurBlock;
5670 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005671
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005672 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005673 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005674 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005675 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005676 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5677 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005678
Steve Naroff52059382008-10-10 01:28:17 +00005679 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005680 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005681}
5682
Mike Stumpc1fddff2009-02-04 22:31:32 +00005683void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005684 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005685
5686 if (ParamInfo.getNumTypeObjects() == 0
5687 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005688 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005689 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5690
Mike Stump458287d2009-04-28 01:10:27 +00005691 if (T->isArrayType()) {
5692 Diag(ParamInfo.getSourceRange().getBegin(),
5693 diag::err_block_returns_array);
5694 return;
5695 }
5696
Mike Stumpc1fddff2009-02-04 22:31:32 +00005697 // The parameter list is optional, if there was none, assume ().
5698 if (!T->isFunctionType())
5699 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5700
5701 CurBlock->hasPrototype = true;
5702 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005703 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005704 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005705 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005706 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005707 // FIXME: remove the attribute.
5708 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005709 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5710
5711 // Do not allow returning a objc interface by-value.
5712 if (RetTy->isObjCInterfaceType()) {
5713 Diag(ParamInfo.getSourceRange().getBegin(),
5714 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5715 return;
5716 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005717 return;
5718 }
5719
Steve Naroff52a81c02008-09-03 18:15:37 +00005720 // Analyze arguments to block.
5721 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5722 "Not a function declarator!");
5723 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005724
Steve Naroff52059382008-10-10 01:28:17 +00005725 CurBlock->hasPrototype = FTI.hasPrototype;
5726 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005727
Steve Naroff52a81c02008-09-03 18:15:37 +00005728 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5729 // no arguments, not a function that takes a single void argument.
5730 if (FTI.hasPrototype &&
5731 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005732 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5733 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005734 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005735 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005736 } else if (FTI.hasPrototype) {
5737 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005738 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005739 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005740 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005741 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005742 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005743 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005744 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005745 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5746 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5747 // If this has an identifier, add it to the scope stack.
5748 if ((*AI)->getIdentifier())
5749 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005750
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005751 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005752 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005753 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005754 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005755 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005756 // FIXME: remove the attribute.
5757 }
5758
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005759 // Analyze the return type.
5760 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5761 QualType RetTy = T->getAsFunctionType()->getResultType();
5762
5763 // Do not allow returning a objc interface by-value.
5764 if (RetTy->isObjCInterfaceType()) {
5765 Diag(ParamInfo.getSourceRange().getBegin(),
5766 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5767 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005768 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005769}
5770
5771/// ActOnBlockError - If there is an error parsing a block, this callback
5772/// is invoked to pop the information about the block from the action impl.
5773void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5774 // Ensure that CurBlock is deleted.
5775 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005776
Chris Lattnere7765e12009-04-19 05:28:12 +00005777 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5778
Steve Naroff52a81c02008-09-03 18:15:37 +00005779 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005780 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005781 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005782 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005783}
5784
5785/// ActOnBlockStmtExpr - This is called when the body of a block statement
5786/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005787Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5788 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005789 // If blocks are disabled, emit an error.
5790 if (!LangOpts.Blocks)
5791 Diag(CaretLoc, diag::err_blocks_disable);
5792
Steve Naroff52a81c02008-09-03 18:15:37 +00005793 // Ensure that CurBlock is deleted.
5794 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005795
Steve Naroff52059382008-10-10 01:28:17 +00005796 PopDeclContext();
5797
Steve Naroff52a81c02008-09-03 18:15:37 +00005798 // Pop off CurBlock, handle nested blocks.
5799 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005800
Steve Naroff52a81c02008-09-03 18:15:37 +00005801 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005802 if (!BSI->ReturnType.isNull())
5803 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005804
Steve Naroff52a81c02008-09-03 18:15:37 +00005805 llvm::SmallVector<QualType, 8> ArgTypes;
5806 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5807 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005808
Mike Stump8e288f42009-07-28 22:04:01 +00005809 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005810 QualType BlockTy;
5811 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005812 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5813 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005814 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005815 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005816 BSI->isVariadic, 0, false, false, 0, 0,
5817 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005818
Eli Friedman2b128322009-03-23 00:24:07 +00005819 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005820 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005821 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005822
Chris Lattnere7765e12009-04-19 05:28:12 +00005823 // If needed, diagnose invalid gotos and switches in the block.
5824 if (CurFunctionNeedsScopeChecking)
5825 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5826 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5827
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005828 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005829 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005830 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5831 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005832}
5833
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005834Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5835 ExprArg expr, TypeTy *type,
5836 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005837 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005838 Expr *E = static_cast<Expr*>(expr.get());
5839 Expr *OrigExpr = E;
5840
Anders Carlsson36760332007-10-15 20:28:48 +00005841 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005842
5843 // Get the va_list type
5844 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005845 if (VaListType->isArrayType()) {
5846 // Deal with implicit array decay; for example, on x86-64,
5847 // va_list is an array, but it's supposed to decay to
5848 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005849 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005850 // Make sure the input expression also decays appropriately.
5851 UsualUnaryConversions(E);
5852 } else {
5853 // Otherwise, the va_list argument must be an l-value because
5854 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005855 if (!E->isTypeDependent() &&
5856 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005857 return ExprError();
5858 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005859
Douglas Gregor25990972009-05-19 23:10:31 +00005860 if (!E->isTypeDependent() &&
5861 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005862 return ExprError(Diag(E->getLocStart(),
5863 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005864 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005865 }
Mike Stump9afab102009-02-19 03:04:26 +00005866
Eli Friedman2b128322009-03-23 00:24:07 +00005867 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005868 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005869
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005870 expr.release();
5871 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5872 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005873}
5874
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005875Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005876 // The type of __null will be int or long, depending on the size of
5877 // pointers on the target.
5878 QualType Ty;
5879 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5880 Ty = Context.IntTy;
5881 else
5882 Ty = Context.LongTy;
5883
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005884 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005885}
5886
Chris Lattner005ed752008-01-04 18:04:52 +00005887bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5888 SourceLocation Loc,
5889 QualType DstType, QualType SrcType,
5890 Expr *SrcExpr, const char *Flavor) {
5891 // Decode the result (notice that AST's are still created for extensions).
5892 bool isInvalid = false;
5893 unsigned DiagKind;
5894 switch (ConvTy) {
5895 default: assert(0 && "Unknown conversion type");
5896 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005897 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005898 DiagKind = diag::ext_typecheck_convert_pointer_int;
5899 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005900 case IntToPointer:
5901 DiagKind = diag::ext_typecheck_convert_int_pointer;
5902 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005903 case IncompatiblePointer:
5904 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5905 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005906 case IncompatiblePointerSign:
5907 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5908 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005909 case FunctionVoidPointer:
5910 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5911 break;
5912 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005913 // If the qualifiers lost were because we were applying the
5914 // (deprecated) C++ conversion from a string literal to a char*
5915 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5916 // Ideally, this check would be performed in
5917 // CheckPointerTypesForAssignment. However, that would require a
5918 // bit of refactoring (so that the second argument is an
5919 // expression, rather than a type), which should be done as part
5920 // of a larger effort to fix CheckPointerTypesForAssignment for
5921 // C++ semantics.
5922 if (getLangOptions().CPlusPlus &&
5923 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5924 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005925 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5926 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005927 case IntToBlockPointer:
5928 DiagKind = diag::err_int_to_block_pointer;
5929 break;
5930 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005931 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005932 break;
Steve Naroff19608432008-10-14 22:18:38 +00005933 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005934 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005935 // it can give a more specific diagnostic.
5936 DiagKind = diag::warn_incompatible_qualified_id;
5937 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005938 case IncompatibleVectors:
5939 DiagKind = diag::warn_incompatible_vectors;
5940 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005941 case Incompatible:
5942 DiagKind = diag::err_typecheck_convert_incompatible;
5943 isInvalid = true;
5944 break;
5945 }
Mike Stump9afab102009-02-19 03:04:26 +00005946
Chris Lattner271d4c22008-11-24 05:29:24 +00005947 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5948 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005949 return isInvalid;
5950}
Anders Carlssond5201b92008-11-30 19:50:32 +00005951
Chris Lattnereec8ae22009-04-25 21:59:05 +00005952bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005953 llvm::APSInt ICEResult;
5954 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5955 if (Result)
5956 *Result = ICEResult;
5957 return false;
5958 }
5959
Anders Carlssond5201b92008-11-30 19:50:32 +00005960 Expr::EvalResult EvalResult;
5961
Mike Stump9afab102009-02-19 03:04:26 +00005962 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005963 EvalResult.HasSideEffects) {
5964 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5965
5966 if (EvalResult.Diag) {
5967 // We only show the note if it's not the usual "invalid subexpression"
5968 // or if it's actually in a subexpression.
5969 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5970 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5971 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5972 }
Mike Stump9afab102009-02-19 03:04:26 +00005973
Anders Carlssond5201b92008-11-30 19:50:32 +00005974 return true;
5975 }
5976
Eli Friedmance329412009-04-25 22:26:58 +00005977 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5978 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005979
Eli Friedmance329412009-04-25 22:26:58 +00005980 if (EvalResult.Diag &&
5981 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5982 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005983
Anders Carlssond5201b92008-11-30 19:50:32 +00005984 if (Result)
5985 *Result = EvalResult.Val.getInt();
5986 return false;
5987}
Douglas Gregor98189262009-06-19 23:52:42 +00005988
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005989Sema::ExpressionEvaluationContext
5990Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5991 // Introduce a new set of potentially referenced declarations to the stack.
5992 if (NewContext == PotentiallyPotentiallyEvaluated)
5993 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5994
5995 std::swap(ExprEvalContext, NewContext);
5996 return NewContext;
5997}
5998
5999void
6000Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6001 ExpressionEvaluationContext NewContext) {
6002 ExprEvalContext = NewContext;
6003
6004 if (OldContext == PotentiallyPotentiallyEvaluated) {
6005 // Mark any remaining declarations in the current position of the stack
6006 // as "referenced". If they were not meant to be referenced, semantic
6007 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6008 PotentiallyReferencedDecls RemainingDecls;
6009 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6010 PotentiallyReferencedDeclStack.pop_back();
6011
6012 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6013 IEnd = RemainingDecls.end();
6014 I != IEnd; ++I)
6015 MarkDeclarationReferenced(I->first, I->second);
6016 }
6017}
Douglas Gregor98189262009-06-19 23:52:42 +00006018
6019/// \brief Note that the given declaration was referenced in the source code.
6020///
6021/// This routine should be invoke whenever a given declaration is referenced
6022/// in the source code, and where that reference occurred. If this declaration
6023/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6024/// C99 6.9p3), then the declaration will be marked as used.
6025///
6026/// \param Loc the location where the declaration was referenced.
6027///
6028/// \param D the declaration that has been referenced by the source code.
6029void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6030 assert(D && "No declaration?");
6031
Douglas Gregorcad27f62009-06-22 23:06:13 +00006032 if (D->isUsed())
6033 return;
6034
Douglas Gregor98189262009-06-19 23:52:42 +00006035 // Mark a parameter declaration "used", regardless of whether we're in a
6036 // template or not.
6037 if (isa<ParmVarDecl>(D))
6038 D->setUsed(true);
6039
6040 // Do not mark anything as "used" within a dependent context; wait for
6041 // an instantiation.
6042 if (CurContext->isDependentContext())
6043 return;
6044
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00006045 switch (ExprEvalContext) {
6046 case Unevaluated:
6047 // We are in an expression that is not potentially evaluated; do nothing.
6048 return;
6049
6050 case PotentiallyEvaluated:
6051 // We are in a potentially-evaluated expression, so this declaration is
6052 // "used"; handle this below.
6053 break;
6054
6055 case PotentiallyPotentiallyEvaluated:
6056 // We are in an expression that may be potentially evaluated; queue this
6057 // declaration reference until we know whether the expression is
6058 // potentially evaluated.
6059 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6060 return;
6061 }
6062
Douglas Gregor98189262009-06-19 23:52:42 +00006063 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00006064 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006065 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00006066 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6067 if (!Constructor->isUsed())
6068 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00006069 } else if (Constructor->isImplicit() &&
6070 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006071 if (!Constructor->isUsed())
6072 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6073 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00006074 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6075 if (Destructor->isImplicit() && !Destructor->isUsed())
6076 DefineImplicitDestructor(Loc, Destructor);
6077
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00006078 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6079 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6080 MethodDecl->getOverloadedOperator() == OO_Equal) {
6081 if (!MethodDecl->isUsed())
6082 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6083 }
6084 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006085 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006086 // Implicit instantiation of function templates and member functions of
6087 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006088 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006089 // FIXME: distinguish between implicit instantiations of function
6090 // templates and explicit specializations (the latter don't get
6091 // instantiated, naturally).
6092 if (Function->getInstantiatedFromMemberFunction() ||
6093 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006094 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006095 }
6096
6097
Douglas Gregor98189262009-06-19 23:52:42 +00006098 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006099 Function->setUsed(true);
6100 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006101 }
Douglas Gregor98189262009-06-19 23:52:42 +00006102
6103 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006104 // Implicit instantiation of static data members of class templates.
6105 // FIXME: distinguish between implicit instantiations (which we need to
6106 // actually instantiate) and explicit specializations.
6107 if (Var->isStaticDataMember() &&
6108 Var->getInstantiatedFromStaticDataMember())
6109 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6110
Douglas Gregor98189262009-06-19 23:52:42 +00006111 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006112
Douglas Gregor98189262009-06-19 23:52:42 +00006113 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006114 return;
6115}
Douglas Gregor98189262009-06-19 23:52:42 +00006116}
6117