blob: 58d6a0dbac7bb02898a951ced57417cd7599545d [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 Carlsson0ab9db22009-08-25 03:49:14 +00002576
2577 // FIXME: We should really make a new InstantiatingTemplate ctor
2578 // that has a better message - right now we're just piggy-backing
2579 // off the "default template argument" error message.
2580 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002581 ArgList.getInnermost().getFlatArgumentList(),
2582 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002583
John McCall0ba26ee2009-08-25 22:02:44 +00002584 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002585 if (Result.isInvalid())
2586 return ExprError();
2587
2588 if (SetParamDefaultArgument(Param, move(Result),
2589 /*FIXME:EqualLoc*/
2590 UninstExpr->getSourceRange().getBegin()))
2591 return ExprError();
2592 }
2593
2594 Expr *DefaultExpr = Param->getDefaultArg();
2595
2596 // If the default expression creates temporaries, we need to
2597 // push them to the current stack of expression temporaries so they'll
2598 // be properly destroyed.
2599 if (CXXExprWithTemporaries *E
2600 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2601 assert(!E->shouldDestroyTemporaries() &&
2602 "Can't destroy temporaries in a default argument expr!");
2603 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2604 ExprTemporaries.push_back(E->getTemporary(I));
2605 }
2606 }
2607
2608 // We already type-checked the argument, so we know it works.
2609 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2610}
2611
Douglas Gregor3257fb52008-12-22 05:46:06 +00002612/// ConvertArgumentsForCall - Converts the arguments specified in
2613/// Args/NumArgs to the parameter types of the function FDecl with
2614/// function prototype Proto. Call is the call expression itself, and
2615/// Fn is the function expression. For a C++ member function, this
2616/// routine does not attempt to convert the object argument. Returns
2617/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002618bool
2619Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002620 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002621 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002622 Expr **Args, unsigned NumArgs,
2623 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002624 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002625 // assignment, to the types of the corresponding parameter, ...
2626 unsigned NumArgsInProto = Proto->getNumArgs();
2627 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002628 bool Invalid = false;
2629
Douglas Gregor3257fb52008-12-22 05:46:06 +00002630 // If too few arguments are available (and we don't have default
2631 // arguments for the remaining parameters), don't make the call.
2632 if (NumArgs < NumArgsInProto) {
2633 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2634 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2635 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2636 // Use default arguments for missing arguments
2637 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002638 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002639 }
2640
2641 // If too many are passed and not variadic, error on the extras and drop
2642 // them.
2643 if (NumArgs > NumArgsInProto) {
2644 if (!Proto->isVariadic()) {
2645 Diag(Args[NumArgsInProto]->getLocStart(),
2646 diag::err_typecheck_call_too_many_args)
2647 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2648 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2649 Args[NumArgs-1]->getLocEnd());
2650 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002651 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002652 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002653 }
2654 NumArgsToCheck = NumArgsInProto;
2655 }
Mike Stump9afab102009-02-19 03:04:26 +00002656
Douglas Gregor3257fb52008-12-22 05:46:06 +00002657 // Continue to check argument types (even if we have too few/many args).
2658 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2659 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002660
Douglas Gregor3257fb52008-12-22 05:46:06 +00002661 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002662 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002663 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002664
Eli Friedman83dec9e2009-03-22 22:00:50 +00002665 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2666 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002667 PDiag(diag::err_call_incomplete_argument)
2668 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002669 return true;
2670
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002671 // Pass the argument.
2672 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2673 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002674 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002675 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002676
2677 OwningExprResult ArgExpr =
2678 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2679 FDecl, Param);
2680 if (ArgExpr.isInvalid())
2681 return true;
2682
2683 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002684 }
2685
Douglas Gregor3257fb52008-12-22 05:46:06 +00002686 Call->setArg(i, Arg);
2687 }
Mike Stump9afab102009-02-19 03:04:26 +00002688
Douglas Gregor3257fb52008-12-22 05:46:06 +00002689 // If this is a variadic call, handle args passed through "...".
2690 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002691 VariadicCallType CallType = VariadicFunction;
2692 if (Fn->getType()->isBlockPointerType())
2693 CallType = VariadicBlock; // Block
2694 else if (isa<MemberExpr>(Fn))
2695 CallType = VariadicMethod;
2696
Douglas Gregor3257fb52008-12-22 05:46:06 +00002697 // Promote the arguments (C99 6.5.2.2p7).
2698 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2699 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002700 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002701 Call->setArg(i, Arg);
2702 }
2703 }
2704
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002705 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002706}
2707
Steve Naroff87d58b42007-09-16 03:34:24 +00002708/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002709/// This provides the location of the left/right parens and a list of comma
2710/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002711Action::OwningExprResult
2712Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2713 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002714 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002715 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002716
2717 // Since this might be a postfix expression, get rid of ParenListExprs.
2718 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2719
Anders Carlssonc154a722009-05-01 19:30:39 +00002720 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002721 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002722 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002723 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002724 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002725 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002726
Douglas Gregor3257fb52008-12-22 05:46:06 +00002727 if (getLangOptions().CPlusPlus) {
Douglas Gregor3e368512009-09-04 17:36:40 +00002728 // If this is a pseudo-destructor expression, build the call immediately.
2729 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2730 if (NumArgs > 0) {
2731 // Pseudo-destructor calls should not have any arguments.
2732 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2733 << CodeModificationHint::CreateRemoval(
2734 SourceRange(Args[0]->getLocStart(),
2735 Args[NumArgs-1]->getLocEnd()));
2736
2737 for (unsigned I = 0; I != NumArgs; ++I)
2738 Args[I]->Destroy(Context);
2739
2740 NumArgs = 0;
2741 }
2742
2743 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2744 RParenLoc));
2745 }
2746
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002747 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002748 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002749 // FIXME: Will need to cache the results of name lookup (including ADL) in
2750 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002751 bool Dependent = false;
2752 if (Fn->isTypeDependent())
2753 Dependent = true;
2754 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2755 Dependent = true;
2756
2757 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002758 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002759 Context.DependentTy, RParenLoc));
2760
2761 // Determine whether this is a call to an object (C++ [over.call.object]).
2762 if (Fn->getType()->isRecordType())
2763 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2764 CommaLocs, RParenLoc));
2765
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002766 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002767 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2768 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2769 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2770 isa<CXXMethodDecl>(MemDecl) ||
2771 (isa<FunctionTemplateDecl>(MemDecl) &&
2772 isa<CXXMethodDecl>(
2773 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002774 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2775 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002776 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002777 }
2778
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002779 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002780 // Also, in C++, keep track of whether we should perform argument-dependent
2781 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002782 Expr *FnExpr = Fn;
2783 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002784 bool HasExplicitTemplateArgs = 0;
2785 const TemplateArgument *ExplicitTemplateArgs = 0;
2786 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002787 while (true) {
2788 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2789 FnExpr = IcExpr->getSubExpr();
2790 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002791 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002792 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002793 ADL = false;
2794 FnExpr = PExpr->getSubExpr();
2795 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002796 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002797 == UnaryOperator::AddrOf) {
2798 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002799 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002800 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2801 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002802 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002803 break;
Mike Stump9afab102009-02-19 03:04:26 +00002804 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002805 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2806 UnqualifiedName = DepName->getName();
2807 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002808 } else if (TemplateIdRefExpr *TemplateIdRef
2809 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2810 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002811 if (!NDecl)
2812 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002813 HasExplicitTemplateArgs = true;
2814 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2815 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2816
2817 // C++ [temp.arg.explicit]p6:
2818 // [Note: For simple function names, argument dependent lookup (3.4.2)
2819 // applies even when the function name is not visible within the
2820 // scope of the call. This is because the call still has the syntactic
2821 // form of a function call (3.4.1). But when a function template with
2822 // explicit template arguments is used, the call does not have the
2823 // correct syntactic form unless there is a function template with
2824 // that name visible at the point of the call. If no such name is
2825 // visible, the call is not syntactically well-formed and
2826 // argument-dependent lookup does not apply. If some such name is
2827 // visible, argument dependent lookup applies and additional function
2828 // templates may be found in other namespaces.
2829 //
2830 // The summary of this paragraph is that, if we get to this point and the
2831 // template-id was not a qualified name, then argument-dependent lookup
2832 // is still possible.
2833 if (TemplateIdRef->getQualifier())
2834 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002835 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002836 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002837 // Any kind of name that does not refer to a declaration (or
2838 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2839 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002840 break;
2841 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002842 }
Mike Stump9afab102009-02-19 03:04:26 +00002843
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002844 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002845 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002846 if (NDecl) {
2847 FDecl = dyn_cast<FunctionDecl>(NDecl);
2848 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002849 FDecl = FunctionTemplate->getTemplatedDecl();
2850 else
Douglas Gregor28857752009-06-30 22:34:41 +00002851 FDecl = dyn_cast<FunctionDecl>(NDecl);
2852 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002853 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002854
Douglas Gregorb60eb752009-06-25 22:08:12 +00002855 if (Ovl || FunctionTemplate ||
2856 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002857 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002858 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002859 ADL = false;
2860
Douglas Gregorfcb19192009-02-11 23:02:49 +00002861 // We don't perform ADL in C.
2862 if (!getLangOptions().CPlusPlus)
2863 ADL = false;
2864
Douglas Gregorb60eb752009-06-25 22:08:12 +00002865 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002866 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2867 HasExplicitTemplateArgs,
2868 ExplicitTemplateArgs,
2869 NumExplicitTemplateArgs,
2870 LParenLoc, Args, NumArgs, CommaLocs,
2871 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002872 if (!FDecl)
2873 return ExprError();
2874
2875 // Update Fn to refer to the actual function selected.
2876 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002877 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002878 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002879 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2880 QDRExpr->getLocation(),
2881 false, false,
2882 QDRExpr->getQualifierRange(),
2883 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002884 else
Mike Stump9afab102009-02-19 03:04:26 +00002885 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002886 Fn->getSourceRange().getBegin());
2887 Fn->Destroy(Context);
2888 Fn = NewFn;
2889 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002890 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002891
2892 // Promote the function operand.
2893 UsualUnaryConversions(Fn);
2894
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002895 // Make the call expr early, before semantic checks. This guarantees cleanup
2896 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002897 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2898 Args, NumArgs,
2899 Context.BoolTy,
2900 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002901
Steve Naroffd6163f32008-09-05 22:11:13 +00002902 const FunctionType *FuncT;
2903 if (!Fn->getType()->isBlockPointerType()) {
2904 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2905 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002906 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002907 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002908 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2909 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002910 FuncT = PT->getPointeeType()->getAsFunctionType();
2911 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002912 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002913 getAsFunctionType();
2914 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002915 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002916 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2917 << Fn->getType() << Fn->getSourceRange());
2918
Eli Friedman83dec9e2009-03-22 22:00:50 +00002919 // Check for a valid return type
2920 if (!FuncT->getResultType()->isVoidType() &&
2921 RequireCompleteType(Fn->getSourceRange().getBegin(),
2922 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002923 PDiag(diag::err_call_incomplete_return)
2924 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002925 return ExprError();
2926
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002927 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002928 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002929
Douglas Gregor4fa58902009-02-26 23:50:07 +00002930 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002931 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002932 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002933 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002934 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002935 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002936
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002937 if (FDecl) {
2938 // Check if we have too few/too many template arguments, based
2939 // on our knowledge of the function definition.
2940 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002941 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002942 const FunctionProtoType *Proto =
2943 Def->getType()->getAsFunctionProtoType();
2944 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2945 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2946 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2947 }
2948 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002949 }
2950
Steve Naroffdb65e052007-08-28 23:30:39 +00002951 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002952 for (unsigned i = 0; i != NumArgs; i++) {
2953 Expr *Arg = Args[i];
2954 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002955 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2956 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002957 PDiag(diag::err_call_incomplete_argument)
2958 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002959 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002960 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002961 }
Chris Lattner4b009652007-07-25 00:24:17 +00002962 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002963
Douglas Gregor3257fb52008-12-22 05:46:06 +00002964 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2965 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002966 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2967 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002968
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002969 // Check for sentinels
2970 if (NDecl)
2971 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002972
Chris Lattner2e64c072007-08-10 20:18:51 +00002973 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002974 if (FDecl) {
2975 if (CheckFunctionCall(FDecl, TheCall.get()))
2976 return ExprError();
2977
2978 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2979 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2980 } else if (NDecl) {
2981 if (CheckBlockCall(NDecl, TheCall.get()))
2982 return ExprError();
2983 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002984
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002985 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002986}
2987
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002988Action::OwningExprResult
2989Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2990 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002991 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002992 //FIXME: Preserve type source info.
2993 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002994 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002995 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002996 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002997
Eli Friedman8c2173d2008-05-20 05:22:08 +00002998 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002999 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003000 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3001 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00003002 } else if (!literalType->isDependentType() &&
3003 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00003004 PDiag(diag::err_typecheck_decl_incomplete_type)
3005 << SourceRange(LParenLoc,
3006 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003007 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00003008
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003009 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003010 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003011 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00003012
Chris Lattnere5cb5862008-12-04 23:50:19 +00003013 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00003014 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00003015 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003016 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00003017 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003018 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00003019 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00003020 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00003021}
3022
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003023Action::OwningExprResult
3024Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003025 SourceLocation RBraceLoc) {
3026 unsigned NumInit = initlist.size();
3027 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00003028
Steve Naroff0acc9c92007-09-15 18:49:24 +00003029 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00003030 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003031
Mike Stump9afab102009-02-19 03:04:26 +00003032 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00003033 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00003034 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003035 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00003036}
3037
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003038/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00003039bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003040 CastExpr::CastKind& Kind,
3041 CXXMethodDecl *& ConversionDecl,
3042 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00003043 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003044 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3045 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00003046
Eli Friedman01e0f652009-08-15 19:02:19 +00003047 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003048
3049 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3050 // type needs to be scalar.
3051 if (castType->isVoidType()) {
3052 // Cast to void allows any expr type.
3053 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003054 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3055 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3056 (castType->isStructureType() || castType->isUnionType())) {
3057 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00003058 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003059 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3060 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003061 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003062 } else if (castType->isUnionType()) {
3063 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003064 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003065 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003066 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003067 Field != FieldEnd; ++Field) {
3068 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3069 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3070 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3071 << castExpr->getSourceRange();
3072 break;
3073 }
3074 }
3075 if (Field == FieldEnd)
3076 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3077 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003078 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003079 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003080 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003081 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003082 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003083 }
Mike Stump9afab102009-02-19 03:04:26 +00003084 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003085 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003086 return Diag(castExpr->getLocStart(),
3087 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003088 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003089 } else if (castType->isExtVectorType()) {
3090 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003091 return true;
3092 } else if (castType->isVectorType()) {
3093 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3094 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003095 } else if (castExpr->getType()->isVectorType()) {
3096 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3097 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003098 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003099 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003100 } else if (!castType->isArithmeticType()) {
3101 QualType castExprType = castExpr->getType();
3102 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3103 return Diag(castExpr->getLocStart(),
3104 diag::err_cast_pointer_from_non_pointer_int)
3105 << castExprType << castExpr->getSourceRange();
3106 } else if (!castExpr->getType()->isArithmeticType()) {
3107 if (!castType->isIntegralType() && castType->isArithmeticType())
3108 return Diag(castExpr->getLocStart(),
3109 diag::err_cast_pointer_to_non_pointer_int)
3110 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003111 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003112 if (isa<ObjCSelectorExpr>(castExpr))
3113 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003114 return false;
3115}
3116
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003117bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003118 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003119
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003120 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003121 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003122 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003123 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003124 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003125 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003126 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003127 } else
3128 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003129 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003130 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003131
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003132 return false;
3133}
3134
Nate Begemanbd42e022009-06-26 00:50:28 +00003135bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3136 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3137
Nate Begeman9e063702009-06-27 22:05:55 +00003138 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3139 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003140 if (SrcTy->isVectorType()) {
3141 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3142 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3143 << DestTy << SrcTy << R;
3144 return false;
3145 }
3146
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003147 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003148 // conversion will take place first from scalar to elt type, and then
3149 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003150 if (SrcTy->isPointerType())
3151 return Diag(R.getBegin(),
3152 diag::err_invalid_conversion_between_vector_and_scalar)
3153 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003154 return false;
3155}
3156
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003157Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003158Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003159 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003160 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3161
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003162 assert((Ty != 0) && (Op.get() != 0) &&
3163 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003164
Nate Begemane85f43d2009-08-10 23:49:36 +00003165 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003166 //FIXME: Preserve type source info.
3167 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003168
3169 // If the Expr being casted is a ParenListExpr, handle it specially.
3170 if (isa<ParenListExpr>(castExpr))
3171 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003172 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003173 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003174 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003175 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003176 if (ConversionDecl) {
3177 // encounterred a c-style cast requiring a conversion function.
3178 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3179 castExpr =
3180 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3181 castType, LParenLoc,
3182 CastExpr::CK_UserDefinedConversion,
3183 castExpr, CD,
3184 RParenLoc);
3185 Kind = CastExpr::CK_UserDefinedConversion;
3186 }
3187 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3188 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003189
3190 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003191 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003192 Kind, castExpr, castType,
3193 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003194}
3195
Nate Begemane85f43d2009-08-10 23:49:36 +00003196/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3197/// of comma binary operators.
3198Action::OwningExprResult
3199Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3200 Expr *expr = EA.takeAs<Expr>();
3201 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3202 if (!E)
3203 return Owned(expr);
3204
3205 OwningExprResult Result(*this, E->getExpr(0));
3206
3207 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3208 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3209 Owned(E->getExpr(i)));
3210
3211 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3212}
3213
3214Action::OwningExprResult
3215Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3216 SourceLocation RParenLoc, ExprArg Op,
3217 QualType Ty) {
3218 ParenListExpr *PE = (ParenListExpr *)Op.get();
3219
3220 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3221 // then handle it as such.
3222 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3223 if (PE->getNumExprs() == 0) {
3224 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3225 return ExprError();
3226 }
3227
3228 llvm::SmallVector<Expr *, 8> initExprs;
3229 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3230 initExprs.push_back(PE->getExpr(i));
3231
3232 // FIXME: This means that pretty-printing the final AST will produce curly
3233 // braces instead of the original commas.
3234 Op.release();
3235 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3236 initExprs.size(), RParenLoc);
3237 E->setType(Ty);
3238 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3239 Owned(E));
3240 } else {
3241 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3242 // sequence of BinOp comma operators.
3243 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3244 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3245 }
3246}
3247
3248Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3249 SourceLocation R,
3250 MultiExprArg Val) {
3251 unsigned nexprs = Val.size();
3252 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3253 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3254 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3255 return Owned(expr);
3256}
3257
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003258/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3259/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003260/// C99 6.5.15
3261QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3262 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003263 // C++ is sufficiently different to merit its own checker.
3264 if (getLangOptions().CPlusPlus)
3265 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3266
Chris Lattnere2897262009-02-18 04:28:32 +00003267 UsualUnaryConversions(Cond);
3268 UsualUnaryConversions(LHS);
3269 UsualUnaryConversions(RHS);
3270 QualType CondTy = Cond->getType();
3271 QualType LHSTy = LHS->getType();
3272 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003273
3274 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003275 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3276 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3277 << CondTy;
3278 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003279 }
Mike Stump9afab102009-02-19 03:04:26 +00003280
Chris Lattner992ae932008-01-06 22:42:25 +00003281 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003282 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3283 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003284
Chris Lattner992ae932008-01-06 22:42:25 +00003285 // If both operands have arithmetic type, do the usual arithmetic conversions
3286 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003287 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3288 UsualArithmeticConversions(LHS, RHS);
3289 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003290 }
Mike Stump9afab102009-02-19 03:04:26 +00003291
Chris Lattner992ae932008-01-06 22:42:25 +00003292 // If both operands are the same structure or union type, the result is that
3293 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003294 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3295 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003296 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003297 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003298 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003299 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003300 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003301 }
Mike Stump9afab102009-02-19 03:04:26 +00003302
Chris Lattner992ae932008-01-06 22:42:25 +00003303 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003304 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003305 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3306 if (!LHSTy->isVoidType())
3307 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3308 << RHS->getSourceRange();
3309 if (!RHSTy->isVoidType())
3310 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3311 << LHS->getSourceRange();
3312 ImpCastExprToType(LHS, Context.VoidTy);
3313 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003314 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003315 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003316 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3317 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003318 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003319 RHS->isNullPointerConstant(Context)) {
3320 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3321 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003322 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003323 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003324 LHS->isNullPointerConstant(Context)) {
3325 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3326 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003327 }
David Chisnall44663db2009-08-17 16:35:33 +00003328 // Handle things like Class and struct objc_class*. Here we case the result
3329 // to the pseudo-builtin, because that will be implicitly cast back to the
3330 // redefinition type if an attempt is made to access its fields.
3331 if (LHSTy->isObjCClassType() &&
3332 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3333 ImpCastExprToType(RHS, LHSTy);
3334 return LHSTy;
3335 }
3336 if (RHSTy->isObjCClassType() &&
3337 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3338 ImpCastExprToType(LHS, RHSTy);
3339 return RHSTy;
3340 }
3341 // And the same for struct objc_object* / id
3342 if (LHSTy->isObjCIdType() &&
3343 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3344 ImpCastExprToType(RHS, LHSTy);
3345 return LHSTy;
3346 }
3347 if (RHSTy->isObjCIdType() &&
3348 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3349 ImpCastExprToType(LHS, RHSTy);
3350 return RHSTy;
3351 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003352 // Handle block pointer types.
3353 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3354 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3355 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3356 QualType destType = Context.getPointerType(Context.VoidTy);
3357 ImpCastExprToType(LHS, destType);
3358 ImpCastExprToType(RHS, destType);
3359 return destType;
3360 }
3361 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3362 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3363 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003364 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003365 // We have 2 block pointer types.
3366 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3367 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003368 return LHSTy;
3369 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003370 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003371 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3372 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003373
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003374 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3375 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003376 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3377 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3378 // In this situation, we assume void* type. No especially good
3379 // reason, but this is what gcc does, and we do have to pick
3380 // to get a consistent AST.
3381 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3382 ImpCastExprToType(LHS, incompatTy);
3383 ImpCastExprToType(RHS, incompatTy);
3384 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003385 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003386 // The block pointer types are compatible.
3387 ImpCastExprToType(LHS, LHSTy);
3388 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003389 return LHSTy;
3390 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003391 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003392 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003393
3394 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3395 // Two identical object pointer types are always compatible.
3396 return LHSTy;
3397 }
Steve Naroff329ec222009-07-10 23:34:53 +00003398 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3399 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003400 QualType compositeType = LHSTy;
3401
3402 // If both operands are interfaces and either operand can be
3403 // assigned to the other, use that type as the composite
3404 // type. This allows
3405 // xxx ? (A*) a : (B*) b
3406 // where B is a subclass of A.
3407 //
3408 // Additionally, as for assignment, if either type is 'id'
3409 // allow silent coercion. Finally, if the types are
3410 // incompatible then make sure to use 'id' as the composite
3411 // type so the result is acceptable for sending messages to.
3412
3413 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3414 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003415 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003416 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003417 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003418 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003419 } else if ((LHSTy->isObjCQualifiedIdType() ||
3420 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003421 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003422 // Need to handle "id<xx>" explicitly.
3423 // GCC allows qualified id and any Objective-C type to devolve to
3424 // id. Currently localizing to here until clear this should be
3425 // part of ObjCQualifiedIdTypesAreCompatible.
3426 compositeType = Context.getObjCIdType();
3427 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003428 compositeType = Context.getObjCIdType();
3429 } else {
3430 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3431 << LHSTy << RHSTy
3432 << LHS->getSourceRange() << RHS->getSourceRange();
3433 QualType incompatTy = Context.getObjCIdType();
3434 ImpCastExprToType(LHS, incompatTy);
3435 ImpCastExprToType(RHS, incompatTy);
3436 return incompatTy;
3437 }
3438 // The object pointer types are compatible.
3439 ImpCastExprToType(LHS, compositeType);
3440 ImpCastExprToType(RHS, compositeType);
3441 return compositeType;
3442 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003443 // Check Objective-C object pointer types and 'void *'
3444 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003445 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003446 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3447 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3448 QualType destType = Context.getPointerType(destPointee);
3449 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3450 ImpCastExprToType(RHS, destType); // promote to void*
3451 return destType;
3452 }
3453 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3454 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003455 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003456 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3457 QualType destType = Context.getPointerType(destPointee);
3458 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3459 ImpCastExprToType(LHS, destType); // promote to void*
3460 return destType;
3461 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003462 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3463 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3464 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003465 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3466 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003467
3468 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3469 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3470 // Figure out necessary qualifiers (C99 6.5.15p6)
3471 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3472 QualType destType = Context.getPointerType(destPointee);
3473 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3474 ImpCastExprToType(RHS, destType); // promote to void*
3475 return destType;
3476 }
3477 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3478 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3479 QualType destType = Context.getPointerType(destPointee);
3480 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3481 ImpCastExprToType(RHS, destType); // promote to void*
3482 return destType;
3483 }
3484
3485 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3486 // Two identical pointer types are always compatible.
3487 return LHSTy;
3488 }
3489 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3490 rhptee.getUnqualifiedType())) {
3491 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3492 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3493 // In this situation, we assume void* type. No especially good
3494 // reason, but this is what gcc does, and we do have to pick
3495 // to get a consistent AST.
3496 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3497 ImpCastExprToType(LHS, incompatTy);
3498 ImpCastExprToType(RHS, incompatTy);
3499 return incompatTy;
3500 }
3501 // The pointer types are compatible.
3502 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3503 // differently qualified versions of compatible types, the result type is
3504 // a pointer to an appropriately qualified version of the *composite*
3505 // type.
3506 // FIXME: Need to calculate the composite type.
3507 // FIXME: Need to add qualifiers
3508 ImpCastExprToType(LHS, LHSTy);
3509 ImpCastExprToType(RHS, LHSTy);
3510 return LHSTy;
3511 }
3512
3513 // GCC compatibility: soften pointer/integer mismatch.
3514 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3515 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3516 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3517 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3518 return RHSTy;
3519 }
3520 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3521 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3522 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3523 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3524 return LHSTy;
3525 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003526
Chris Lattner992ae932008-01-06 22:42:25 +00003527 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003528 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3529 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003530 return QualType();
3531}
3532
Steve Naroff87d58b42007-09-16 03:34:24 +00003533/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003534/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003535Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3536 SourceLocation ColonLoc,
3537 ExprArg Cond, ExprArg LHS,
3538 ExprArg RHS) {
3539 Expr *CondExpr = (Expr *) Cond.get();
3540 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003541
3542 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3543 // was the condition.
3544 bool isLHSNull = LHSExpr == 0;
3545 if (isLHSNull)
3546 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003547
3548 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003549 RHSExpr, QuestionLoc);
3550 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003551 return ExprError();
3552
3553 Cond.release();
3554 LHS.release();
3555 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003556 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003557 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003558 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003559}
3560
Chris Lattner4b009652007-07-25 00:24:17 +00003561// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003562// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003563// routine is it effectively iqnores the qualifiers on the top level pointee.
3564// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3565// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003566Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003567Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3568 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003569
David Chisnall44663db2009-08-17 16:35:33 +00003570 if ((lhsType->isObjCClassType() &&
3571 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3572 (rhsType->isObjCClassType() &&
3573 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3574 return Compatible;
3575 }
3576
Chris Lattner4b009652007-07-25 00:24:17 +00003577 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003578 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3579 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003580
Chris Lattner4b009652007-07-25 00:24:17 +00003581 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003582 lhptee = Context.getCanonicalType(lhptee);
3583 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003584
Chris Lattner005ed752008-01-04 18:04:52 +00003585 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003586
3587 // C99 6.5.16.1p1: This following citation is common to constraints
3588 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3589 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003590 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003591 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003592 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003593
Mike Stump9afab102009-02-19 03:04:26 +00003594 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3595 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003596 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003597 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003598 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003599 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003600
Chris Lattner4ca3d772008-01-03 22:56:36 +00003601 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003602 assert(rhptee->isFunctionType());
3603 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003604 }
Mike Stump9afab102009-02-19 03:04:26 +00003605
Chris Lattner4ca3d772008-01-03 22:56:36 +00003606 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003607 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003608 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003609
3610 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003611 assert(lhptee->isFunctionType());
3612 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003613 }
Mike Stump9afab102009-02-19 03:04:26 +00003614 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003615 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003616 lhptee = lhptee.getUnqualifiedType();
3617 rhptee = rhptee.getUnqualifiedType();
3618 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3619 // Check if the pointee types are compatible ignoring the sign.
3620 // We explicitly check for char so that we catch "char" vs
3621 // "unsigned char" on systems where "char" is unsigned.
3622 if (lhptee->isCharType()) {
3623 lhptee = Context.UnsignedCharTy;
3624 } else if (lhptee->isSignedIntegerType()) {
3625 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3626 }
3627 if (rhptee->isCharType()) {
3628 rhptee = Context.UnsignedCharTy;
3629 } else if (rhptee->isSignedIntegerType()) {
3630 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3631 }
3632 if (lhptee == rhptee) {
3633 // Types are compatible ignoring the sign. Qualifier incompatibility
3634 // takes priority over sign incompatibility because the sign
3635 // warning can be disabled.
3636 if (ConvTy != Compatible)
3637 return ConvTy;
3638 return IncompatiblePointerSign;
3639 }
3640 // General pointer incompatibility takes priority over qualifiers.
3641 return IncompatiblePointer;
3642 }
Chris Lattner005ed752008-01-04 18:04:52 +00003643 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003644}
3645
Steve Naroff3454b6c2008-09-04 15:10:53 +00003646/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3647/// block pointer types are compatible or whether a block and normal pointer
3648/// are compatible. It is more restrict than comparing two function pointer
3649// types.
Mike Stump9afab102009-02-19 03:04:26 +00003650Sema::AssignConvertType
3651Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003652 QualType rhsType) {
3653 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003654
Steve Naroff3454b6c2008-09-04 15:10:53 +00003655 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003656 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3657 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003658
Steve Naroff3454b6c2008-09-04 15:10:53 +00003659 // make sure we operate on the canonical type
3660 lhptee = Context.getCanonicalType(lhptee);
3661 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003662
Steve Naroff3454b6c2008-09-04 15:10:53 +00003663 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003664
Steve Naroff3454b6c2008-09-04 15:10:53 +00003665 // For blocks we enforce that qualifiers are identical.
3666 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3667 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003668
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003669 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003670 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003671 return ConvTy;
3672}
3673
Mike Stump9afab102009-02-19 03:04:26 +00003674/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3675/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003676/// pointers. Here are some objectionable examples that GCC considers warnings:
3677///
3678/// int a, *pint;
3679/// short *pshort;
3680/// struct foo *pfoo;
3681///
3682/// pint = pshort; // warning: assignment from incompatible pointer type
3683/// a = pint; // warning: assignment makes integer from pointer without a cast
3684/// pint = a; // warning: assignment makes pointer from integer without a cast
3685/// pint = pfoo; // warning: assignment from incompatible pointer type
3686///
3687/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003688/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003689///
Chris Lattner005ed752008-01-04 18:04:52 +00003690Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003691Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003692 // Get canonical types. We're not formatting these types, just comparing
3693 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003694 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3695 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003696
3697 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003698 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003699
David Chisnall44663db2009-08-17 16:35:33 +00003700 if ((lhsType->isObjCClassType() &&
3701 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3702 (rhsType->isObjCClassType() &&
3703 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3704 return Compatible;
3705 }
3706
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003707 // If the left-hand side is a reference type, then we are in a
3708 // (rare!) case where we've allowed the use of references in C,
3709 // e.g., as a parameter type in a built-in function. In this case,
3710 // just make sure that the type referenced is compatible with the
3711 // right-hand side type. The caller is responsible for adjusting
3712 // lhsType so that the resulting expression does not have reference
3713 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003714 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003715 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003716 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003717 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003718 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003719 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3720 // to the same ExtVector type.
3721 if (lhsType->isExtVectorType()) {
3722 if (rhsType->isExtVectorType())
3723 return lhsType == rhsType ? Compatible : Incompatible;
3724 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3725 return Compatible;
3726 }
3727
Nate Begemanc5f0f652008-07-14 18:02:46 +00003728 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003729 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003730 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003731 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003732 if (getLangOptions().LaxVectorConversions &&
3733 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003734 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003735 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003736 }
3737 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003738 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003739
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003740 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003741 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003742
Chris Lattner390564e2008-04-07 06:49:41 +00003743 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003744 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003745 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003746
Chris Lattner390564e2008-04-07 06:49:41 +00003747 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003748 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003749
Steve Naroff8194a542009-07-20 17:56:53 +00003750 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003751 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003752 if (lhsType->isVoidPointerType()) // an exception to the rule.
3753 return Compatible;
3754 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003755 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003756 if (rhsType->getAs<BlockPointerType>()) {
3757 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003758 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003759
3760 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003761 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003762 return Compatible;
3763 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003764 return Incompatible;
3765 }
3766
3767 if (isa<BlockPointerType>(lhsType)) {
3768 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003769 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003770
Steve Naroffa982c712008-09-29 18:10:17 +00003771 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003772 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003773 return Compatible;
3774
Steve Naroff3454b6c2008-09-04 15:10:53 +00003775 if (rhsType->isBlockPointerType())
3776 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003777
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003778 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003779 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003780 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003781 }
Chris Lattner1853da22008-01-04 23:18:45 +00003782 return Incompatible;
3783 }
3784
Steve Naroff329ec222009-07-10 23:34:53 +00003785 if (isa<ObjCObjectPointerType>(lhsType)) {
3786 if (rhsType->isIntegerType())
3787 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003788
3789 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003790 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003791 if (rhsType->isVoidPointerType()) // an exception to the rule.
3792 return Compatible;
3793 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003794 }
3795 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003796 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3797 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003798 if (Context.typesAreCompatible(lhsType, rhsType))
3799 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003800 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3801 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003802 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003803 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003804 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003805 if (RHSPT->getPointeeType()->isVoidType())
3806 return Compatible;
3807 }
3808 // Treat block pointers as objects.
3809 if (rhsType->isBlockPointerType())
3810 return Compatible;
3811 return Incompatible;
3812 }
Chris Lattner390564e2008-04-07 06:49:41 +00003813 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003814 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003815 if (lhsType == Context.BoolTy)
3816 return Compatible;
3817
3818 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003819 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003820
Mike Stump9afab102009-02-19 03:04:26 +00003821 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003822 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003823
3824 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003825 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003826 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003827 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003828 }
Steve Naroff329ec222009-07-10 23:34:53 +00003829 if (isa<ObjCObjectPointerType>(rhsType)) {
3830 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3831 if (lhsType == Context.BoolTy)
3832 return Compatible;
3833
3834 if (lhsType->isIntegerType())
3835 return PointerToInt;
3836
Steve Naroff8194a542009-07-20 17:56:53 +00003837 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003838 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003839 if (lhsType->isVoidPointerType()) // an exception to the rule.
3840 return Compatible;
3841 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003842 }
3843 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003844 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003845 return Compatible;
3846 return Incompatible;
3847 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003848
Chris Lattner1853da22008-01-04 23:18:45 +00003849 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003850 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003851 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003852 }
3853 return Incompatible;
3854}
3855
Douglas Gregor144b06c2009-04-29 22:16:16 +00003856/// \brief Constructs a transparent union from an expression that is
3857/// used to initialize the transparent union.
3858static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3859 QualType UnionType, FieldDecl *Field) {
3860 // Build an initializer list that designates the appropriate member
3861 // of the transparent union.
3862 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3863 &E, 1,
3864 SourceLocation());
3865 Initializer->setType(UnionType);
3866 Initializer->setInitializedFieldInUnion(Field);
3867
3868 // Build a compound literal constructing a value of the transparent
3869 // union type from this initializer list.
3870 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3871 false);
3872}
3873
3874Sema::AssignConvertType
3875Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3876 QualType FromType = rExpr->getType();
3877
3878 // If the ArgType is a Union type, we want to handle a potential
3879 // transparent_union GCC extension.
3880 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003881 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003882 return Incompatible;
3883
3884 // The field to initialize within the transparent union.
3885 RecordDecl *UD = UT->getDecl();
3886 FieldDecl *InitField = 0;
3887 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003888 for (RecordDecl::field_iterator it = UD->field_begin(),
3889 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003890 it != itend; ++it) {
3891 if (it->getType()->isPointerType()) {
3892 // If the transparent union contains a pointer type, we allow:
3893 // 1) void pointer
3894 // 2) null pointer constant
3895 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003896 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003897 ImpCastExprToType(rExpr, it->getType());
3898 InitField = *it;
3899 break;
3900 }
3901
3902 if (rExpr->isNullPointerConstant(Context)) {
3903 ImpCastExprToType(rExpr, it->getType());
3904 InitField = *it;
3905 break;
3906 }
3907 }
3908
3909 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3910 == Compatible) {
3911 InitField = *it;
3912 break;
3913 }
3914 }
3915
3916 if (!InitField)
3917 return Incompatible;
3918
3919 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3920 return Compatible;
3921}
3922
Chris Lattner005ed752008-01-04 18:04:52 +00003923Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003924Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003925 if (getLangOptions().CPlusPlus) {
3926 if (!lhsType->isRecordType()) {
3927 // C++ 5.17p3: If the left operand is not of class type, the
3928 // expression is implicitly converted (C++ 4) to the
3929 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003930 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3931 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003932 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003933 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003934 }
3935
3936 // FIXME: Currently, we fall through and treat C++ classes like C
3937 // structures.
3938 }
3939
Steve Naroffcdee22d2007-11-27 17:58:44 +00003940 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3941 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003942 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003943 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003944 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003945 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003946 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003947 return Compatible;
3948 }
Mike Stump9afab102009-02-19 03:04:26 +00003949
Chris Lattner5f505bf2007-10-16 02:55:40 +00003950 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003951 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003952 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003953 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003954 //
Mike Stump9afab102009-02-19 03:04:26 +00003955 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003956 if (!lhsType->isReferenceType())
3957 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003958
Chris Lattner005ed752008-01-04 18:04:52 +00003959 Sema::AssignConvertType result =
3960 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003961
Steve Naroff0f32f432007-08-24 22:33:52 +00003962 // C99 6.5.16.1p2: The value of the right operand is converted to the
3963 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003964 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3965 // so that we can use references in built-in functions even in C.
3966 // The getNonReferenceType() call makes sure that the resulting expression
3967 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003968 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003969 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003970 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003971}
3972
Chris Lattner1eafdea2008-11-18 01:30:42 +00003973QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003974 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003975 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003976 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003977 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003978}
3979
Mike Stump9afab102009-02-19 03:04:26 +00003980inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003981 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003982 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003983 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003984 QualType lhsType =
3985 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3986 QualType rhsType =
3987 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003988
Nate Begemanc5f0f652008-07-14 18:02:46 +00003989 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003990 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003991 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003992
Nate Begemanc5f0f652008-07-14 18:02:46 +00003993 // Handle the case of a vector & extvector type of the same size and element
3994 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003995 if (getLangOptions().LaxVectorConversions) {
3996 // FIXME: Should we warn here?
3997 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003998 if (const VectorType *RV = rhsType->getAsVectorType())
3999 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00004000 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00004001 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00004002 }
4003 }
4004 }
Mike Stump9afab102009-02-19 03:04:26 +00004005
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004006 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4007 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4008 bool swapped = false;
4009 if (rhsType->isExtVectorType()) {
4010 swapped = true;
4011 std::swap(rex, lex);
4012 std::swap(rhsType, lhsType);
4013 }
4014
Nate Begemanf1695892009-06-28 19:12:57 +00004015 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004016 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4017 QualType EltTy = LV->getElementType();
4018 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4019 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00004020 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004021 if (swapped) std::swap(rex, lex);
4022 return lhsType;
4023 }
4024 }
4025 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4026 rhsType->isRealFloatingType()) {
4027 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00004028 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004029 if (swapped) std::swap(rex, lex);
4030 return lhsType;
4031 }
Nate Begemanec2d1062007-12-30 02:59:45 +00004032 }
4033 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00004034
Nate Begemanf1695892009-06-28 19:12:57 +00004035 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00004036 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004037 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00004038 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004039 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00004040}
4041
Chris Lattner4b009652007-07-25 00:24:17 +00004042inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004043 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004044{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00004045 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004046 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004047
Steve Naroff8f708362007-08-24 19:07:16 +00004048 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004049
Chris Lattner4b009652007-07-25 00:24:17 +00004050 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00004051 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004052 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004053}
4054
4055inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004056 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004057{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00004058 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4059 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4060 return CheckVectorOperands(Loc, lex, rex);
4061 return InvalidOperands(Loc, lex, rex);
4062 }
Chris Lattner4b009652007-07-25 00:24:17 +00004063
Steve Naroff8f708362007-08-24 19:07:16 +00004064 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004065
Chris Lattner4b009652007-07-25 00:24:17 +00004066 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004067 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004068 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004069}
4070
4071inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004072 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004073{
Eli Friedman3cd92882009-03-28 01:22:36 +00004074 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4075 QualType compType = CheckVectorOperands(Loc, lex, rex);
4076 if (CompLHSTy) *CompLHSTy = compType;
4077 return compType;
4078 }
Chris Lattner4b009652007-07-25 00:24:17 +00004079
Eli Friedman3cd92882009-03-28 01:22:36 +00004080 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004081
Chris Lattner4b009652007-07-25 00:24:17 +00004082 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004083 if (lex->getType()->isArithmeticType() &&
4084 rex->getType()->isArithmeticType()) {
4085 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004086 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004087 }
Chris Lattner4b009652007-07-25 00:24:17 +00004088
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004089 // Put any potential pointer into PExp
4090 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004091 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004092 std::swap(PExp, IExp);
4093
Steve Naroff79ae19a2009-07-14 18:25:06 +00004094 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004095
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004096 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004097 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004098
Chris Lattner184f92d2009-04-24 23:50:08 +00004099 // Check for arithmetic on pointers to incomplete types.
4100 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004101 if (getLangOptions().CPlusPlus) {
4102 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004103 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004104 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004105 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004106
4107 // GNU extension: arithmetic on pointer to void
4108 Diag(Loc, diag::ext_gnu_void_ptr)
4109 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004110 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004111 if (getLangOptions().CPlusPlus) {
4112 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4113 << lex->getType() << lex->getSourceRange();
4114 return QualType();
4115 }
4116
4117 // GNU extension: arithmetic on pointer to function
4118 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4119 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004120 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004121 // Check if we require a complete type.
4122 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004123 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004124 PExp->getType()->isObjCObjectPointerType()) &&
4125 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004126 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4127 << PExp->getSourceRange()
4128 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004129 return QualType();
4130 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004131 // Diagnose bad cases where we step over interface counts.
4132 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4133 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4134 << PointeeTy << PExp->getSourceRange();
4135 return QualType();
4136 }
4137
Eli Friedman3cd92882009-03-28 01:22:36 +00004138 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004139 QualType LHSTy = Context.isPromotableBitField(lex);
4140 if (LHSTy.isNull()) {
4141 LHSTy = lex->getType();
4142 if (LHSTy->isPromotableIntegerType())
4143 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004144 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004145 *CompLHSTy = LHSTy;
4146 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004147 return PExp->getType();
4148 }
4149 }
4150
Chris Lattner1eafdea2008-11-18 01:30:42 +00004151 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004152}
4153
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004154// C99 6.5.6
4155QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004156 SourceLocation Loc, QualType* CompLHSTy) {
4157 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4158 QualType compType = CheckVectorOperands(Loc, lex, rex);
4159 if (CompLHSTy) *CompLHSTy = compType;
4160 return compType;
4161 }
Mike Stump9afab102009-02-19 03:04:26 +00004162
Eli Friedman3cd92882009-03-28 01:22:36 +00004163 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004164
Chris Lattnerf6da2912007-12-09 21:53:25 +00004165 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004166
Chris Lattnerf6da2912007-12-09 21:53:25 +00004167 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004168 if (lex->getType()->isArithmeticType()
4169 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004170 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004171 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004172 }
Steve Naroff329ec222009-07-10 23:34:53 +00004173
Chris Lattnerf6da2912007-12-09 21:53:25 +00004174 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004175 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004176 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004177
Douglas Gregor05e28f62009-03-24 19:52:54 +00004178 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004179
Douglas Gregor05e28f62009-03-24 19:52:54 +00004180 bool ComplainAboutVoid = false;
4181 Expr *ComplainAboutFunc = 0;
4182 if (lpointee->isVoidType()) {
4183 if (getLangOptions().CPlusPlus) {
4184 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4185 << lex->getSourceRange() << rex->getSourceRange();
4186 return QualType();
4187 }
4188
4189 // GNU C extension: arithmetic on pointer to void
4190 ComplainAboutVoid = true;
4191 } else if (lpointee->isFunctionType()) {
4192 if (getLangOptions().CPlusPlus) {
4193 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004194 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004195 return QualType();
4196 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004197
4198 // GNU C extension: arithmetic on pointer to function
4199 ComplainAboutFunc = lex;
4200 } else if (!lpointee->isDependentType() &&
4201 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004202 PDiag(diag::err_typecheck_sub_ptr_object)
4203 << lex->getSourceRange()
4204 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004205 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004206
Chris Lattner184f92d2009-04-24 23:50:08 +00004207 // Diagnose bad cases where we step over interface counts.
4208 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4209 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4210 << lpointee << lex->getSourceRange();
4211 return QualType();
4212 }
4213
Chris Lattnerf6da2912007-12-09 21:53:25 +00004214 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004215 if (rex->getType()->isIntegerType()) {
4216 if (ComplainAboutVoid)
4217 Diag(Loc, diag::ext_gnu_void_ptr)
4218 << lex->getSourceRange() << rex->getSourceRange();
4219 if (ComplainAboutFunc)
4220 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4221 << ComplainAboutFunc->getType()
4222 << ComplainAboutFunc->getSourceRange();
4223
Eli Friedman3cd92882009-03-28 01:22:36 +00004224 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004225 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004226 }
Mike Stump9afab102009-02-19 03:04:26 +00004227
Chris Lattnerf6da2912007-12-09 21:53:25 +00004228 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004229 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004230 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004231
Douglas Gregor05e28f62009-03-24 19:52:54 +00004232 // RHS must be a completely-type object type.
4233 // Handle the GNU void* extension.
4234 if (rpointee->isVoidType()) {
4235 if (getLangOptions().CPlusPlus) {
4236 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4237 << lex->getSourceRange() << rex->getSourceRange();
4238 return QualType();
4239 }
Mike Stump9afab102009-02-19 03:04:26 +00004240
Douglas Gregor05e28f62009-03-24 19:52:54 +00004241 ComplainAboutVoid = true;
4242 } else if (rpointee->isFunctionType()) {
4243 if (getLangOptions().CPlusPlus) {
4244 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004245 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004246 return QualType();
4247 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004248
4249 // GNU extension: arithmetic on pointer to function
4250 if (!ComplainAboutFunc)
4251 ComplainAboutFunc = rex;
4252 } else if (!rpointee->isDependentType() &&
4253 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004254 PDiag(diag::err_typecheck_sub_ptr_object)
4255 << rex->getSourceRange()
4256 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004257 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004258
Eli Friedman143ddc92009-05-16 13:54:38 +00004259 if (getLangOptions().CPlusPlus) {
4260 // Pointee types must be the same: C++ [expr.add]
4261 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4262 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4263 << lex->getType() << rex->getType()
4264 << lex->getSourceRange() << rex->getSourceRange();
4265 return QualType();
4266 }
4267 } else {
4268 // Pointee types must be compatible C99 6.5.6p3
4269 if (!Context.typesAreCompatible(
4270 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4271 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4272 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4273 << lex->getType() << rex->getType()
4274 << lex->getSourceRange() << rex->getSourceRange();
4275 return QualType();
4276 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004277 }
Mike Stump9afab102009-02-19 03:04:26 +00004278
Douglas Gregor05e28f62009-03-24 19:52:54 +00004279 if (ComplainAboutVoid)
4280 Diag(Loc, diag::ext_gnu_void_ptr)
4281 << lex->getSourceRange() << rex->getSourceRange();
4282 if (ComplainAboutFunc)
4283 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4284 << ComplainAboutFunc->getType()
4285 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004286
4287 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004288 return Context.getPointerDiffType();
4289 }
4290 }
Mike Stump9afab102009-02-19 03:04:26 +00004291
Chris Lattner1eafdea2008-11-18 01:30:42 +00004292 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004293}
4294
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004295// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004296QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004297 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004298 // C99 6.5.7p2: Each of the operands shall have integer type.
4299 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004300 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004301
Chris Lattner2c8bff72007-12-12 05:47:28 +00004302 // Shifts don't perform usual arithmetic conversions, they just do integer
4303 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004304 QualType LHSTy = Context.isPromotableBitField(lex);
4305 if (LHSTy.isNull()) {
4306 LHSTy = lex->getType();
4307 if (LHSTy->isPromotableIntegerType())
4308 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004309 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004310 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004311 ImpCastExprToType(lex, LHSTy);
4312
Chris Lattner2c8bff72007-12-12 05:47:28 +00004313 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004314
Ryan Flynnf109fff2009-08-07 16:20:20 +00004315 // Sanity-check shift operands
4316 llvm::APSInt Right;
4317 // Check right/shifter operand
4318 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004319 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004320 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4321 else {
4322 llvm::APInt LeftBits(Right.getBitWidth(),
4323 Context.getTypeSize(lex->getType()));
4324 if (Right.uge(LeftBits))
4325 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4326 }
4327 }
4328
Chris Lattner2c8bff72007-12-12 05:47:28 +00004329 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004330 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004331}
4332
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004333// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004334QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004335 unsigned OpaqueOpc, bool isRelational) {
4336 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4337
Nate Begemanc5f0f652008-07-14 18:02:46 +00004338 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004339 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004340
Chris Lattner254f3bc2007-08-26 01:18:55 +00004341 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004342 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4343 UsualArithmeticConversions(lex, rex);
4344 else {
4345 UsualUnaryConversions(lex);
4346 UsualUnaryConversions(rex);
4347 }
Chris Lattner4b009652007-07-25 00:24:17 +00004348 QualType lType = lex->getType();
4349 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004350
Mike Stumpea3d74e2009-05-07 18:43:07 +00004351 if (!lType->isFloatingType()
4352 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004353 // For non-floating point types, check for self-comparisons of the form
4354 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4355 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004356 // NOTE: Don't warn about comparisons of enum constants. These can arise
4357 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004358 Expr *LHSStripped = lex->IgnoreParens();
4359 Expr *RHSStripped = rex->IgnoreParens();
4360 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4361 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004362 if (DRL->getDecl() == DRR->getDecl() &&
4363 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004364 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004365
4366 if (isa<CastExpr>(LHSStripped))
4367 LHSStripped = LHSStripped->IgnoreParenCasts();
4368 if (isa<CastExpr>(RHSStripped))
4369 RHSStripped = RHSStripped->IgnoreParenCasts();
4370
4371 // Warn about comparisons against a string constant (unless the other
4372 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004373 Expr *literalString = 0;
4374 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004375 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004376 !RHSStripped->isNullPointerConstant(Context)) {
4377 literalString = lex;
4378 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004379 } else if ((isa<StringLiteral>(RHSStripped) ||
4380 isa<ObjCEncodeExpr>(RHSStripped)) &&
4381 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004382 literalString = rex;
4383 literalStringStripped = RHSStripped;
4384 }
4385
4386 if (literalString) {
4387 std::string resultComparison;
4388 switch (Opc) {
4389 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4390 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4391 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4392 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4393 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4394 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4395 default: assert(false && "Invalid comparison operator");
4396 }
4397 Diag(Loc, diag::warn_stringcompare)
4398 << isa<ObjCEncodeExpr>(literalStringStripped)
4399 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004400 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4401 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4402 "strcmp(")
4403 << CodeModificationHint::CreateInsertion(
4404 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004405 resultComparison);
4406 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004407 }
Mike Stump9afab102009-02-19 03:04:26 +00004408
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004409 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004410 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004411
Chris Lattner254f3bc2007-08-26 01:18:55 +00004412 if (isRelational) {
4413 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004414 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004415 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004416 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004417 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004418 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004419 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004420 }
Mike Stump9afab102009-02-19 03:04:26 +00004421
Chris Lattner254f3bc2007-08-26 01:18:55 +00004422 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004423 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004424 }
Mike Stump9afab102009-02-19 03:04:26 +00004425
Chris Lattner22be8422007-08-26 01:10:14 +00004426 bool LHSIsNull = lex->isNullPointerConstant(Context);
4427 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004428
Chris Lattner254f3bc2007-08-26 01:18:55 +00004429 // All of the following pointer related warnings are GCC extensions, except
4430 // when handling null pointer constants. One day, we can consider making them
4431 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004432 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004433 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004434 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004435 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004436 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004437
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004438 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004439 if (LCanPointeeTy == RCanPointeeTy)
4440 return ResultTy;
4441
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004442 // C++ [expr.rel]p2:
4443 // [...] Pointer conversions (4.10) and qualification
4444 // conversions (4.4) are performed on pointer operands (or on
4445 // a pointer operand and a null pointer constant) to bring
4446 // them to their composite pointer type. [...]
4447 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004448 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004449 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004450 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004451 if (T.isNull()) {
4452 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4453 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4454 return QualType();
4455 }
4456
4457 ImpCastExprToType(lex, T);
4458 ImpCastExprToType(rex, T);
4459 return ResultTy;
4460 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004461 // C99 6.5.9p2 and C99 6.5.8p2
4462 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4463 RCanPointeeTy.getUnqualifiedType())) {
4464 // Valid unless a relational comparison of function pointers
4465 if (isRelational && LCanPointeeTy->isFunctionType()) {
4466 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4467 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4468 }
4469 } else if (!isRelational &&
4470 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4471 // Valid unless comparison between non-null pointer and function pointer
4472 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4473 && !LHSIsNull && !RHSIsNull) {
4474 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4475 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4476 }
4477 } else {
4478 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004479 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004480 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004481 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004482 if (LCanPointeeTy != RCanPointeeTy)
4483 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004484 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004485 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004486
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004487 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004488 // Comparison of pointers with null pointer constants and equality
4489 // comparisons of member pointers to null pointer constants.
4490 if (RHSIsNull &&
4491 (lType->isPointerType() ||
4492 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004493 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004494 return ResultTy;
4495 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004496 if (LHSIsNull &&
4497 (rType->isPointerType() ||
4498 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004499 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004500 return ResultTy;
4501 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004502
4503 // Comparison of member pointers.
4504 if (!isRelational &&
4505 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4506 // C++ [expr.eq]p2:
4507 // In addition, pointers to members can be compared, or a pointer to
4508 // member and a null pointer constant. Pointer to member conversions
4509 // (4.11) and qualification conversions (4.4) are performed to bring
4510 // them to a common type. If one operand is a null pointer constant,
4511 // the common type is the type of the other operand. Otherwise, the
4512 // common type is a pointer to member type similar (4.4) to the type
4513 // of one of the operands, with a cv-qualification signature (4.4)
4514 // that is the union of the cv-qualification signatures of the operand
4515 // types.
4516 QualType T = FindCompositePointerType(lex, rex);
4517 if (T.isNull()) {
4518 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4520 return QualType();
4521 }
4522
4523 ImpCastExprToType(lex, T);
4524 ImpCastExprToType(rex, T);
4525 return ResultTy;
4526 }
4527
4528 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004529 if (lType->isNullPtrType() && rType->isNullPtrType())
4530 return ResultTy;
4531 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004532
Steve Naroff3454b6c2008-09-04 15:10:53 +00004533 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004534 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004535 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4536 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004537
Steve Naroff3454b6c2008-09-04 15:10:53 +00004538 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004539 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004540 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004541 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004542 }
4543 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004544 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004545 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004546 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004547 if (!isRelational
4548 && ((lType->isBlockPointerType() && rType->isPointerType())
4549 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004550 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004551 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004552 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004553 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004554 ->getPointeeType()->isVoidType())))
4555 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4556 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004557 }
4558 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004559 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004560 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004561
Steve Naroff329ec222009-07-10 23:34:53 +00004562 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004563 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004564 const PointerType *LPT = lType->getAs<PointerType>();
4565 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004566 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004567 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004568 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004569 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004570
Steve Naroff030fcda2008-11-17 19:49:16 +00004571 if (!LPtrToVoid && !RPtrToVoid &&
4572 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004573 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004574 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004575 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004576 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004577 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004578 }
Steve Naroff329ec222009-07-10 23:34:53 +00004579 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004580 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004581 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4582 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004583 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004584 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004585 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004586 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004587 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004588 unsigned DiagID = 0;
4589 if (RHSIsNull) {
4590 if (isRelational)
4591 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4592 } else if (isRelational)
4593 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4594 else
4595 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4596
4597 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004598 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004599 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004600 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004601 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004602 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004603 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004604 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004605 unsigned DiagID = 0;
4606 if (LHSIsNull) {
4607 if (isRelational)
4608 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4609 } else if (isRelational)
4610 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4611 else
4612 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004613
Chris Lattner124569f2009-08-23 00:03:44 +00004614 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004615 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004616 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004617 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004618 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004619 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004620 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004621 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004622 if (!isRelational && RHSIsNull
4623 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004624 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004625 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004626 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004627 if (!isRelational && LHSIsNull
4628 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004629 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004630 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004631 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004632 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004633}
4634
Nate Begemanc5f0f652008-07-14 18:02:46 +00004635/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004636/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004637/// like a scalar comparison, a vector comparison produces a vector of integer
4638/// types.
4639QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004640 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004641 bool isRelational) {
4642 // Check to make sure we're operating on vectors of the same type and width,
4643 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004644 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004645 if (vType.isNull())
4646 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004647
Nate Begemanc5f0f652008-07-14 18:02:46 +00004648 QualType lType = lex->getType();
4649 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004650
Nate Begemanc5f0f652008-07-14 18:02:46 +00004651 // For non-floating point types, check for self-comparisons of the form
4652 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4653 // often indicate logic errors in the program.
4654 if (!lType->isFloatingType()) {
4655 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4656 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4657 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004658 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004659 }
Mike Stump9afab102009-02-19 03:04:26 +00004660
Nate Begemanc5f0f652008-07-14 18:02:46 +00004661 // Check for comparisons of floating point operands using != and ==.
4662 if (!isRelational && lType->isFloatingType()) {
4663 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004664 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004665 }
Mike Stump9afab102009-02-19 03:04:26 +00004666
Nate Begemanc5f0f652008-07-14 18:02:46 +00004667 // Return the type for the comparison, which is the same as vector type for
4668 // integer vectors, or an integer type of identical size and number of
4669 // elements for floating point vectors.
4670 if (lType->isIntegerType())
4671 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004672
Nate Begemanc5f0f652008-07-14 18:02:46 +00004673 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004674 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004675 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004676 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004677 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004678 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4679
Mike Stump9afab102009-02-19 03:04:26 +00004680 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004681 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004682 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4683}
4684
Chris Lattner4b009652007-07-25 00:24:17 +00004685inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004686 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004687{
4688 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004689 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004690
Steve Naroff8f708362007-08-24 19:07:16 +00004691 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004692
Chris Lattner4b009652007-07-25 00:24:17 +00004693 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004694 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004695 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004696}
4697
4698inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004699 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004700{
4701 UsualUnaryConversions(lex);
4702 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004703
Eli Friedmanbea3f842008-05-13 20:16:47 +00004704 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004705 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004706 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004707}
4708
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004709/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4710/// is a read-only property; return true if so. A readonly property expression
4711/// depends on various declarations and thus must be treated specially.
4712///
Mike Stump9afab102009-02-19 03:04:26 +00004713static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004714{
4715 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4716 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4717 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4718 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004719 if (const ObjCObjectPointerType *OPT =
4720 BaseType->getAsObjCInterfacePointerType())
4721 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4722 if (S.isPropertyReadonly(PDecl, IFace))
4723 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004724 }
4725 }
4726 return false;
4727}
4728
Chris Lattner4c2642c2008-11-18 01:22:49 +00004729/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4730/// emit an error and return true. If so, return false.
4731static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004732 SourceLocation OrigLoc = Loc;
4733 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4734 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004735 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4736 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004737 if (IsLV == Expr::MLV_Valid)
4738 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004739
Chris Lattner4c2642c2008-11-18 01:22:49 +00004740 unsigned Diag = 0;
4741 bool NeedType = false;
4742 switch (IsLV) { // C99 6.5.16p2
4743 default: assert(0 && "Unknown result from isModifiableLvalue!");
4744 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004745 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004746 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4747 NeedType = true;
4748 break;
Mike Stump9afab102009-02-19 03:04:26 +00004749 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004750 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4751 NeedType = true;
4752 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004753 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004754 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4755 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004756 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004757 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4758 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004759 case Expr::MLV_IncompleteType:
4760 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004761 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004762 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4763 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004764 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004765 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4766 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004767 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004768 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4769 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004770 case Expr::MLV_ReadonlyProperty:
4771 Diag = diag::error_readonly_property_assignment;
4772 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004773 case Expr::MLV_NoSetterProperty:
4774 Diag = diag::error_nosetter_property_assignment;
4775 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004776 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004777
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004778 SourceRange Assign;
4779 if (Loc != OrigLoc)
4780 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004781 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004782 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004783 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004784 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004785 return true;
4786}
4787
4788
4789
4790// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004791QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4792 SourceLocation Loc,
4793 QualType CompoundType) {
4794 // Verify that LHS is a modifiable lvalue, and emit error if not.
4795 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004796 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004797
4798 QualType LHSType = LHS->getType();
4799 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004800
Chris Lattner005ed752008-01-04 18:04:52 +00004801 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004802 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004803 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004804 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004805 // Special case of NSObject attributes on c-style pointer types.
4806 if (ConvTy == IncompatiblePointer &&
4807 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004808 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004809 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004810 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004811 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004812
Chris Lattner34c85082008-08-21 18:04:13 +00004813 // If the RHS is a unary plus or minus, check to see if they = and + are
4814 // right next to each other. If so, the user may have typo'd "x =+ 4"
4815 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004816 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004817 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4818 RHSCheck = ICE->getSubExpr();
4819 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4820 if ((UO->getOpcode() == UnaryOperator::Plus ||
4821 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004822 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004823 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004824 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4825 // And there is a space or other character before the subexpr of the
4826 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004827 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4828 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004829 Diag(Loc, diag::warn_not_compound_assign)
4830 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4831 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004832 }
Chris Lattner34c85082008-08-21 18:04:13 +00004833 }
4834 } else {
4835 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004836 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004837 }
Chris Lattner005ed752008-01-04 18:04:52 +00004838
Chris Lattner1eafdea2008-11-18 01:30:42 +00004839 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4840 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004841 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004842
Chris Lattner4b009652007-07-25 00:24:17 +00004843 // C99 6.5.16p3: The type of an assignment expression is the type of the
4844 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004845 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004846 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4847 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004848 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004849 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004850 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004851}
4852
Chris Lattner1eafdea2008-11-18 01:30:42 +00004853// C99 6.5.17
4854QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004855 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004856 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004857
4858 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4859 // incomplete in C++).
4860
Chris Lattner1eafdea2008-11-18 01:30:42 +00004861 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004862}
4863
4864/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4865/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004866QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4867 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004868 if (Op->isTypeDependent())
4869 return Context.DependentTy;
4870
Chris Lattnere65182c2008-11-21 07:05:48 +00004871 QualType ResType = Op->getType();
4872 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004873
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004874 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4875 // Decrement of bool is not allowed.
4876 if (!isInc) {
4877 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4878 return QualType();
4879 }
4880 // Increment of bool sets it to true, but is deprecated.
4881 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4882 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004883 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004884 } else if (ResType->isAnyPointerType()) {
4885 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004886
Chris Lattnere65182c2008-11-21 07:05:48 +00004887 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004888 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004889 if (getLangOptions().CPlusPlus) {
4890 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4891 << Op->getSourceRange();
4892 return QualType();
4893 }
4894
4895 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004896 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004897 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004898 if (getLangOptions().CPlusPlus) {
4899 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4900 << Op->getType() << Op->getSourceRange();
4901 return QualType();
4902 }
4903
4904 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004905 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004906 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004907 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4908 << Op->getSourceRange()
4909 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004910 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004911 // Diagnose bad cases where we step over interface counts.
4912 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4913 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4914 << PointeeTy << Op->getSourceRange();
4915 return QualType();
4916 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004917 } else if (ResType->isComplexType()) {
4918 // C99 does not support ++/-- on complex types, we allow as an extension.
4919 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004920 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004921 } else {
4922 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004923 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004924 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004925 }
Mike Stump9afab102009-02-19 03:04:26 +00004926 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004927 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004928 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004929 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004930 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004931}
4932
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004933/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004934/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004935/// where the declaration is needed for type checking. We only need to
4936/// handle cases when the expression references a function designator
4937/// or is an lvalue. Here are some examples:
4938/// - &(x) => x
4939/// - &*****f => f for f a function designator.
4940/// - &s.xx => s
4941/// - &s.zz[1].yy -> s, if zz is an array
4942/// - *(x + 1) -> x, if x is an array
4943/// - &"123"[2] -> 0
4944/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004945static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004946 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004947 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004948 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004949 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004950 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004951 // If this is an arrow operator, the address is an offset from
4952 // the base's value, so the object the base refers to is
4953 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004954 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004955 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004956 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004957 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004958 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004959 // FIXME: This code shouldn't be necessary! We should catch the implicit
4960 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004961 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4962 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4963 if (ICE->getSubExpr()->getType()->isArrayType())
4964 return getPrimaryDecl(ICE->getSubExpr());
4965 }
4966 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004967 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004968 case Stmt::UnaryOperatorClass: {
4969 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004970
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004971 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004972 case UnaryOperator::Real:
4973 case UnaryOperator::Imag:
4974 case UnaryOperator::Extension:
4975 return getPrimaryDecl(UO->getSubExpr());
4976 default:
4977 return 0;
4978 }
4979 }
Chris Lattner4b009652007-07-25 00:24:17 +00004980 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004981 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004982 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004983 // If the result of an implicit cast is an l-value, we care about
4984 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004985 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004986 default:
4987 return 0;
4988 }
4989}
4990
4991/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004992/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004993/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004994/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004995/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004996/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004997/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004998QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004999 // Make sure to ignore parentheses in subsequent checks
5000 op = op->IgnoreParens();
5001
Douglas Gregore6be68a2008-12-17 22:52:20 +00005002 if (op->isTypeDependent())
5003 return Context.DependentTy;
5004
Steve Naroff9c6c3592008-01-13 17:10:08 +00005005 if (getLangOptions().C99) {
5006 // Implement C99-only parts of addressof rules.
5007 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5008 if (uOp->getOpcode() == UnaryOperator::Deref)
5009 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5010 // (assuming the deref expression is valid).
5011 return uOp->getSubExpr()->getType();
5012 }
5013 // Technically, there should be a check for array subscript
5014 // expressions here, but the result of one is always an lvalue anyway.
5015 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00005016 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00005017 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00005018
Eli Friedman14ab4c42009-05-16 23:27:50 +00005019 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5020 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00005021 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00005022 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00005023 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00005024 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5025 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005026 return QualType();
5027 }
Douglas Gregor531434b2009-05-02 02:18:30 +00005028 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00005029 // The operand cannot be a bit-field
5030 Diag(OpLoc, diag::err_typecheck_address_of)
5031 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00005032 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00005033 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5034 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00005035 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00005036 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00005037 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00005038 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00005039 } else if (isa<ObjCPropertyRefExpr>(op)) {
5040 // cannot take address of a property expression.
5041 Diag(OpLoc, diag::err_typecheck_address_of)
5042 << "property expression" << op->getSourceRange();
5043 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00005044 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00005045 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00005046 // with the register storage-class specifier.
5047 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5048 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00005049 Diag(OpLoc, diag::err_typecheck_address_of)
5050 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005051 return QualType();
5052 }
Douglas Gregor62f78762009-07-08 20:55:45 +00005053 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5054 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00005055 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00005056 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00005057 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00005058 // Could be a pointer to member, though, if there is an explicit
5059 // scope qualifier for the class.
5060 if (isa<QualifiedDeclRefExpr>(op)) {
5061 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00005062 if (Ctx && Ctx->isRecord()) {
5063 if (FD->getType()->isReferenceType()) {
5064 Diag(OpLoc,
5065 diag::err_cannot_form_pointer_to_member_of_reference_type)
5066 << FD->getDeclName() << FD->getType();
5067 return QualType();
5068 }
5069
Sebastian Redl0c9da212009-02-03 20:19:35 +00005070 return Context.getMemberPointerType(op->getType(),
5071 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00005072 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00005073 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005074 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00005075 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00005076 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005077 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5078 return Context.getMemberPointerType(op->getType(),
5079 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5080 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00005081 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00005082 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00005083
Eli Friedman14ab4c42009-05-16 23:27:50 +00005084 if (lval == Expr::LV_IncompleteVoidType) {
5085 // Taking the address of a void variable is technically illegal, but we
5086 // allow it in cases which are otherwise valid.
5087 // Example: "extern void x; void* y = &x;".
5088 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5089 }
5090
Chris Lattner4b009652007-07-25 00:24:17 +00005091 // If the operand has type "type", the result has type "pointer to type".
5092 return Context.getPointerType(op->getType());
5093}
5094
Chris Lattnerda5c0872008-11-23 09:13:29 +00005095QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005096 if (Op->isTypeDependent())
5097 return Context.DependentTy;
5098
Chris Lattnerda5c0872008-11-23 09:13:29 +00005099 UsualUnaryConversions(Op);
5100 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005101
Chris Lattnerda5c0872008-11-23 09:13:29 +00005102 // Note that per both C89 and C99, this is always legal, even if ptype is an
5103 // incomplete type or void. It would be possible to warn about dereferencing
5104 // a void pointer, but it's completely well-defined, and such a warning is
5105 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005106 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005107 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005108
Fariborz Jahanian81699d92009-09-03 00:43:07 +00005109 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5110 return OPT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00005111
Chris Lattner77d52da2008-11-20 06:06:08 +00005112 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005113 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005114 return QualType();
5115}
5116
5117static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5118 tok::TokenKind Kind) {
5119 BinaryOperator::Opcode Opc;
5120 switch (Kind) {
5121 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005122 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5123 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005124 case tok::star: Opc = BinaryOperator::Mul; break;
5125 case tok::slash: Opc = BinaryOperator::Div; break;
5126 case tok::percent: Opc = BinaryOperator::Rem; break;
5127 case tok::plus: Opc = BinaryOperator::Add; break;
5128 case tok::minus: Opc = BinaryOperator::Sub; break;
5129 case tok::lessless: Opc = BinaryOperator::Shl; break;
5130 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5131 case tok::lessequal: Opc = BinaryOperator::LE; break;
5132 case tok::less: Opc = BinaryOperator::LT; break;
5133 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5134 case tok::greater: Opc = BinaryOperator::GT; break;
5135 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5136 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5137 case tok::amp: Opc = BinaryOperator::And; break;
5138 case tok::caret: Opc = BinaryOperator::Xor; break;
5139 case tok::pipe: Opc = BinaryOperator::Or; break;
5140 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5141 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5142 case tok::equal: Opc = BinaryOperator::Assign; break;
5143 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5144 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5145 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5146 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5147 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5148 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5149 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5150 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5151 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5152 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5153 case tok::comma: Opc = BinaryOperator::Comma; break;
5154 }
5155 return Opc;
5156}
5157
5158static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5159 tok::TokenKind Kind) {
5160 UnaryOperator::Opcode Opc;
5161 switch (Kind) {
5162 default: assert(0 && "Unknown unary op!");
5163 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5164 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5165 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5166 case tok::star: Opc = UnaryOperator::Deref; break;
5167 case tok::plus: Opc = UnaryOperator::Plus; break;
5168 case tok::minus: Opc = UnaryOperator::Minus; break;
5169 case tok::tilde: Opc = UnaryOperator::Not; break;
5170 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005171 case tok::kw___real: Opc = UnaryOperator::Real; break;
5172 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5173 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5174 }
5175 return Opc;
5176}
5177
Douglas Gregord7f915e2008-11-06 23:29:22 +00005178/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5179/// operator @p Opc at location @c TokLoc. This routine only supports
5180/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005181Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5182 unsigned Op,
5183 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005184 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005185 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005186 // The following two variables are used for compound assignment operators
5187 QualType CompLHSTy; // Type of LHS after promotions for computation
5188 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005189
5190 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005191 case BinaryOperator::Assign:
5192 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5193 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005194 case BinaryOperator::PtrMemD:
5195 case BinaryOperator::PtrMemI:
5196 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5197 Opc == BinaryOperator::PtrMemI);
5198 break;
5199 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005200 case BinaryOperator::Div:
5201 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5202 break;
5203 case BinaryOperator::Rem:
5204 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5205 break;
5206 case BinaryOperator::Add:
5207 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5208 break;
5209 case BinaryOperator::Sub:
5210 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5211 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005212 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005213 case BinaryOperator::Shr:
5214 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5215 break;
5216 case BinaryOperator::LE:
5217 case BinaryOperator::LT:
5218 case BinaryOperator::GE:
5219 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005220 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005221 break;
5222 case BinaryOperator::EQ:
5223 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005224 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005225 break;
5226 case BinaryOperator::And:
5227 case BinaryOperator::Xor:
5228 case BinaryOperator::Or:
5229 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5230 break;
5231 case BinaryOperator::LAnd:
5232 case BinaryOperator::LOr:
5233 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5234 break;
5235 case BinaryOperator::MulAssign:
5236 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005237 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5238 CompLHSTy = CompResultTy;
5239 if (!CompResultTy.isNull())
5240 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005241 break;
5242 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005243 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5244 CompLHSTy = CompResultTy;
5245 if (!CompResultTy.isNull())
5246 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005247 break;
5248 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005249 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5250 if (!CompResultTy.isNull())
5251 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005252 break;
5253 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005254 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5255 if (!CompResultTy.isNull())
5256 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005257 break;
5258 case BinaryOperator::ShlAssign:
5259 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005260 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5261 CompLHSTy = CompResultTy;
5262 if (!CompResultTy.isNull())
5263 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005264 break;
5265 case BinaryOperator::AndAssign:
5266 case BinaryOperator::XorAssign:
5267 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005268 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5269 CompLHSTy = CompResultTy;
5270 if (!CompResultTy.isNull())
5271 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005272 break;
5273 case BinaryOperator::Comma:
5274 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5275 break;
5276 }
5277 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005278 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005279 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005280 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5281 else
5282 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005283 CompLHSTy, CompResultTy,
5284 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005285}
5286
Chris Lattner4b009652007-07-25 00:24:17 +00005287// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005288Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5289 tok::TokenKind Kind,
5290 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005291 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005292 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005293
Steve Naroff87d58b42007-09-16 03:34:24 +00005294 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5295 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005296
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005297 if (getLangOptions().CPlusPlus &&
5298 (lhs->getType()->isOverloadableType() ||
5299 rhs->getType()->isOverloadableType())) {
5300 // Find all of the overloaded operators visible from this
5301 // point. We perform both an operator-name lookup from the local
5302 // scope and an argument-dependent lookup based on the types of
5303 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005304 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005305 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5306 if (OverOp != OO_None) {
5307 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5308 Functions);
5309 Expr *Args[2] = { lhs, rhs };
5310 DeclarationName OpName
5311 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5312 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005313 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005314
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005315 // Build the (potentially-overloaded, potentially-dependent)
5316 // binary operation.
5317 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005318 }
5319
Douglas Gregord7f915e2008-11-06 23:29:22 +00005320 // Build a built-in binary operation.
5321 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005322}
5323
Douglas Gregorc78182d2009-03-13 23:49:33 +00005324Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5325 unsigned OpcIn,
5326 ExprArg InputArg) {
5327 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005328
Mike Stumpe127ae32009-05-16 07:39:55 +00005329 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005330 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005331 QualType resultType;
5332 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005333 case UnaryOperator::OffsetOf:
5334 assert(false && "Invalid unary operator");
5335 break;
5336
Chris Lattner4b009652007-07-25 00:24:17 +00005337 case UnaryOperator::PreInc:
5338 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005339 case UnaryOperator::PostInc:
5340 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005341 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005342 Opc == UnaryOperator::PreInc ||
5343 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005344 break;
Mike Stump9afab102009-02-19 03:04:26 +00005345 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005346 resultType = CheckAddressOfOperand(Input, OpLoc);
5347 break;
Mike Stump9afab102009-02-19 03:04:26 +00005348 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005349 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005350 resultType = CheckIndirectionOperand(Input, OpLoc);
5351 break;
5352 case UnaryOperator::Plus:
5353 case UnaryOperator::Minus:
5354 UsualUnaryConversions(Input);
5355 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005356 if (resultType->isDependentType())
5357 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005358 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5359 break;
5360 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5361 resultType->isEnumeralType())
5362 break;
5363 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5364 Opc == UnaryOperator::Plus &&
5365 resultType->isPointerType())
5366 break;
5367
Sebastian Redl8b769972009-01-19 00:08:26 +00005368 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5369 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005370 case UnaryOperator::Not: // bitwise complement
5371 UsualUnaryConversions(Input);
5372 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005373 if (resultType->isDependentType())
5374 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005375 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5376 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5377 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005378 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005379 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005380 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005381 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5382 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005383 break;
5384 case UnaryOperator::LNot: // logical negation
5385 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5386 DefaultFunctionArrayConversion(Input);
5387 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005388 if (resultType->isDependentType())
5389 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005390 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005391 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5392 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005393 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005394 // In C++, it's bool. C++ 5.3.1p8
5395 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005396 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005397 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005398 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005399 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005400 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005401 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005402 resultType = Input->getType();
5403 break;
5404 }
5405 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005406 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005407
5408 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005409 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005410}
5411
Douglas Gregorc78182d2009-03-13 23:49:33 +00005412// Unary Operators. 'Tok' is the token for the operator.
5413Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5414 tok::TokenKind Op, ExprArg input) {
5415 Expr *Input = (Expr*)input.get();
5416 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5417
5418 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5419 // Find all of the overloaded operators visible from this
5420 // point. We perform both an operator-name lookup from the local
5421 // scope and an argument-dependent lookup based on the types of
5422 // the arguments.
5423 FunctionSet Functions;
5424 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5425 if (OverOp != OO_None) {
5426 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5427 Functions);
5428 DeclarationName OpName
5429 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5430 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5431 }
5432
5433 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5434 }
5435
5436 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5437}
5438
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005439/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005440Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5441 SourceLocation LabLoc,
5442 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005443 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005444 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005445
Daniel Dunbar879788d2008-08-04 16:51:22 +00005446 // If we haven't seen this label yet, create a forward reference. It
5447 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005448 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005449 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005450
Chris Lattner4b009652007-07-25 00:24:17 +00005451 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005452 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5453 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005454}
5455
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005456Sema::OwningExprResult
5457Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5458 SourceLocation RPLoc) { // "({..})"
5459 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005460 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5461 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5462
Eli Friedmanbc941e12009-01-24 23:09:00 +00005463 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005464 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005465 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005466
Chris Lattner4b009652007-07-25 00:24:17 +00005467 // FIXME: there are a variety of strange constraints to enforce here, for
5468 // example, it is not possible to goto into a stmt expression apparently.
5469 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005470
Chris Lattner4b009652007-07-25 00:24:17 +00005471 // If there are sub stmts in the compound stmt, take the type of the last one
5472 // as the type of the stmtexpr.
5473 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005474
Chris Lattner200964f2008-07-26 19:51:01 +00005475 if (!Compound->body_empty()) {
5476 Stmt *LastStmt = Compound->body_back();
5477 // If LastStmt is a label, skip down through into the body.
5478 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5479 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005480
Chris Lattner200964f2008-07-26 19:51:01 +00005481 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005482 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005483 }
Mike Stump9afab102009-02-19 03:04:26 +00005484
Eli Friedman2b128322009-03-23 00:24:07 +00005485 // FIXME: Check that expression type is complete/non-abstract; statement
5486 // expressions are not lvalues.
5487
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005488 substmt.release();
5489 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005490}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005491
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005492Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5493 SourceLocation BuiltinLoc,
5494 SourceLocation TypeLoc,
5495 TypeTy *argty,
5496 OffsetOfComponent *CompPtr,
5497 unsigned NumComponents,
5498 SourceLocation RPLoc) {
5499 // FIXME: This function leaks all expressions in the offset components on
5500 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005501 // FIXME: Preserve type source info.
5502 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005503 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005504
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005505 bool Dependent = ArgTy->isDependentType();
5506
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005507 // We must have at least one component that refers to the type, and the first
5508 // one is known to be a field designator. Verify that the ArgTy represents
5509 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005510 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005511 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005512
Eli Friedman2b128322009-03-23 00:24:07 +00005513 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5514 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005515
Eli Friedman342d9432009-02-27 06:44:11 +00005516 // Otherwise, create a null pointer as the base, and iteratively process
5517 // the offsetof designators.
5518 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5519 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005520 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005521 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005522
Chris Lattnerb37522e2007-08-31 21:49:13 +00005523 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5524 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005525 // FIXME: This diagnostic isn't actually visible because the location is in
5526 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005527 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005528 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5529 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005530
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005531 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005532 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005533
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005534 // FIXME: Dependent case loses a lot of information here. And probably
5535 // leaks like a sieve.
5536 for (unsigned i = 0; i != NumComponents; ++i) {
5537 const OffsetOfComponent &OC = CompPtr[i];
5538 if (OC.isBrackets) {
5539 // Offset of an array sub-field. TODO: Should we allow vector elements?
5540 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5541 if (!AT) {
5542 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005543 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5544 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005545 }
5546
5547 // FIXME: C++: Verify that operator[] isn't overloaded.
5548
Eli Friedman342d9432009-02-27 06:44:11 +00005549 // Promote the array so it looks more like a normal array subscript
5550 // expression.
5551 DefaultFunctionArrayConversion(Res);
5552
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005553 // C99 6.5.2.1p1
5554 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005555 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005556 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005557 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005558 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005559 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005560
5561 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5562 OC.LocEnd);
5563 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005564 }
Mike Stump9afab102009-02-19 03:04:26 +00005565
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005566 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005567 if (!RC) {
5568 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005569 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5570 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005571 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005572
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005573 // Get the decl corresponding to this.
5574 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005575 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005576 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005577 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5578 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5579 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005580 DidWarnAboutNonPOD = true;
5581 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005582 }
5583
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005584 FieldDecl *MemberDecl
5585 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5586 LookupMemberName)
5587 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005588 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005589 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005590 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005591 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005592
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005593 // FIXME: C++: Verify that MemberDecl isn't a static field.
5594 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005595 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005596 Res = BuildAnonymousStructUnionMemberReference(
5597 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005598 } else {
5599 // MemberDecl->getType() doesn't get the right qualifiers, but it
5600 // doesn't matter here.
5601 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5602 MemberDecl->getType().getNonReferenceType());
5603 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005604 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005605 }
Mike Stump9afab102009-02-19 03:04:26 +00005606
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005607 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5608 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005609}
5610
5611
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005612Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5613 TypeTy *arg1,TypeTy *arg2,
5614 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005615 // FIXME: Preserve type source info.
5616 QualType argT1 = GetTypeFromParser(arg1);
5617 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005618
Steve Naroff63bad2d2007-08-01 22:05:33 +00005619 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005620
Douglas Gregore6211502009-05-19 22:28:02 +00005621 if (getLangOptions().CPlusPlus) {
5622 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5623 << SourceRange(BuiltinLoc, RPLoc);
5624 return ExprError();
5625 }
5626
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005627 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5628 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005629}
5630
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005631Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5632 ExprArg cond,
5633 ExprArg expr1, ExprArg expr2,
5634 SourceLocation RPLoc) {
5635 Expr *CondExpr = static_cast<Expr*>(cond.get());
5636 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5637 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005638
Steve Naroff93c53012007-08-03 21:21:27 +00005639 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5640
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005641 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005642 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005643 resType = Context.DependentTy;
5644 } else {
5645 // The conditional expression is required to be a constant expression.
5646 llvm::APSInt condEval(32);
5647 SourceLocation ExpLoc;
5648 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005649 return ExprError(Diag(ExpLoc,
5650 diag::err_typecheck_choose_expr_requires_constant)
5651 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005652
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005653 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5654 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5655 }
5656
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005657 cond.release(); expr1.release(); expr2.release();
5658 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5659 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005660}
5661
Steve Naroff52a81c02008-09-03 18:15:37 +00005662//===----------------------------------------------------------------------===//
5663// Clang Extensions.
5664//===----------------------------------------------------------------------===//
5665
5666/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005667void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005668 // Analyze block parameters.
5669 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005670
Steve Naroff52a81c02008-09-03 18:15:37 +00005671 // Add BSI to CurBlock.
5672 BSI->PrevBlockInfo = CurBlock;
5673 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005674
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005675 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005676 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005677 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005678 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005679 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5680 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005681
Steve Naroff52059382008-10-10 01:28:17 +00005682 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005683 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005684}
5685
Mike Stumpc1fddff2009-02-04 22:31:32 +00005686void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005687 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005688
5689 if (ParamInfo.getNumTypeObjects() == 0
5690 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005691 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005692 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5693
Mike Stump458287d2009-04-28 01:10:27 +00005694 if (T->isArrayType()) {
5695 Diag(ParamInfo.getSourceRange().getBegin(),
5696 diag::err_block_returns_array);
5697 return;
5698 }
5699
Mike Stumpc1fddff2009-02-04 22:31:32 +00005700 // The parameter list is optional, if there was none, assume ().
5701 if (!T->isFunctionType())
5702 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5703
5704 CurBlock->hasPrototype = true;
5705 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005706 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005707 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005708 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005709 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005710 // FIXME: remove the attribute.
5711 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005712 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5713
5714 // Do not allow returning a objc interface by-value.
5715 if (RetTy->isObjCInterfaceType()) {
5716 Diag(ParamInfo.getSourceRange().getBegin(),
5717 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5718 return;
5719 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005720 return;
5721 }
5722
Steve Naroff52a81c02008-09-03 18:15:37 +00005723 // Analyze arguments to block.
5724 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5725 "Not a function declarator!");
5726 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005727
Steve Naroff52059382008-10-10 01:28:17 +00005728 CurBlock->hasPrototype = FTI.hasPrototype;
5729 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005730
Steve Naroff52a81c02008-09-03 18:15:37 +00005731 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5732 // no arguments, not a function that takes a single void argument.
5733 if (FTI.hasPrototype &&
5734 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005735 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5736 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005737 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005738 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005739 } else if (FTI.hasPrototype) {
5740 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005741 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005742 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005743 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005744 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005745 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005746 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005747 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005748 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5749 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5750 // If this has an identifier, add it to the scope stack.
5751 if ((*AI)->getIdentifier())
5752 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005753
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005754 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005755 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005756 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005757 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005758 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005759 // FIXME: remove the attribute.
5760 }
5761
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005762 // Analyze the return type.
5763 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5764 QualType RetTy = T->getAsFunctionType()->getResultType();
5765
5766 // Do not allow returning a objc interface by-value.
5767 if (RetTy->isObjCInterfaceType()) {
5768 Diag(ParamInfo.getSourceRange().getBegin(),
5769 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5770 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005771 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005772}
5773
5774/// ActOnBlockError - If there is an error parsing a block, this callback
5775/// is invoked to pop the information about the block from the action impl.
5776void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5777 // Ensure that CurBlock is deleted.
5778 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005779
Chris Lattnere7765e12009-04-19 05:28:12 +00005780 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5781
Steve Naroff52a81c02008-09-03 18:15:37 +00005782 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005783 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005784 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005785 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005786}
5787
5788/// ActOnBlockStmtExpr - This is called when the body of a block statement
5789/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005790Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5791 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005792 // If blocks are disabled, emit an error.
5793 if (!LangOpts.Blocks)
5794 Diag(CaretLoc, diag::err_blocks_disable);
5795
Steve Naroff52a81c02008-09-03 18:15:37 +00005796 // Ensure that CurBlock is deleted.
5797 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005798
Steve Naroff52059382008-10-10 01:28:17 +00005799 PopDeclContext();
5800
Steve Naroff52a81c02008-09-03 18:15:37 +00005801 // Pop off CurBlock, handle nested blocks.
5802 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005803
Steve Naroff52a81c02008-09-03 18:15:37 +00005804 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005805 if (!BSI->ReturnType.isNull())
5806 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005807
Steve Naroff52a81c02008-09-03 18:15:37 +00005808 llvm::SmallVector<QualType, 8> ArgTypes;
5809 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5810 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005811
Mike Stump8e288f42009-07-28 22:04:01 +00005812 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005813 QualType BlockTy;
5814 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005815 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5816 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005817 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005818 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005819 BSI->isVariadic, 0, false, false, 0, 0,
5820 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005821
Eli Friedman2b128322009-03-23 00:24:07 +00005822 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005823 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005824 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005825
Chris Lattnere7765e12009-04-19 05:28:12 +00005826 // If needed, diagnose invalid gotos and switches in the block.
5827 if (CurFunctionNeedsScopeChecking)
5828 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5829 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5830
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005831 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005832 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005833 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5834 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005835}
5836
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005837Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5838 ExprArg expr, TypeTy *type,
5839 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005840 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005841 Expr *E = static_cast<Expr*>(expr.get());
5842 Expr *OrigExpr = E;
5843
Anders Carlsson36760332007-10-15 20:28:48 +00005844 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005845
5846 // Get the va_list type
5847 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005848 if (VaListType->isArrayType()) {
5849 // Deal with implicit array decay; for example, on x86-64,
5850 // va_list is an array, but it's supposed to decay to
5851 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005852 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005853 // Make sure the input expression also decays appropriately.
5854 UsualUnaryConversions(E);
5855 } else {
5856 // Otherwise, the va_list argument must be an l-value because
5857 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005858 if (!E->isTypeDependent() &&
5859 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005860 return ExprError();
5861 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005862
Douglas Gregor25990972009-05-19 23:10:31 +00005863 if (!E->isTypeDependent() &&
5864 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005865 return ExprError(Diag(E->getLocStart(),
5866 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005867 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005868 }
Mike Stump9afab102009-02-19 03:04:26 +00005869
Eli Friedman2b128322009-03-23 00:24:07 +00005870 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005871 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005872
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005873 expr.release();
5874 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5875 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005876}
5877
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005878Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005879 // The type of __null will be int or long, depending on the size of
5880 // pointers on the target.
5881 QualType Ty;
5882 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5883 Ty = Context.IntTy;
5884 else
5885 Ty = Context.LongTy;
5886
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005887 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005888}
5889
Chris Lattner005ed752008-01-04 18:04:52 +00005890bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5891 SourceLocation Loc,
5892 QualType DstType, QualType SrcType,
5893 Expr *SrcExpr, const char *Flavor) {
5894 // Decode the result (notice that AST's are still created for extensions).
5895 bool isInvalid = false;
5896 unsigned DiagKind;
5897 switch (ConvTy) {
5898 default: assert(0 && "Unknown conversion type");
5899 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005900 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005901 DiagKind = diag::ext_typecheck_convert_pointer_int;
5902 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005903 case IntToPointer:
5904 DiagKind = diag::ext_typecheck_convert_int_pointer;
5905 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005906 case IncompatiblePointer:
5907 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5908 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005909 case IncompatiblePointerSign:
5910 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5911 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005912 case FunctionVoidPointer:
5913 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5914 break;
5915 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005916 // If the qualifiers lost were because we were applying the
5917 // (deprecated) C++ conversion from a string literal to a char*
5918 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5919 // Ideally, this check would be performed in
5920 // CheckPointerTypesForAssignment. However, that would require a
5921 // bit of refactoring (so that the second argument is an
5922 // expression, rather than a type), which should be done as part
5923 // of a larger effort to fix CheckPointerTypesForAssignment for
5924 // C++ semantics.
5925 if (getLangOptions().CPlusPlus &&
5926 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5927 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005928 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5929 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005930 case IntToBlockPointer:
5931 DiagKind = diag::err_int_to_block_pointer;
5932 break;
5933 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005934 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005935 break;
Steve Naroff19608432008-10-14 22:18:38 +00005936 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005937 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005938 // it can give a more specific diagnostic.
5939 DiagKind = diag::warn_incompatible_qualified_id;
5940 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005941 case IncompatibleVectors:
5942 DiagKind = diag::warn_incompatible_vectors;
5943 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005944 case Incompatible:
5945 DiagKind = diag::err_typecheck_convert_incompatible;
5946 isInvalid = true;
5947 break;
5948 }
Mike Stump9afab102009-02-19 03:04:26 +00005949
Chris Lattner271d4c22008-11-24 05:29:24 +00005950 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5951 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005952 return isInvalid;
5953}
Anders Carlssond5201b92008-11-30 19:50:32 +00005954
Chris Lattnereec8ae22009-04-25 21:59:05 +00005955bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005956 llvm::APSInt ICEResult;
5957 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5958 if (Result)
5959 *Result = ICEResult;
5960 return false;
5961 }
5962
Anders Carlssond5201b92008-11-30 19:50:32 +00005963 Expr::EvalResult EvalResult;
5964
Mike Stump9afab102009-02-19 03:04:26 +00005965 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005966 EvalResult.HasSideEffects) {
5967 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5968
5969 if (EvalResult.Diag) {
5970 // We only show the note if it's not the usual "invalid subexpression"
5971 // or if it's actually in a subexpression.
5972 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5973 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5974 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5975 }
Mike Stump9afab102009-02-19 03:04:26 +00005976
Anders Carlssond5201b92008-11-30 19:50:32 +00005977 return true;
5978 }
5979
Eli Friedmance329412009-04-25 22:26:58 +00005980 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5981 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005982
Eli Friedmance329412009-04-25 22:26:58 +00005983 if (EvalResult.Diag &&
5984 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5985 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005986
Anders Carlssond5201b92008-11-30 19:50:32 +00005987 if (Result)
5988 *Result = EvalResult.Val.getInt();
5989 return false;
5990}
Douglas Gregor98189262009-06-19 23:52:42 +00005991
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005992Sema::ExpressionEvaluationContext
5993Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5994 // Introduce a new set of potentially referenced declarations to the stack.
5995 if (NewContext == PotentiallyPotentiallyEvaluated)
5996 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5997
5998 std::swap(ExprEvalContext, NewContext);
5999 return NewContext;
6000}
6001
6002void
6003Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6004 ExpressionEvaluationContext NewContext) {
6005 ExprEvalContext = NewContext;
6006
6007 if (OldContext == PotentiallyPotentiallyEvaluated) {
6008 // Mark any remaining declarations in the current position of the stack
6009 // as "referenced". If they were not meant to be referenced, semantic
6010 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6011 PotentiallyReferencedDecls RemainingDecls;
6012 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6013 PotentiallyReferencedDeclStack.pop_back();
6014
6015 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6016 IEnd = RemainingDecls.end();
6017 I != IEnd; ++I)
6018 MarkDeclarationReferenced(I->first, I->second);
6019 }
6020}
Douglas Gregor98189262009-06-19 23:52:42 +00006021
6022/// \brief Note that the given declaration was referenced in the source code.
6023///
6024/// This routine should be invoke whenever a given declaration is referenced
6025/// in the source code, and where that reference occurred. If this declaration
6026/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6027/// C99 6.9p3), then the declaration will be marked as used.
6028///
6029/// \param Loc the location where the declaration was referenced.
6030///
6031/// \param D the declaration that has been referenced by the source code.
6032void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6033 assert(D && "No declaration?");
6034
Douglas Gregorcad27f62009-06-22 23:06:13 +00006035 if (D->isUsed())
6036 return;
6037
Douglas Gregor98189262009-06-19 23:52:42 +00006038 // Mark a parameter declaration "used", regardless of whether we're in a
6039 // template or not.
6040 if (isa<ParmVarDecl>(D))
6041 D->setUsed(true);
6042
6043 // Do not mark anything as "used" within a dependent context; wait for
6044 // an instantiation.
6045 if (CurContext->isDependentContext())
6046 return;
6047
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00006048 switch (ExprEvalContext) {
6049 case Unevaluated:
6050 // We are in an expression that is not potentially evaluated; do nothing.
6051 return;
6052
6053 case PotentiallyEvaluated:
6054 // We are in a potentially-evaluated expression, so this declaration is
6055 // "used"; handle this below.
6056 break;
6057
6058 case PotentiallyPotentiallyEvaluated:
6059 // We are in an expression that may be potentially evaluated; queue this
6060 // declaration reference until we know whether the expression is
6061 // potentially evaluated.
6062 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6063 return;
6064 }
6065
Douglas Gregor98189262009-06-19 23:52:42 +00006066 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00006067 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006068 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00006069 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6070 if (!Constructor->isUsed())
6071 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00006072 } else if (Constructor->isImplicit() &&
6073 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006074 if (!Constructor->isUsed())
6075 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6076 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00006077 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6078 if (Destructor->isImplicit() && !Destructor->isUsed())
6079 DefineImplicitDestructor(Loc, Destructor);
6080
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00006081 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6082 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6083 MethodDecl->getOverloadedOperator() == OO_Equal) {
6084 if (!MethodDecl->isUsed())
6085 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6086 }
6087 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006088 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006089 // Implicit instantiation of function templates and member functions of
6090 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006091 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006092 // FIXME: distinguish between implicit instantiations of function
6093 // templates and explicit specializations (the latter don't get
6094 // instantiated, naturally).
6095 if (Function->getInstantiatedFromMemberFunction() ||
6096 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006097 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006098 }
6099
6100
Douglas Gregor98189262009-06-19 23:52:42 +00006101 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006102 Function->setUsed(true);
6103 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006104 }
Douglas Gregor98189262009-06-19 23:52:42 +00006105
6106 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006107 // Implicit instantiation of static data members of class templates.
6108 // FIXME: distinguish between implicit instantiations (which we need to
6109 // actually instantiate) and explicit specializations.
6110 if (Var->isStaticDataMember() &&
6111 Var->getInstantiatedFromStaticDataMember())
6112 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6113
Douglas Gregor98189262009-06-19 23:52:42 +00006114 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006115
Douglas Gregor98189262009-06-19 23:52:42 +00006116 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006117 return;
6118}
Douglas Gregor98189262009-06-19 23:52:42 +00006119}
6120