blob: ef924fee4282b9294ed826251b4bf82d84a743ef [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())
199 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000200 else if (Ty->isArrayType()) {
201 // In C90 mode, arrays only promote to pointers if the array expression is
202 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
203 // type 'array of type' is converted to an expression that has type 'pointer
204 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
205 // that has type 'array of type' ...". The relevant change is "an lvalue"
206 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000207 //
208 // C++ 4.2p1:
209 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
210 // T" can be converted to an rvalue of type "pointer to T".
211 //
212 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
213 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000214 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
215 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000216 }
Chris Lattner299b8842008-07-25 21:10:04 +0000217}
218
219/// UsualUnaryConversions - Performs various conversions that are common to most
220/// operators (C99 6.3). The conversions of array and function types are
221/// sometimes surpressed. For example, the array->pointer conversion doesn't
222/// apply if the array is an argument to the sizeof or address (&) operators.
223/// In these instances, this routine should *not* be called.
224Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
225 QualType Ty = Expr->getType();
226 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
227
Douglas Gregor70b307e2009-05-01 20:41:21 +0000228 // C99 6.3.1.1p2:
229 //
230 // The following may be used in an expression wherever an int or
231 // unsigned int may be used:
232 // - an object or expression with an integer type whose integer
233 // conversion rank is less than or equal to the rank of int
234 // and unsigned int.
235 // - A bit-field of type _Bool, int, signed int, or unsigned int.
236 //
237 // If an int can represent all values of the original type, the
238 // value is converted to an int; otherwise, it is converted to an
239 // unsigned int. These are called the integer promotions. All
240 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000241 QualType PTy = Context.isPromotableBitField(Expr);
242 if (!PTy.isNull()) {
243 ImpCastExprToType(Expr, PTy);
244 return Expr;
245 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000246 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000247 QualType PT = Context.getPromotedIntegerType(Ty);
248 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000249 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000250 }
251
Douglas Gregor70b307e2009-05-01 20:41:21 +0000252 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000253 return Expr;
254}
255
Chris Lattner9305c3d2008-07-25 22:25:12 +0000256/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
257/// do not have a prototype. Arguments that have type float are promoted to
258/// double. All other argument types are converted by UsualUnaryConversions().
259void Sema::DefaultArgumentPromotion(Expr *&Expr) {
260 QualType Ty = Expr->getType();
261 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
262
263 // If this is a 'float' (CVR qualified or typedef) promote to double.
264 if (const BuiltinType *BT = Ty->getAsBuiltinType())
265 if (BT->getKind() == BuiltinType::Float)
266 return ImpCastExprToType(Expr, Context.DoubleTy);
267
268 UsualUnaryConversions(Expr);
269}
270
Chris Lattner81f00ed2009-04-12 08:11:20 +0000271/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
272/// will warn if the resulting type is not a POD type, and rejects ObjC
273/// interfaces passed by value. This returns true if the argument type is
274/// completely illegal.
275bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000276 DefaultArgumentPromotion(Expr);
277
Chris Lattner81f00ed2009-04-12 08:11:20 +0000278 if (Expr->getType()->isObjCInterfaceType()) {
279 Diag(Expr->getLocStart(),
280 diag::err_cannot_pass_objc_interface_to_vararg)
281 << Expr->getType() << CT;
282 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000283 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000284
285 if (!Expr->getType()->isPODType())
286 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287 << Expr->getType() << CT;
288
289 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000290}
291
292
Chris Lattner299b8842008-07-25 21:10:04 +0000293/// UsualArithmeticConversions - Performs various conversions that are common to
294/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
295/// routine returns the first non-arithmetic type found. The client is
296/// responsible for emitting appropriate error diagnostics.
297/// FIXME: verify the conversion rules for "complex int" are consistent with
298/// GCC.
299QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
300 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000301 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000302 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000303
304 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000305
Chris Lattner299b8842008-07-25 21:10:04 +0000306 // For conversion purposes, we ignore any qualifiers.
307 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000308 QualType lhs =
309 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
310 QualType rhs =
311 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000312
313 // If both types are identical, no conversion is needed.
314 if (lhs == rhs)
315 return lhs;
316
317 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
318 // The caller can deal with this (e.g. pointer + int).
319 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
320 return lhs;
321
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000322 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000323 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000324 if (!LHSBitfieldPromoteTy.isNull())
325 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000326 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000327 if (!RHSBitfieldPromoteTy.isNull())
328 rhs = RHSBitfieldPromoteTy;
329
Eli Friedman6ae7d112009-08-19 07:44:53 +0000330 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000331 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000332 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000333 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000334 return destType;
335}
336
Chris Lattner299b8842008-07-25 21:10:04 +0000337//===----------------------------------------------------------------------===//
338// Semantic Analysis for various Expression Types
339//===----------------------------------------------------------------------===//
340
341
Steve Naroff87d58b42007-09-16 03:34:24 +0000342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000343/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
345/// multiple tokens. However, the common case is that StringToks points to one
346/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000347///
348Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000350 assert(NumStringToks && "Must have at least one string!");
351
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000352 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000353 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000354 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000355
356 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
357 for (unsigned i = 0; i != NumStringToks; ++i)
358 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000359
Chris Lattnera6dcce32008-02-11 00:02:17 +0000360 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000361 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000362 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000363
364 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
365 if (getLangOptions().CPlusPlus)
366 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 // Get an array type for the string, according to C99 6.4.5. This includes
369 // the nul terminator character as well as the string length for pascal
370 // strings.
371 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000372 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000373 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000374
Chris Lattner4b009652007-07-25 00:24:17 +0000375 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000376 return Owned(StringLiteral::Create(Context, Literal.GetString(),
377 Literal.GetStringLength(),
378 Literal.AnyWide, StrTy,
379 &StringTokLocs[0],
380 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000381}
382
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000383/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
384/// CurBlock to VD should cause it to be snapshotted (as we do for auto
385/// variables defined outside the block) or false if this is not needed (e.g.
386/// for values inside the block or for globals).
387///
Chris Lattner0b464252009-04-21 22:26:47 +0000388/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
389/// up-to-date.
390///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
392 ValueDecl *VD) {
393 // If the value is defined inside the block, we couldn't snapshot it even if
394 // we wanted to.
395 if (CurBlock->TheDecl == VD->getDeclContext())
396 return false;
397
398 // If this is an enum constant or function, it is constant, don't snapshot.
399 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
400 return false;
401
402 // If this is a reference to an extern, static, or global variable, no need to
403 // snapshot it.
404 // FIXME: What about 'const' variables in C++?
405 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000406 if (!Var->hasLocalStorage())
407 return false;
408
409 // Blocks that have these can't be constant.
410 CurBlock->hasBlockDeclRefExprs = true;
411
412 // If we have nested blocks, the decl may be declared in an outer block (in
413 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
414 // be defined outside all of the current blocks (in which case the blocks do
415 // all get the bit). Walk the nesting chain.
416 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
417 NextBlock = NextBlock->PrevBlockInfo) {
418 // If we found the defining block for the variable, don't mark the block as
419 // having a reference outside it.
420 if (NextBlock->TheDecl == VD->getDeclContext())
421 break;
422
423 // Otherwise, the DeclRef from the inner block causes the outer one to need
424 // a snapshot as well.
425 NextBlock->hasBlockDeclRefExprs = true;
426 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000427
428 return true;
429}
430
431
432
Steve Naroff0acc9c92007-09-15 18:49:24 +0000433/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000434/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000435/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000436/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000437/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000438Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
439 IdentifierInfo &II,
440 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000441 const CXXScopeSpec *SS,
442 bool isAddressOfOperand) {
443 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000444 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000445}
446
Douglas Gregor566782a2009-01-06 05:10:23 +0000447/// BuildDeclRefExpr - Build either a DeclRefExpr or a
448/// QualifiedDeclRefExpr based on whether or not SS is a
449/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000450Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452 bool TypeDependent, bool ValueDependent,
453 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
456 diag::err_auto_variable_cannot_appear_in_own_initializer)
457 << D->getDeclName();
458 return ExprError();
459 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000460
461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
466 << D->getIdentifier() << FD->getDeclName();
467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
474
Douglas Gregor98189262009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000476
477 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000478 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000479 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
480 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000481 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000482 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000483 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
484
485 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000486}
487
Douglas Gregor723d3332009-01-07 00:43:41 +0000488/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
489/// variable corresponding to the anonymous union or struct whose type
490/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000491static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
492 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000493 assert(Record->isAnonymousStructOrUnion() &&
494 "Record must be an anonymous struct or union!");
495
Mike Stumpe127ae32009-05-16 07:39:55 +0000496 // FIXME: Once Decls are directly linked together, this will be an O(1)
497 // operation rather than a slow walk through DeclContext's vector (which
498 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000500 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
501 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000502 D != DEnd; ++D) {
503 if (*D == Record) {
504 // The object for the anonymous struct/union directly
505 // follows its type in the list of declarations.
506 ++D;
507 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000508 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000509 return *D;
510 }
511 }
512
513 assert(false && "Missing object for anonymous record");
514 return 0;
515}
516
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000517/// \brief Given a field that represents a member of an anonymous
518/// struct/union, build the path from that field's context to the
519/// actual member.
520///
521/// Construct the sequence of field member references we'll have to
522/// perform to get to the field in the anonymous union/struct. The
523/// list of members is built from the field outward, so traverse it
524/// backwards to go from an object in the current context to the field
525/// we found.
526///
527/// \returns The variable from which the field access should begin,
528/// for an anonymous struct/union that is not a member of another
529/// class. Otherwise, returns NULL.
530VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
531 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000532 assert(Field->getDeclContext()->isRecord() &&
533 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
534 && "Field must be stored inside an anonymous struct or union");
535
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000536 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000537 VarDecl *BaseObject = 0;
538 DeclContext *Ctx = Field->getDeclContext();
539 do {
540 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000541 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000542 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000543 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000544 else {
545 BaseObject = cast<VarDecl>(AnonObject);
546 break;
547 }
548 Ctx = Ctx->getParent();
549 } while (Ctx->isRecord() &&
550 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000551
552 return BaseObject;
553}
554
555Sema::OwningExprResult
556Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
557 FieldDecl *Field,
558 Expr *BaseObjectExpr,
559 SourceLocation OpLoc) {
560 llvm::SmallVector<FieldDecl *, 4> AnonFields;
561 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
562 AnonFields);
563
Douglas Gregor723d3332009-01-07 00:43:41 +0000564 // Build the expression that refers to the base object, from
565 // which we will build a sequence of member references to each
566 // of the anonymous union objects and, eventually, the field we
567 // found via name lookup.
568 bool BaseObjectIsPointer = false;
569 unsigned ExtraQuals = 0;
570 if (BaseObject) {
571 // BaseObject is an anonymous struct/union variable (and is,
572 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000573 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000574 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000575 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000576 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000577 ExtraQuals
578 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
579 } else if (BaseObjectExpr) {
580 // The caller provided the base object expression. Determine
581 // whether its a pointer and whether it adds any qualifiers to the
582 // anonymous struct/union fields we're looking into.
583 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000584 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000585 BaseObjectIsPointer = true;
586 ObjectType = ObjectPtr->getPointeeType();
587 }
588 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
589 } else {
590 // We've found a member of an anonymous struct/union that is
591 // inside a non-anonymous struct/union, so in a well-formed
592 // program our base object expression is "this".
593 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
594 if (!MD->isStatic()) {
595 QualType AnonFieldType
596 = Context.getTagDeclType(
597 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598 QualType ThisType = Context.getTagDeclType(MD->getParent());
599 if ((Context.getCanonicalType(AnonFieldType)
600 == Context.getCanonicalType(ThisType)) ||
601 IsDerivedFrom(ThisType, AnonFieldType)) {
602 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000603 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000604 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000605 BaseObjectIsPointer = true;
606 }
607 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000610 }
611 ExtraQuals = MD->getTypeQualifiers();
612 }
613
614 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000617 }
618
619 // Build the implicit member references to the field of the
620 // anonymous struct/union.
621 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000622 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625 FI != FIEnd; ++FI) {
626 QualType MemberType = (*FI)->getType();
627 if (!(*FI)->isMutable()) {
628 unsigned combinedQualifiers
629 = MemberType.getCVRQualifiers() | ExtraQuals;
630 MemberType = MemberType.getQualifiedType(combinedQualifiers);
631 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000632 if (BaseAddrSpace != MemberType.getAddressSpace())
633 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000634 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
639 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000640 }
641
Sebastian Redlcd883f72009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000643}
644
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000645/// ActOnDeclarationNameExpr - The parser has read some kind of name
646/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
647/// performs lookup on that name and returns an expression that refers
648/// to that name. This routine isn't directly called from the parser,
649/// because the parser doesn't know about DeclarationName. Rather,
650/// this routine is called by ActOnIdentifierExpr,
651/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
652/// which form the DeclarationName from the corresponding syntactic
653/// forms.
654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context. LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000659///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000667 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000668 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000669 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000670 if (SS && SS->isInvalid())
671 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000672
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000677 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000678 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
680 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000683 }
684
Douglas Gregor411889e2009-02-13 23:20:09 +0000685 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
686 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000687
Sebastian Redlcd883f72009-01-18 18:53:16 +0000688 if (Lookup.isAmbiguous()) {
689 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690 SS && SS->isSet() ? SS->getRange()
691 : SourceRange());
692 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000693 }
694
695 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000696
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000697 // If this reference is in an Objective-C method, then ivar lookup happens as
698 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000699 IdentifierInfo *II = Name.getAsIdentifierInfo();
700 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000701 // There are two cases to handle here. 1) scoped lookup could have failed,
702 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000703 // found a decl, but that decl is outside the current instance method (i.e.
704 // a global variable). In these two cases, we do a lookup for an ivar with
705 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000706 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000707 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000708 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000710 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000711 if (DiagnoseUseOfDecl(IV, Loc))
712 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000713
714 // If we're referencing an invalid decl, just return this as a silent
715 // error node. The error diagnostic was already emitted on the decl.
716 if (IV->isInvalidDecl())
717 return ExprError();
718
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000719 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720 // If a class method attemps to use a free standing ivar, this is
721 // an error.
722 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724 << IV->getDeclName());
725 // If a class method uses a global variable, even if an ivar with
726 // same name exists, use the global.
727 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000728 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729 ClassDeclared != IFace)
730 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000731 // FIXME: This should use a new expr for a direct reference, don't
732 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000733 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000734 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
735 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000736 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000737 return Owned(new (Context)
738 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000739 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000740 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000741 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000742 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000743 // We should warn if a local variable hides an ivar.
744 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000745 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000746 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000747 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
748 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000749 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000750 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000751 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000752 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000753 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000754 QualType T;
755
756 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000757 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
758 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000759 else
760 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000761 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000762 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000763 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000764
Douglas Gregoraa57e862009-02-18 21:56:37 +0000765 // Determine whether this name might be a candidate for
766 // argument-dependent lookup.
767 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
768 HasTrailingLParen;
769
770 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000771 // We've seen something of the form
772 //
773 // identifier(
774 //
775 // and we did not find any entity by the name
776 // "identifier". However, this identifier is still subject to
777 // argument-dependent lookup, so keep track of the name.
778 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
779 Context.OverloadTy,
780 Loc));
781 }
782
Chris Lattner4b009652007-07-25 00:24:17 +0000783 if (D == 0) {
784 // Otherwise, this could be an implicitly declared function reference (legal
785 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000786 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000787 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000788 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000789 else {
790 // If this name wasn't predeclared and if this is not a function call,
791 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000792 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000793 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
794 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000795 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
796 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000797 return ExprError(Diag(Loc, diag::err_undeclared_use)
798 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000799 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
802 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000803
804 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
805 // Warn about constructs like:
806 // if (void *X = foo()) { ... } else { X }.
807 // In the else block, the pointer is always false.
808
809 // FIXME: In a template instantiation, we don't have scope
810 // information to check this property.
811 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
812 Scope *CheckS = S;
813 while (CheckS) {
814 if (CheckS->isWithinElse() &&
815 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
816 if (Var->getType()->isBooleanType())
817 ExprError(Diag(Loc, diag::warn_value_always_false)
818 << Var->getDeclName());
819 else
820 ExprError(Diag(Loc, diag::warn_value_always_zero)
821 << Var->getDeclName());
822 break;
823 }
824
825 // Move up one more control parent to check again.
826 CheckS = CheckS->getControlParent();
827 if (CheckS)
828 CheckS = CheckS->getParent();
829 }
830 }
831 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
832 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
833 // C99 DR 316 says that, if a function type comes from a
834 // function definition (without a prototype), that type is only
835 // used for checking compatibility. Therefore, when referencing
836 // the function, we pretend that we don't have the full function
837 // type.
838 if (DiagnoseUseOfDecl(Func, Loc))
839 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000840
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000841 QualType T = Func->getType();
842 QualType NoProtoType = T;
843 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
844 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
845 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
846 }
847 }
848
849 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
850}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000851/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000852bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000853Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
854 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
855 if (CXXRecordDecl *RD =
856 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
857 QualType DestType =
858 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000859 if (DestType->isDependentType() || From->getType()->isDependentType())
860 return false;
861 QualType FromRecordType = From->getType();
862 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000863 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000864 DestType = Context.getPointerType(DestType);
865 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000866 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000867 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
868 CheckDerivedToBaseConversion(FromRecordType,
869 DestRecordType,
870 From->getSourceRange().getBegin(),
871 From->getSourceRange()))
872 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000873 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
874 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000875 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000876 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000877}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000878
Douglas Gregore399ad42009-08-26 22:36:53 +0000879/// \brief Build a MemberExpr or CXXQualifiedMemberExpr, as appropriate.
880static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
881 const CXXScopeSpec *SS, NamedDecl *Member,
882 SourceLocation Loc, QualType Ty) {
883 if (SS && SS->isSet())
884 return new (C) CXXQualifiedMemberExpr(Base, isArrow,
885 (NestedNameSpecifier *)SS->getScopeRep(),
886 SS->getRange(),
887 Member, Loc, Ty);
888
889 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
890}
891
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000892/// \brief Complete semantic analysis for a reference to the given declaration.
893Sema::OwningExprResult
894Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
895 bool HasTrailingLParen,
896 const CXXScopeSpec *SS,
897 bool isAddressOfOperand) {
898 assert(D && "Cannot refer to a NULL declaration");
899 DeclarationName Name = D->getDeclName();
900
Sebastian Redl0c9da212009-02-03 20:19:35 +0000901 // If this is an expression of the form &Class::member, don't build an
902 // implicit member ref, because we want a pointer to the member in general,
903 // not any specific instance's member.
904 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000905 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000906 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000907 QualType DType;
908 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
909 DType = FD->getType().getNonReferenceType();
910 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
911 DType = Method->getType();
912 } else if (isa<OverloadedFunctionDecl>(D)) {
913 DType = Context.OverloadTy;
914 }
915 // Could be an inner type. That's diagnosed below, so ignore it here.
916 if (!DType.isNull()) {
917 // The pointer is type- and value-dependent if it points into something
918 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000919 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000920 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000921 }
922 }
923 }
924
Douglas Gregor723d3332009-01-07 00:43:41 +0000925 // We may have found a field within an anonymous union or struct
926 // (C++ [class.union]).
927 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
928 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
929 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000930
Douglas Gregor3257fb52008-12-22 05:46:06 +0000931 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
932 if (!MD->isStatic()) {
933 // C++ [class.mfct.nonstatic]p2:
934 // [...] if name lookup (3.4.1) resolves the name in the
935 // id-expression to a nonstatic nontype member of class X or of
936 // a base class of X, the id-expression is transformed into a
937 // class member access expression (5.2.5) using (*this) (9.3.2)
938 // as the postfix-expression to the left of the '.' operator.
939 DeclContext *Ctx = 0;
940 QualType MemberType;
941 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
942 Ctx = FD->getDeclContext();
943 MemberType = FD->getType();
944
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000945 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000946 MemberType = RefType->getPointeeType();
947 else if (!FD->isMutable()) {
948 unsigned combinedQualifiers
949 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
950 MemberType = MemberType.getQualifiedType(combinedQualifiers);
951 }
952 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
953 if (!Method->isStatic()) {
954 Ctx = Method->getParent();
955 MemberType = Method->getType();
956 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000957 } else if (FunctionTemplateDecl *FunTmpl
958 = dyn_cast<FunctionTemplateDecl>(D)) {
959 if (CXXMethodDecl *Method
960 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
961 if (!Method->isStatic()) {
962 Ctx = Method->getParent();
963 MemberType = Context.OverloadTy;
964 }
965 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000966 } else if (OverloadedFunctionDecl *Ovl
967 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000968 // FIXME: We need an abstraction for iterating over one or more function
969 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000970 for (OverloadedFunctionDecl::function_iterator
971 Func = Ovl->function_begin(),
972 FuncEnd = Ovl->function_end();
973 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000974 CXXMethodDecl *DMethod = 0;
975 if (FunctionTemplateDecl *FunTmpl
976 = dyn_cast<FunctionTemplateDecl>(*Func))
977 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
978 else
979 DMethod = dyn_cast<CXXMethodDecl>(*Func);
980
981 if (DMethod && !DMethod->isStatic()) {
982 Ctx = DMethod->getDeclContext();
983 MemberType = Context.OverloadTy;
984 break;
985 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000986 }
987 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000988
989 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000990 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
991 QualType ThisType = Context.getTagDeclType(MD->getParent());
992 if ((Context.getCanonicalType(CtxType)
993 == Context.getCanonicalType(ThisType)) ||
994 IsDerivedFrom(ThisType, CtxType)) {
995 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000996 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000997 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +0000998 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000999 if (PerformObjectMemberConversion(This, D))
1000 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001001 if (DiagnoseUseOfDecl(D, Loc))
1002 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001003 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1004 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001005 }
1006 }
1007 }
1008 }
1009
Douglas Gregor8acb7272008-12-11 16:49:14 +00001010 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001011 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1012 if (MD->isStatic())
1013 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001014 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1015 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001016 }
1017
Douglas Gregor3257fb52008-12-22 05:46:06 +00001018 // Any other ways we could have found the field in a well-formed
1019 // program would have been turned into implicit member expressions
1020 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1022 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001023 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001024
Chris Lattner4b009652007-07-25 00:24:17 +00001025 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001027 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001028 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001029 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001031
Steve Naroffd6163f32008-09-05 22:11:13 +00001032 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001033 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001034 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1035 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001036 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001037 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1038 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001039 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001040
Douglas Gregoraa57e862009-02-18 21:56:37 +00001041 // Check whether this declaration can be used. Note that we suppress
1042 // this check when we're going to perform argument-dependent lookup
1043 // on this function name, because this might not be the function
1044 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001045 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1046 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001047 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1048 return ExprError();
1049
Steve Naroffd6163f32008-09-05 22:11:13 +00001050 // Only create DeclRefExpr's for valid Decl's.
1051 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052 return ExprError();
1053
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001054 // If the identifier reference is inside a block, and it refers to a value
1055 // that is outside the block, create a BlockDeclRefExpr instead of a
1056 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1057 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001058 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001059 // We do not do this for things like enum constants, global variables, etc,
1060 // as they do not get snapshotted.
1061 //
1062 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001063 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001064 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001065 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001066 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001067 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001068 // This is to record that a 'const' was actually synthesize and added.
1069 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001070 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001071
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001072 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001073 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1074 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001075 }
1076 // If this reference is not in a block or if the referenced variable is
1077 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001078
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001079 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001080 bool ValueDependent = false;
1081 if (getLangOptions().CPlusPlus) {
1082 // C++ [temp.dep.expr]p3:
1083 // An id-expression is type-dependent if it contains:
1084 // - an identifier that was declared with a dependent type,
1085 if (VD->getType()->isDependentType())
1086 TypeDependent = true;
1087 // - FIXME: a template-id that is dependent,
1088 // - a conversion-function-id that specifies a dependent type,
1089 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1090 Name.getCXXNameType()->isDependentType())
1091 TypeDependent = true;
1092 // - a nested-name-specifier that contains a class-name that
1093 // names a dependent type.
1094 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001095 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001096 DC; DC = DC->getParent()) {
1097 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001098 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001099 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1100 if (Context.getTypeDeclType(Record)->isDependentType()) {
1101 TypeDependent = true;
1102 break;
1103 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001104 }
1105 }
1106 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001107
Douglas Gregora5d84612008-12-10 20:57:37 +00001108 // C++ [temp.dep.constexpr]p2:
1109 //
1110 // An identifier is value-dependent if it is:
1111 // - a name declared with a dependent type,
1112 if (TypeDependent)
1113 ValueDependent = true;
1114 // - the name of a non-type template parameter,
1115 else if (isa<NonTypeTemplateParmDecl>(VD))
1116 ValueDependent = true;
1117 // - a constant with integral or enumeration type and is
1118 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001119 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1120 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1121 Dcl->getInit()) {
1122 ValueDependent = Dcl->getInit()->isValueDependent();
1123 }
1124 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001125 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001126
Anders Carlsson4571d812009-06-24 00:10:43 +00001127 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1128 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001129}
1130
Sebastian Redlcd883f72009-01-18 18:53:16 +00001131Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1132 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001133 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001134
Chris Lattner4b009652007-07-25 00:24:17 +00001135 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001136 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001137 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1138 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1139 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001140 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001141
Chris Lattner7e637512008-01-12 08:14:25 +00001142 // Pre-defined identifiers are of type char[x], where x is the length of the
1143 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001144 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001145 if (FunctionDecl *FD = getCurFunctionDecl())
1146 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001147 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1148 Length = MD->getSynthesizedMethodSize();
1149 else {
1150 Diag(Loc, diag::ext_predef_outside_function);
1151 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1152 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1153 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001154
1155
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001156 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001157 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001158 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001159 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001160}
1161
Sebastian Redlcd883f72009-01-18 18:53:16 +00001162Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001163 llvm::SmallString<16> CharBuffer;
1164 CharBuffer.resize(Tok.getLength());
1165 const char *ThisTokBegin = &CharBuffer[0];
1166 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001167
Chris Lattner4b009652007-07-25 00:24:17 +00001168 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1169 Tok.getLocation(), PP);
1170 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001172
1173 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1174
Sebastian Redl75324932009-01-20 22:23:13 +00001175 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1176 Literal.isWide(),
1177 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001178}
1179
Sebastian Redlcd883f72009-01-18 18:53:16 +00001180Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1181 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001182 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1183 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001184 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001185 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001186 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001187 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001188 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001189
Chris Lattner4b009652007-07-25 00:24:17 +00001190 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001191 // Add padding so that NumericLiteralParser can overread by one character.
1192 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001193 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001194
Chris Lattner4b009652007-07-25 00:24:17 +00001195 // Get the spelling of the token, which eliminates trigraphs, etc.
1196 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001197
Chris Lattner4b009652007-07-25 00:24:17 +00001198 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1199 Tok.getLocation(), PP);
1200 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001201 return ExprError();
1202
Chris Lattner1de66eb2007-08-26 03:42:43 +00001203 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001204
Chris Lattner1de66eb2007-08-26 03:42:43 +00001205 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001206 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001207 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001208 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001209 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001210 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001211 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001212 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001213
1214 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1215
Ted Kremenekddedbe22007-11-29 00:56:49 +00001216 // isExact will be set by GetFloatValue().
1217 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001218 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1219 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001220
Chris Lattner1de66eb2007-08-26 03:42:43 +00001221 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001222 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001223 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001224 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001225
Neil Booth7421e9c2007-08-29 22:00:19 +00001226 // long long is a C99 feature.
1227 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001228 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001229 Diag(Tok.getLocation(), diag::ext_longlong);
1230
Chris Lattner4b009652007-07-25 00:24:17 +00001231 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001232 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001233
Chris Lattner4b009652007-07-25 00:24:17 +00001234 if (Literal.GetIntegerValue(ResultVal)) {
1235 // If this value didn't fit into uintmax_t, warn and force to ull.
1236 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001237 Ty = Context.UnsignedLongLongTy;
1238 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001239 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001240 } else {
1241 // If this value fits into a ULL, try to figure out what else it fits into
1242 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001243
Chris Lattner4b009652007-07-25 00:24:17 +00001244 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1245 // be an unsigned int.
1246 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1247
1248 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001249 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001250 if (!Literal.isLong && !Literal.isLongLong) {
1251 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001252 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // Does it fit in a unsigned int?
1255 if (ResultVal.isIntN(IntSize)) {
1256 // Does it fit in a signed int?
1257 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001258 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001259 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001260 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001261 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001262 }
Chris Lattner4b009652007-07-25 00:24:17 +00001263 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001264
Chris Lattner4b009652007-07-25 00:24:17 +00001265 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001266 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001267 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 // Does it fit in a unsigned long?
1270 if (ResultVal.isIntN(LongSize)) {
1271 // Does it fit in a signed long?
1272 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001273 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001274 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001275 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001276 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001277 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001278 }
1279
Chris Lattner4b009652007-07-25 00:24:17 +00001280 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001281 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001282 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 // Does it fit in a unsigned long long?
1285 if (ResultVal.isIntN(LongLongSize)) {
1286 // Does it fit in a signed long long?
1287 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001288 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001289 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001290 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001291 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001292 }
1293 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001294
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // If we still couldn't decide a type, we probably have something that
1296 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001297 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001298 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001299 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001300 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001301 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001302
Chris Lattnere4068872008-05-09 05:59:00 +00001303 if (ResultVal.getBitWidth() != Width)
1304 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001305 }
Sebastian Redl75324932009-01-20 22:23:13 +00001306 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001307 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001308
Chris Lattner1de66eb2007-08-26 03:42:43 +00001309 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1310 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001311 Res = new (Context) ImaginaryLiteral(Res,
1312 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001313
1314 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001315}
1316
Sebastian Redlcd883f72009-01-18 18:53:16 +00001317Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1318 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001319 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001320 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001321 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001322}
1323
1324/// The UsualUnaryConversions() function is *not* called by this routine.
1325/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001326bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001327 SourceLocation OpLoc,
1328 const SourceRange &ExprRange,
1329 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001330 if (exprType->isDependentType())
1331 return false;
1332
Chris Lattner4b009652007-07-25 00:24:17 +00001333 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001334 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001335 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001336 if (isSizeof)
1337 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1338 return false;
1339 }
1340
Chris Lattner95933c12009-04-24 00:30:45 +00001341 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001342 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001343 Diag(OpLoc, diag::ext_sizeof_void_type)
1344 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001345 return false;
1346 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001347
Chris Lattner95933c12009-04-24 00:30:45 +00001348 if (RequireCompleteType(OpLoc, exprType,
1349 isSizeof ? diag::err_sizeof_incomplete_type :
1350 diag::err_alignof_incomplete_type,
1351 ExprRange))
1352 return true;
1353
1354 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001355 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001356 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001357 << exprType << isSizeof << ExprRange;
1358 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001359 }
1360
Chris Lattner95933c12009-04-24 00:30:45 +00001361 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001362}
1363
Chris Lattner8d9f7962009-01-24 20:17:12 +00001364bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1365 const SourceRange &ExprRange) {
1366 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001367
Chris Lattner8d9f7962009-01-24 20:17:12 +00001368 // alignof decl is always ok.
1369 if (isa<DeclRefExpr>(E))
1370 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001371
1372 // Cannot know anything else if the expression is dependent.
1373 if (E->isTypeDependent())
1374 return false;
1375
Douglas Gregor531434b2009-05-02 02:18:30 +00001376 if (E->getBitField()) {
1377 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1378 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001379 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001380
1381 // Alignment of a field access is always okay, so long as it isn't a
1382 // bit-field.
1383 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001384 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001385 return false;
1386
Chris Lattner8d9f7962009-01-24 20:17:12 +00001387 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1388}
1389
Douglas Gregor396f1142009-03-13 21:01:28 +00001390/// \brief Build a sizeof or alignof expression given a type operand.
1391Action::OwningExprResult
1392Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1393 bool isSizeOf, SourceRange R) {
1394 if (T.isNull())
1395 return ExprError();
1396
1397 if (!T->isDependentType() &&
1398 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1399 return ExprError();
1400
1401 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1402 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1403 Context.getSizeType(), OpLoc,
1404 R.getEnd()));
1405}
1406
1407/// \brief Build a sizeof or alignof expression given an expression
1408/// operand.
1409Action::OwningExprResult
1410Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1411 bool isSizeOf, SourceRange R) {
1412 // Verify that the operand is valid.
1413 bool isInvalid = false;
1414 if (E->isTypeDependent()) {
1415 // Delay type-checking for type-dependent expressions.
1416 } else if (!isSizeOf) {
1417 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001418 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001419 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1420 isInvalid = true;
1421 } else {
1422 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1423 }
1424
1425 if (isInvalid)
1426 return ExprError();
1427
1428 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1429 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1430 Context.getSizeType(), OpLoc,
1431 R.getEnd()));
1432}
1433
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001434/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1435/// the same for @c alignof and @c __alignof
1436/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001437Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001438Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1439 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001441 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001442
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001443 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001444 // FIXME: Preserve type source info.
1445 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001446 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1447 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001448
Douglas Gregor396f1142009-03-13 21:01:28 +00001449 // Get the end location.
1450 Expr *ArgEx = (Expr *)TyOrEx;
1451 Action::OwningExprResult Result
1452 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1453
1454 if (Result.isInvalid())
1455 DeleteExpr(ArgEx);
1456
1457 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001458}
1459
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001460QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001461 if (V->isTypeDependent())
1462 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001463
Chris Lattnera16e42d2007-08-26 05:39:26 +00001464 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001465 if (const ComplexType *CT = V->getType()->getAsComplexType())
1466 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001467
1468 // Otherwise they pass through real integer and floating point types here.
1469 if (V->getType()->isArithmeticType())
1470 return V->getType();
1471
1472 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001473 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1474 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001475 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001476}
1477
1478
Chris Lattner4b009652007-07-25 00:24:17 +00001479
Sebastian Redl8b769972009-01-19 00:08:26 +00001480Action::OwningExprResult
1481Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1482 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001483 // Since this might be a postfix expression, get rid of ParenListExprs.
1484 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001485 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001486
Chris Lattner4b009652007-07-25 00:24:17 +00001487 UnaryOperator::Opcode Opc;
1488 switch (Kind) {
1489 default: assert(0 && "Unknown unary op!");
1490 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1491 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1492 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001493
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001494 if (getLangOptions().CPlusPlus &&
1495 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1496 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001497 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001498 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1499
1500 // C++ [over.inc]p1:
1501 //
1502 // [...] If the function is a member function with one
1503 // parameter (which shall be of type int) or a non-member
1504 // function with two parameters (the second of which shall be
1505 // of type int), it defines the postfix increment operator ++
1506 // for objects of that type. When the postfix increment is
1507 // called as a result of using the ++ operator, the int
1508 // argument will have value zero.
1509 Expr *Args[2] = {
1510 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001511 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1512 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001513 };
1514
1515 // Build the candidate set for overloading
1516 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001517 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001518
1519 // Perform overload resolution.
1520 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001521 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001522 case OR_Success: {
1523 // We found a built-in operator or an overloaded operator.
1524 FunctionDecl *FnDecl = Best->Function;
1525
1526 if (FnDecl) {
1527 // We matched an overloaded operator. Build a call to that
1528 // operator.
1529
1530 // Convert the arguments.
1531 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1532 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001533 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001534 } else {
1535 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001536 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001537 FnDecl->getParamDecl(0)->getType(),
1538 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001540 }
1541
1542 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001544 = FnDecl->getType()->getAsFunctionType()->getResultType();
1545 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001546
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001547 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001548 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001549 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001550 UsualUnaryConversions(FnExpr);
1551
Sebastian Redl8b769972009-01-19 00:08:26 +00001552 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001553 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001554 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1555 Args, 2, ResultTy,
1556 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001557 } else {
1558 // We matched a built-in operator. Convert the arguments, then
1559 // break out so that we will build the appropriate built-in
1560 // operator node.
1561 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1562 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001563 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001564
1565 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001566 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001567 }
1568
1569 case OR_No_Viable_Function:
1570 // No viable function; fall through to handling this as a
1571 // built-in operator, which will produce an error message for us.
1572 break;
1573
1574 case OR_Ambiguous:
1575 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1576 << UnaryOperator::getOpcodeStr(Opc)
1577 << Arg->getSourceRange();
1578 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001579 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001580
1581 case OR_Deleted:
1582 Diag(OpLoc, diag::err_ovl_deleted_oper)
1583 << Best->Function->isDeleted()
1584 << UnaryOperator::getOpcodeStr(Opc)
1585 << Arg->getSourceRange();
1586 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1587 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001588 }
1589
1590 // Either we found no viable overloaded operator or we matched a
1591 // built-in operator. In either case, fall through to trying to
1592 // build a built-in operation.
1593 }
1594
Eli Friedman94d30952009-07-22 23:24:42 +00001595 Input.release();
1596 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001597 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001598}
1599
Sebastian Redl8b769972009-01-19 00:08:26 +00001600Action::OwningExprResult
1601Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1602 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001603 // Since this might be a postfix expression, get rid of ParenListExprs.
1604 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1605
Sebastian Redl8b769972009-01-19 00:08:26 +00001606 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1607 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001608
Douglas Gregor80723c52008-11-19 17:17:41 +00001609 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001610 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1611 Base.release();
1612 Idx.release();
1613 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1614 Context.DependentTy, RLoc));
1615 }
1616
1617 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001618 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001619 LHSExp->getType()->isEnumeralType() ||
1620 RHSExp->getType()->isRecordType() ||
1621 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001622 // Add the appropriate overloaded operators (C++ [over.match.oper])
1623 // to the candidate set.
1624 OverloadCandidateSet CandidateSet;
1625 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001626 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1627 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001628
Douglas Gregor80723c52008-11-19 17:17:41 +00001629 // Perform overload resolution.
1630 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001631 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001632 case OR_Success: {
1633 // We found a built-in operator or an overloaded operator.
1634 FunctionDecl *FnDecl = Best->Function;
1635
1636 if (FnDecl) {
1637 // We matched an overloaded operator. Build a call to that
1638 // operator.
1639
1640 // Convert the arguments.
1641 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1642 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1643 PerformCopyInitialization(RHSExp,
1644 FnDecl->getParamDecl(0)->getType(),
1645 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001646 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001647 } else {
1648 // Convert the arguments.
1649 if (PerformCopyInitialization(LHSExp,
1650 FnDecl->getParamDecl(0)->getType(),
1651 "passing") ||
1652 PerformCopyInitialization(RHSExp,
1653 FnDecl->getParamDecl(1)->getType(),
1654 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001656 }
1657
1658 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001659 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001660 = FnDecl->getType()->getAsFunctionType()->getResultType();
1661 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001662
Douglas Gregor80723c52008-11-19 17:17:41 +00001663 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001664 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1665 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001666 UsualUnaryConversions(FnExpr);
1667
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 Base.release();
1669 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001670 Args[0] = LHSExp;
1671 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001672 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1673 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001674 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001675 } else {
1676 // We matched a built-in operator. Convert the arguments, then
1677 // break out so that we will build the appropriate built-in
1678 // operator node.
1679 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1680 "passing") ||
1681 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1682 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001684
1685 break;
1686 }
1687 }
1688
1689 case OR_No_Viable_Function:
1690 // No viable function; fall through to handling this as a
1691 // built-in operator, which will produce an error message for us.
1692 break;
1693
1694 case OR_Ambiguous:
1695 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1696 << "[]"
1697 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1698 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001699 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001700
1701 case OR_Deleted:
1702 Diag(LLoc, diag::err_ovl_deleted_oper)
1703 << Best->Function->isDeleted()
1704 << "[]"
1705 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1707 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001708 }
1709
1710 // Either we found no viable overloaded operator or we matched a
1711 // built-in operator. In either case, fall through to trying to
1712 // build a built-in operation.
1713 }
1714
Chris Lattner4b009652007-07-25 00:24:17 +00001715 // Perform default conversions.
1716 DefaultFunctionArrayConversion(LHSExp);
1717 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001718
Chris Lattner4b009652007-07-25 00:24:17 +00001719 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1720
1721 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001722 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001723 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001724 // and index from the expression types.
1725 Expr *BaseExpr, *IndexExpr;
1726 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001727 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1728 BaseExpr = LHSExp;
1729 IndexExpr = RHSExp;
1730 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001731 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001732 BaseExpr = LHSExp;
1733 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001734 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001735 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001736 // Handle the uncommon case of "123[Ptr]".
1737 BaseExpr = RHSExp;
1738 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001739 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001740 } else if (const ObjCObjectPointerType *PTy =
1741 LHSTy->getAsObjCObjectPointerType()) {
1742 BaseExpr = LHSExp;
1743 IndexExpr = RHSExp;
1744 ResultType = PTy->getPointeeType();
1745 } else if (const ObjCObjectPointerType *PTy =
1746 RHSTy->getAsObjCObjectPointerType()) {
1747 // Handle the uncommon case of "123[Ptr]".
1748 BaseExpr = RHSExp;
1749 IndexExpr = LHSExp;
1750 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001751 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1752 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001753 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001754
Chris Lattner4b009652007-07-25 00:24:17 +00001755 // FIXME: need to deal with const...
1756 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001757 } else if (LHSTy->isArrayType()) {
1758 // If we see an array that wasn't promoted by
1759 // DefaultFunctionArrayConversion, it must be an array that
1760 // wasn't promoted because of the C90 rule that doesn't
1761 // allow promoting non-lvalue arrays. Warn, then
1762 // force the promotion here.
1763 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1764 LHSExp->getSourceRange();
1765 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1766 LHSTy = LHSExp->getType();
1767
1768 BaseExpr = LHSExp;
1769 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001770 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001771 } else if (RHSTy->isArrayType()) {
1772 // Same as previous, except for 123[f().a] case
1773 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1774 RHSExp->getSourceRange();
1775 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1776 RHSTy = RHSExp->getType();
1777
1778 BaseExpr = RHSExp;
1779 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001780 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001781 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001782 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1783 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001784 }
Chris Lattner4b009652007-07-25 00:24:17 +00001785 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001786 if (!(IndexExpr->getType()->isIntegerType() &&
1787 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001788 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1789 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001790
Douglas Gregor05e28f62009-03-24 19:52:54 +00001791 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1792 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1793 // type. Note that Functions are not objects, and that (in C99 parlance)
1794 // incomplete types are not object types.
1795 if (ResultType->isFunctionType()) {
1796 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1797 << ResultType << BaseExpr->getSourceRange();
1798 return ExprError();
1799 }
Chris Lattner95933c12009-04-24 00:30:45 +00001800
Douglas Gregor05e28f62009-03-24 19:52:54 +00001801 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001802 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001803 BaseExpr->getSourceRange()))
1804 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001805
1806 // Diagnose bad cases where we step over interface counts.
1807 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1808 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1809 << ResultType << BaseExpr->getSourceRange();
1810 return ExprError();
1811 }
1812
Sebastian Redl8b769972009-01-19 00:08:26 +00001813 Base.release();
1814 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001815 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001816 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001817}
1818
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001819QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001820CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001821 const IdentifierInfo *CompName,
1822 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001823 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001824
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001825 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001826 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001827
Mike Stump9afab102009-02-19 03:04:26 +00001828 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001829 // special names that indicate a subset of exactly half the elements are
1830 // to be selected.
1831 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001832
Nate Begeman1486b502009-01-18 01:47:54 +00001833 // This flag determines whether or not CompName has an 's' char prefix,
1834 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001835 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001836
1837 // Check that we've found one of the special components, or that the component
1838 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001839 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001840 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1841 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001842 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001843 do
1844 compStr++;
1845 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001846 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001847 do
1848 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001849 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001850 }
Nate Begeman1486b502009-01-18 01:47:54 +00001851
Mike Stump9afab102009-02-19 03:04:26 +00001852 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001853 // We didn't get to the end of the string. This means the component names
1854 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001855 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1856 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001857 return QualType();
1858 }
Mike Stump9afab102009-02-19 03:04:26 +00001859
Nate Begeman1486b502009-01-18 01:47:54 +00001860 // Ensure no component accessor exceeds the width of the vector type it
1861 // operates on.
1862 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001863 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001864
1865 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001866 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001867
1868 while (*compStr) {
1869 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1870 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1871 << baseType << SourceRange(CompLoc);
1872 return QualType();
1873 }
1874 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001875 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001876
Nate Begeman1486b502009-01-18 01:47:54 +00001877 // If this is a halving swizzle, verify that the base type has an even
1878 // number of elements.
1879 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001880 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001881 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001882 return QualType();
1883 }
Mike Stump9afab102009-02-19 03:04:26 +00001884
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001885 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001886 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001887 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001888 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001889 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001890 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001891 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001892 if (HexSwizzle)
1893 CompSize--;
1894
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001895 if (CompSize == 1)
1896 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001897
Nate Begemanaf6ed502008-04-18 23:10:10 +00001898 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001899 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001900 // diagostics look bad. We want extended vector types to appear built-in.
1901 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1902 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1903 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001904 }
1905 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001906}
1907
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001908static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001909 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001910 const Selector &Sel,
1911 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001912
Anders Carlsson9935ab92009-08-26 18:25:21 +00001913 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001914 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001915 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001916 return OMD;
1917
1918 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1919 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001920 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1921 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001922 return D;
1923 }
1924 return 0;
1925}
1926
Steve Naroffc75c1a82009-06-17 22:40:22 +00001927static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001928 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001929 const Selector &Sel,
1930 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001931 // Check protocols on qualified interfaces.
1932 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001933 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001934 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001935 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001936 GDecl = PD;
1937 break;
1938 }
1939 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001940 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001941 GDecl = OMD;
1942 break;
1943 }
1944 }
1945 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001946 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001947 E = QIdTy->qual_end(); I != E; ++I) {
1948 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001949 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001950 if (GDecl)
1951 return GDecl;
1952 }
1953 }
1954 return GDecl;
1955}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001956
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001957/// FindMethodInNestedImplementations - Look up a method in current and
1958/// all base class implementations.
1959///
1960ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1961 const ObjCInterfaceDecl *IFace,
1962 const Selector &Sel) {
1963 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001964 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001965 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001966
1967 if (!Method && IFace->getSuperClass())
1968 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1969 return Method;
1970}
Douglas Gregore399ad42009-08-26 22:36:53 +00001971
Anders Carlsson9935ab92009-08-26 18:25:21 +00001972Action::OwningExprResult
1973Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001974 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001975 DeclarationName MemberName,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001976 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001977 if (SS && SS->isInvalid())
1978 return ExprError();
1979
Nate Begemane85f43d2009-08-10 23:49:36 +00001980 // Since this might be a postfix expression, get rid of ParenListExprs.
1981 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1982
Anders Carlssonc154a722009-05-01 19:30:39 +00001983 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001984 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00001985
Steve Naroff137e11d2007-12-16 21:42:28 +00001986 // Perform default conversions.
1987 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001988
Steve Naroff2cb66382007-07-26 03:11:44 +00001989 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00001990 // If this is an Objective-C pseudo-builtin and a definition is provided then
1991 // use that.
1992 if (BaseType->isObjCIdType()) {
1993 // We have an 'id' type. Rather than fall through, we check if this
1994 // is a reference to 'isa'.
1995 if (BaseType != Context.ObjCIdRedefinitionType) {
1996 BaseType = Context.ObjCIdRedefinitionType;
1997 ImpCastExprToType(BaseExpr, BaseType);
1998 }
1999 } else if (BaseType->isObjCClassType() &&
2000 BaseType != Context.ObjCClassRedefinitionType) {
2001 BaseType = Context.ObjCClassRedefinitionType;
2002 ImpCastExprToType(BaseExpr, BaseType);
2003 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002004 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002005
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002006 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2007 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002008 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002009 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002010 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2011 BaseExpr, true,
2012 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002013 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002014 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002015 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002016 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002017 else if (BaseType->isObjCObjectPointerType())
2018 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002019 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002020 return ExprError(Diag(MemberLoc,
2021 diag::err_typecheck_member_reference_arrow)
2022 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002023 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002024 if (BaseType->isDependentType()) {
2025 // Require that the base type isn't a pointer type
2026 // (so we'll report an error for)
2027 // T* t;
2028 // t.f;
2029 //
2030 // In Obj-C++, however, the above expression is valid, since it could be
2031 // accessing the 'f' property if T is an Obj-C interface. The extra check
2032 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002033 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002034
2035 if (!PT || (getLangOptions().ObjC1 &&
2036 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002037 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2038 BaseExpr, false,
2039 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002040 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002041 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002042 }
Chris Lattner4b009652007-07-25 00:24:17 +00002043 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002044
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002045 // Handle field access to simple records. This also handles access to fields
2046 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002047 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002048 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002049 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002050 diag::err_typecheck_incomplete_tag,
2051 BaseExpr->getSourceRange()))
2052 return ExprError();
2053
Douglas Gregorda61ad22009-08-06 03:17:00 +00002054 DeclContext *DC = RDecl;
2055 if (SS && SS->isSet()) {
2056 // If the member name was a qualified-id, look into the
2057 // nested-name-specifier.
2058 DC = computeDeclContext(*SS, false);
2059
2060 // FIXME: If DC is not computable, we should build a
2061 // CXXUnresolvedMemberExpr.
2062 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2063 }
2064
Steve Naroff2cb66382007-07-26 03:11:44 +00002065 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002066 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002067 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002068
Douglas Gregor12431cb2009-08-06 05:28:30 +00002069 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002070 QualType BaseTypeCanon
2071 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2072 QualType MemberTypeCanon
2073 = Context.getCanonicalType(
2074 Context.getTypeDeclType(
2075 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2076
2077 if (BaseTypeCanon != MemberTypeCanon &&
2078 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2079 return ExprError(Diag(SS->getBeginLoc(),
2080 diag::err_not_direct_base_or_virtual)
2081 << MemberTypeCanon << BaseTypeCanon);
2082 }
2083
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002084 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002085 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002086 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002087 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002088 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2089 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002090 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002091 }
2092
2093 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002094
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002095 // If the decl being referenced had an error, return an error for this
2096 // sub-expr without emitting another error, in order to avoid cascading
2097 // error cases.
2098 if (MemberDecl->isInvalidDecl())
2099 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002100
Douglas Gregoraa57e862009-02-18 21:56:37 +00002101 // Check the use of this field
2102 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2103 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002104
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002105 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002106 // We may have found a field within an anonymous union or struct
2107 // (C++ [class.union]).
2108 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002109 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002110 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002111
Douglas Gregor82d44772008-12-20 23:49:58 +00002112 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002113 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002114 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002115 MemberType = Ref->getPointeeType();
2116 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002117 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002118 unsigned combinedQualifiers =
2119 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002120 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002121 combinedQualifiers &= ~QualType::Const;
2122 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002123 if (BaseAddrSpace != MemberType.getAddressSpace())
2124 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002125 }
Eli Friedman76b49832008-02-06 22:48:16 +00002126
Douglas Gregorcad27f62009-06-22 23:06:13 +00002127 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002128 if (PerformObjectMemberConversion(BaseExpr, FD))
2129 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002130 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2131 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002132 }
2133
Douglas Gregorcad27f62009-06-22 23:06:13 +00002134 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2135 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002136 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2137 Var, MemberLoc,
2138 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002139 }
2140 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2141 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002142 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2143 MemberFn, MemberLoc,
2144 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002145 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002146 if (FunctionTemplateDecl *FunTmpl
2147 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2148 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002149 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2150 FunTmpl, MemberLoc,
2151 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002152 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002153 if (OverloadedFunctionDecl *Ovl
2154 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregore399ad42009-08-26 22:36:53 +00002155 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2156 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002157 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2158 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002159 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2160 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002161 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002162 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002163 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002164 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002165
Douglas Gregor82d44772008-12-20 23:49:58 +00002166 // We found a declaration kind that we didn't expect. This is a
2167 // generic error message that tells the user that she can't refer
2168 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002169 return ExprError(Diag(MemberLoc,
2170 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002171 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002172 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002173
Steve Naroff329ec222009-07-10 23:34:53 +00002174 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002175 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002176 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002177 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2178 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002179 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2180 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2181 ObjCMethodDecl *Getter;
2182 // FIXME: need to also look locally in the implementation.
2183 if ((Getter = IFace->lookupClassMethod(Sel))) {
2184 // Check the use of this method.
2185 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2186 return ExprError();
2187 }
2188 // If we found a getter then this may be a valid dot-reference, we
2189 // will look for the matching setter, in case it is needed.
2190 Selector SetterSel =
2191 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002192 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002193 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2194 if (!Setter) {
2195 // If this reference is in an @implementation, also check for 'private'
2196 // methods.
2197 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2198 }
2199 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002200 if (!Setter)
2201 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002202
2203 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2204 return ExprError();
2205
2206 if (Getter || Setter) {
2207 QualType PType;
2208
2209 if (Getter)
2210 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002211 else
2212 // Get the expression type from Setter's incoming parameter.
2213 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002214 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002215 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002216 Setter, MemberLoc, BaseExpr));
2217 }
2218 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002219 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002220 }
2221 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002222 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2223 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002224 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2225 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2226 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2227 const ObjCInterfaceType *IFaceT =
2228 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002229 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002230 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2231
Steve Naroff4e743962009-07-16 00:25:06 +00002232 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2233 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002234 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002235
2236 if (IV) {
2237 // If the decl being referenced had an error, return an error for this
2238 // sub-expr without emitting another error, in order to avoid cascading
2239 // error cases.
2240 if (IV->isInvalidDecl())
2241 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002242
Steve Naroff4e743962009-07-16 00:25:06 +00002243 // Check whether we can reference this field.
2244 if (DiagnoseUseOfDecl(IV, MemberLoc))
2245 return ExprError();
2246 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2247 IV->getAccessControl() != ObjCIvarDecl::Package) {
2248 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2249 if (ObjCMethodDecl *MD = getCurMethodDecl())
2250 ClassOfMethodDecl = MD->getClassInterface();
2251 else if (ObjCImpDecl && getCurFunctionDecl()) {
2252 // Case of a c-function declared inside an objc implementation.
2253 // FIXME: For a c-style function nested inside an objc implementation
2254 // class, there is no implementation context available, so we pass
2255 // down the context as argument to this routine. Ideally, this context
2256 // need be passed down in the AST node and somehow calculated from the
2257 // AST for a function decl.
2258 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2259 if (ObjCImplementationDecl *IMPD =
2260 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2261 ClassOfMethodDecl = IMPD->getClassInterface();
2262 else if (ObjCCategoryImplDecl* CatImplClass =
2263 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2264 ClassOfMethodDecl = CatImplClass->getClassInterface();
2265 }
2266
2267 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2268 if (ClassDeclared != IDecl ||
2269 ClassOfMethodDecl != ClassDeclared)
2270 Diag(MemberLoc, diag::error_private_ivar_access)
2271 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002272 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2273 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002274 Diag(MemberLoc, diag::error_protected_ivar_access)
2275 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002276 }
Steve Naroff4e743962009-07-16 00:25:06 +00002277
2278 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2279 MemberLoc, BaseExpr,
2280 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002281 }
Steve Naroff4e743962009-07-16 00:25:06 +00002282 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002283 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002284 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002285 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002286 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002287 // Handle properties on 'id' and qualified "id".
2288 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2289 BaseType->isObjCQualifiedIdType())) {
2290 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002291 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002292
Steve Naroff329ec222009-07-10 23:34:53 +00002293 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002294 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002295 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2296 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2297 // Check the use of this declaration
2298 if (DiagnoseUseOfDecl(PD, MemberLoc))
2299 return ExprError();
2300
2301 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2302 MemberLoc, BaseExpr));
2303 }
2304 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2305 // Check the use of this method.
2306 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2307 return ExprError();
2308
2309 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2310 OMD->getResultType(),
2311 OMD, OpLoc, MemberLoc,
2312 NULL, 0));
2313 }
2314 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002315
Steve Naroff329ec222009-07-10 23:34:53 +00002316 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002317 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002318 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002319 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2320 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002321 const ObjCObjectPointerType *OPT;
2322 if (OpKind == tok::period &&
2323 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2324 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2325 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002326 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002327
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002328 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002329 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002330 // Check whether we can reference this property.
2331 if (DiagnoseUseOfDecl(PD, MemberLoc))
2332 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002333 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002334 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002335 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002336 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2337 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002338 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002339 MemberLoc, BaseExpr));
2340 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002341 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002342 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2343 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002344 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002345 // Check whether we can reference this property.
2346 if (DiagnoseUseOfDecl(PD, MemberLoc))
2347 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002348
Steve Naroff774e4152009-01-21 00:14:39 +00002349 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002350 MemberLoc, BaseExpr));
2351 }
Steve Naroff329ec222009-07-10 23:34:53 +00002352 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2353 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002354 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002355 // Check whether we can reference this property.
2356 if (DiagnoseUseOfDecl(PD, MemberLoc))
2357 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002358
Steve Naroff329ec222009-07-10 23:34:53 +00002359 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2360 MemberLoc, BaseExpr));
2361 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002362 // If that failed, look for an "implicit" property by seeing if the nullary
2363 // selector is implemented.
2364
2365 // FIXME: The logic for looking up nullary and unary selectors should be
2366 // shared with the code in ActOnInstanceMessage.
2367
Anders Carlsson9935ab92009-08-26 18:25:21 +00002368 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002369 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002370
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002371 // If this reference is in an @implementation, check for 'private' methods.
2372 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002373 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002374
Steve Naroff04151f32008-10-22 19:16:27 +00002375 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002376 if (!Getter)
2377 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002378 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002379 // Check if we can reference this property.
2380 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2381 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002382 }
2383 // If we found a getter then this may be a valid dot-reference, we
2384 // will look for the matching setter, in case it is needed.
2385 Selector SetterSel =
2386 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002387 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002388 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002389 if (!Setter) {
2390 // If this reference is in an @implementation, also check for 'private'
2391 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002392 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002393 }
2394 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002395 if (!Setter)
2396 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002397
Steve Naroffdede0c92009-03-11 13:48:17 +00002398 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2399 return ExprError();
2400
2401 if (Getter || Setter) {
2402 QualType PType;
2403
2404 if (Getter)
2405 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002406 else
2407 // Get the expression type from Setter's incoming parameter.
2408 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002409 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002410 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002411 Setter, MemberLoc, BaseExpr));
2412 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002413 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002414 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002415 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002416
Steve Naroff29d293b2009-07-24 17:54:45 +00002417 // Handle the following exceptional case (*Obj).isa.
2418 if (OpKind == tok::period &&
2419 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002420 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002421 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2422 Context.getObjCIdType()));
2423
Chris Lattnera57cf472008-07-21 04:28:12 +00002424 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002425 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002426 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002427 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2428 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002429 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002430 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002431 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002432 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002433
Douglas Gregor762da552009-03-27 06:00:30 +00002434 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2435 << BaseType << BaseExpr->getSourceRange();
2436
2437 // If the user is trying to apply -> or . to a function or function
2438 // pointer, it's probably because they forgot parentheses to call
2439 // the function. Suggest the addition of those parentheses.
2440 if (BaseType == Context.OverloadTy ||
2441 BaseType->isFunctionType() ||
2442 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002443 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002444 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2445 Diag(Loc, diag::note_member_reference_needs_call)
2446 << CodeModificationHint::CreateInsertion(Loc, "()");
2447 }
2448
2449 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002450}
2451
Anders Carlsson9935ab92009-08-26 18:25:21 +00002452Action::OwningExprResult
2453Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2454 tok::TokenKind OpKind, SourceLocation MemberLoc,
2455 IdentifierInfo &Member,
2456 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2457 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2458 DeclarationName(&Member), ObjCImpDecl, SS);
2459}
2460
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002461Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2462 FunctionDecl *FD,
2463 ParmVarDecl *Param) {
2464 if (Param->hasUnparsedDefaultArg()) {
2465 Diag (CallLoc,
2466 diag::err_use_of_default_argument_to_function_declared_later) <<
2467 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2468 Diag(UnparsedDefaultArgLocs[Param],
2469 diag::note_default_argument_declared_here);
2470 } else {
2471 if (Param->hasUninstantiatedDefaultArg()) {
2472 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2473
2474 // Instantiate the expression.
2475 const TemplateArgumentList &ArgList = getTemplateInstantiationArgs(FD);
2476
2477 // FIXME: We should really make a new InstantiatingTemplate ctor
2478 // that has a better message - right now we're just piggy-backing
2479 // off the "default template argument" error message.
2480 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
2481 ArgList.getFlatArgumentList(),
2482 ArgList.flat_size());
2483
John McCall0ba26ee2009-08-25 22:02:44 +00002484 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002485 if (Result.isInvalid())
2486 return ExprError();
2487
2488 if (SetParamDefaultArgument(Param, move(Result),
2489 /*FIXME:EqualLoc*/
2490 UninstExpr->getSourceRange().getBegin()))
2491 return ExprError();
2492 }
2493
2494 Expr *DefaultExpr = Param->getDefaultArg();
2495
2496 // If the default expression creates temporaries, we need to
2497 // push them to the current stack of expression temporaries so they'll
2498 // be properly destroyed.
2499 if (CXXExprWithTemporaries *E
2500 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2501 assert(!E->shouldDestroyTemporaries() &&
2502 "Can't destroy temporaries in a default argument expr!");
2503 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2504 ExprTemporaries.push_back(E->getTemporary(I));
2505 }
2506 }
2507
2508 // We already type-checked the argument, so we know it works.
2509 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2510}
2511
Douglas Gregor3257fb52008-12-22 05:46:06 +00002512/// ConvertArgumentsForCall - Converts the arguments specified in
2513/// Args/NumArgs to the parameter types of the function FDecl with
2514/// function prototype Proto. Call is the call expression itself, and
2515/// Fn is the function expression. For a C++ member function, this
2516/// routine does not attempt to convert the object argument. Returns
2517/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002518bool
2519Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002520 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002521 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002522 Expr **Args, unsigned NumArgs,
2523 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002524 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002525 // assignment, to the types of the corresponding parameter, ...
2526 unsigned NumArgsInProto = Proto->getNumArgs();
2527 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002528 bool Invalid = false;
2529
Douglas Gregor3257fb52008-12-22 05:46:06 +00002530 // If too few arguments are available (and we don't have default
2531 // arguments for the remaining parameters), don't make the call.
2532 if (NumArgs < NumArgsInProto) {
2533 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2534 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2535 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2536 // Use default arguments for missing arguments
2537 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002538 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002539 }
2540
2541 // If too many are passed and not variadic, error on the extras and drop
2542 // them.
2543 if (NumArgs > NumArgsInProto) {
2544 if (!Proto->isVariadic()) {
2545 Diag(Args[NumArgsInProto]->getLocStart(),
2546 diag::err_typecheck_call_too_many_args)
2547 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2548 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2549 Args[NumArgs-1]->getLocEnd());
2550 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002551 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002552 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002553 }
2554 NumArgsToCheck = NumArgsInProto;
2555 }
Mike Stump9afab102009-02-19 03:04:26 +00002556
Douglas Gregor3257fb52008-12-22 05:46:06 +00002557 // Continue to check argument types (even if we have too few/many args).
2558 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2559 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002560
Douglas Gregor3257fb52008-12-22 05:46:06 +00002561 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002562 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002563 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002564
Eli Friedman83dec9e2009-03-22 22:00:50 +00002565 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2566 ProtoArgType,
2567 diag::err_call_incomplete_argument,
2568 Arg->getSourceRange()))
2569 return true;
2570
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002571 // Pass the argument.
2572 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2573 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002574 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002575 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002576
2577 OwningExprResult ArgExpr =
2578 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2579 FDecl, Param);
2580 if (ArgExpr.isInvalid())
2581 return true;
2582
2583 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002584 }
2585
Douglas Gregor3257fb52008-12-22 05:46:06 +00002586 Call->setArg(i, Arg);
2587 }
Mike Stump9afab102009-02-19 03:04:26 +00002588
Douglas Gregor3257fb52008-12-22 05:46:06 +00002589 // If this is a variadic call, handle args passed through "...".
2590 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002591 VariadicCallType CallType = VariadicFunction;
2592 if (Fn->getType()->isBlockPointerType())
2593 CallType = VariadicBlock; // Block
2594 else if (isa<MemberExpr>(Fn))
2595 CallType = VariadicMethod;
2596
Douglas Gregor3257fb52008-12-22 05:46:06 +00002597 // Promote the arguments (C99 6.5.2.2p7).
2598 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2599 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002600 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002601 Call->setArg(i, Arg);
2602 }
2603 }
2604
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002605 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002606}
2607
Steve Naroff87d58b42007-09-16 03:34:24 +00002608/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002609/// This provides the location of the left/right parens and a list of comma
2610/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002611Action::OwningExprResult
2612Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2613 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002614 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002615 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002616
2617 // Since this might be a postfix expression, get rid of ParenListExprs.
2618 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2619
Anders Carlssonc154a722009-05-01 19:30:39 +00002620 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002621 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002622 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002623 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002624 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002625 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002626
Douglas Gregor3257fb52008-12-22 05:46:06 +00002627 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002628 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002629 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002630 // FIXME: Will need to cache the results of name lookup (including ADL) in
2631 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002632 bool Dependent = false;
2633 if (Fn->isTypeDependent())
2634 Dependent = true;
2635 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2636 Dependent = true;
2637
2638 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002639 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002640 Context.DependentTy, RParenLoc));
2641
2642 // Determine whether this is a call to an object (C++ [over.call.object]).
2643 if (Fn->getType()->isRecordType())
2644 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2645 CommaLocs, RParenLoc));
2646
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002647 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002648 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2649 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2650 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2651 isa<CXXMethodDecl>(MemDecl) ||
2652 (isa<FunctionTemplateDecl>(MemDecl) &&
2653 isa<CXXMethodDecl>(
2654 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002655 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2656 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002657 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002658 }
2659
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002660 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002661 // Also, in C++, keep track of whether we should perform argument-dependent
2662 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002663 Expr *FnExpr = Fn;
2664 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002665 bool HasExplicitTemplateArgs = 0;
2666 const TemplateArgument *ExplicitTemplateArgs = 0;
2667 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002668 while (true) {
2669 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2670 FnExpr = IcExpr->getSubExpr();
2671 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002672 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002673 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002674 ADL = false;
2675 FnExpr = PExpr->getSubExpr();
2676 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002677 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002678 == UnaryOperator::AddrOf) {
2679 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002680 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002681 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2682 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002683 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002684 break;
Mike Stump9afab102009-02-19 03:04:26 +00002685 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002686 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2687 UnqualifiedName = DepName->getName();
2688 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002689 } else if (TemplateIdRefExpr *TemplateIdRef
2690 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2691 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002692 if (!NDecl)
2693 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002694 HasExplicitTemplateArgs = true;
2695 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2696 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2697
2698 // C++ [temp.arg.explicit]p6:
2699 // [Note: For simple function names, argument dependent lookup (3.4.2)
2700 // applies even when the function name is not visible within the
2701 // scope of the call. This is because the call still has the syntactic
2702 // form of a function call (3.4.1). But when a function template with
2703 // explicit template arguments is used, the call does not have the
2704 // correct syntactic form unless there is a function template with
2705 // that name visible at the point of the call. If no such name is
2706 // visible, the call is not syntactically well-formed and
2707 // argument-dependent lookup does not apply. If some such name is
2708 // visible, argument dependent lookup applies and additional function
2709 // templates may be found in other namespaces.
2710 //
2711 // The summary of this paragraph is that, if we get to this point and the
2712 // template-id was not a qualified name, then argument-dependent lookup
2713 // is still possible.
2714 if (TemplateIdRef->getQualifier())
2715 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002716 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002717 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002718 // Any kind of name that does not refer to a declaration (or
2719 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2720 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002721 break;
2722 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002723 }
Mike Stump9afab102009-02-19 03:04:26 +00002724
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002725 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002726 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002727 if (NDecl) {
2728 FDecl = dyn_cast<FunctionDecl>(NDecl);
2729 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002730 FDecl = FunctionTemplate->getTemplatedDecl();
2731 else
Douglas Gregor28857752009-06-30 22:34:41 +00002732 FDecl = dyn_cast<FunctionDecl>(NDecl);
2733 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002734 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002735
Douglas Gregorb60eb752009-06-25 22:08:12 +00002736 if (Ovl || FunctionTemplate ||
2737 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002738 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002739 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002740 ADL = false;
2741
Douglas Gregorfcb19192009-02-11 23:02:49 +00002742 // We don't perform ADL in C.
2743 if (!getLangOptions().CPlusPlus)
2744 ADL = false;
2745
Douglas Gregorb60eb752009-06-25 22:08:12 +00002746 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002747 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2748 HasExplicitTemplateArgs,
2749 ExplicitTemplateArgs,
2750 NumExplicitTemplateArgs,
2751 LParenLoc, Args, NumArgs, CommaLocs,
2752 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002753 if (!FDecl)
2754 return ExprError();
2755
2756 // Update Fn to refer to the actual function selected.
2757 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002758 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002759 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002760 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2761 QDRExpr->getLocation(),
2762 false, false,
2763 QDRExpr->getQualifierRange(),
2764 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002765 else
Mike Stump9afab102009-02-19 03:04:26 +00002766 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002767 Fn->getSourceRange().getBegin());
2768 Fn->Destroy(Context);
2769 Fn = NewFn;
2770 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002771 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002772
2773 // Promote the function operand.
2774 UsualUnaryConversions(Fn);
2775
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002776 // Make the call expr early, before semantic checks. This guarantees cleanup
2777 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002778 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2779 Args, NumArgs,
2780 Context.BoolTy,
2781 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002782
Steve Naroffd6163f32008-09-05 22:11:13 +00002783 const FunctionType *FuncT;
2784 if (!Fn->getType()->isBlockPointerType()) {
2785 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2786 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002787 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002788 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002789 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2790 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002791 FuncT = PT->getPointeeType()->getAsFunctionType();
2792 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002793 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002794 getAsFunctionType();
2795 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002796 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002797 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2798 << Fn->getType() << Fn->getSourceRange());
2799
Eli Friedman83dec9e2009-03-22 22:00:50 +00002800 // Check for a valid return type
2801 if (!FuncT->getResultType()->isVoidType() &&
2802 RequireCompleteType(Fn->getSourceRange().getBegin(),
2803 FuncT->getResultType(),
2804 diag::err_call_incomplete_return,
2805 TheCall->getSourceRange()))
2806 return ExprError();
2807
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002808 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002809 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002810
Douglas Gregor4fa58902009-02-26 23:50:07 +00002811 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002812 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002813 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002814 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002815 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002816 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002817
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002818 if (FDecl) {
2819 // Check if we have too few/too many template arguments, based
2820 // on our knowledge of the function definition.
2821 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002822 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002823 const FunctionProtoType *Proto =
2824 Def->getType()->getAsFunctionProtoType();
2825 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2826 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2827 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2828 }
2829 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002830 }
2831
Steve Naroffdb65e052007-08-28 23:30:39 +00002832 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002833 for (unsigned i = 0; i != NumArgs; i++) {
2834 Expr *Arg = Args[i];
2835 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002836 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2837 Arg->getType(),
2838 diag::err_call_incomplete_argument,
2839 Arg->getSourceRange()))
2840 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002841 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002842 }
Chris Lattner4b009652007-07-25 00:24:17 +00002843 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002844
Douglas Gregor3257fb52008-12-22 05:46:06 +00002845 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2846 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002847 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2848 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002849
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002850 // Check for sentinels
2851 if (NDecl)
2852 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002853
Chris Lattner2e64c072007-08-10 20:18:51 +00002854 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002855 if (FDecl) {
2856 if (CheckFunctionCall(FDecl, TheCall.get()))
2857 return ExprError();
2858
2859 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2860 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2861 } else if (NDecl) {
2862 if (CheckBlockCall(NDecl, TheCall.get()))
2863 return ExprError();
2864 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002865
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002866 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002867}
2868
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002869Action::OwningExprResult
2870Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2871 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002872 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002873 //FIXME: Preserve type source info.
2874 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002875 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002876 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002877 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002878
Eli Friedman8c2173d2008-05-20 05:22:08 +00002879 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002880 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002881 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2882 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002883 } else if (!literalType->isDependentType() &&
2884 RequireCompleteType(LParenLoc, literalType,
2885 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002886 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002887 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002888
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002889 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002890 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002891 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002892
Chris Lattnere5cb5862008-12-04 23:50:19 +00002893 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002894 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002895 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002896 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002897 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002898 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002899 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002900 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002901}
2902
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002903Action::OwningExprResult
2904Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002905 SourceLocation RBraceLoc) {
2906 unsigned NumInit = initlist.size();
2907 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002908
Steve Naroff0acc9c92007-09-15 18:49:24 +00002909 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002910 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002911
Mike Stump9afab102009-02-19 03:04:26 +00002912 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002913 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002914 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002915 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002916}
2917
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002918/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002919bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002920 CastExpr::CastKind& Kind,
2921 CXXMethodDecl *& ConversionDecl,
2922 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002923 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002924 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2925 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002926
Eli Friedman01e0f652009-08-15 19:02:19 +00002927 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002928
2929 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2930 // type needs to be scalar.
2931 if (castType->isVoidType()) {
2932 // Cast to void allows any expr type.
2933 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002934 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2935 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2936 (castType->isStructureType() || castType->isUnionType())) {
2937 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002938 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002939 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2940 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002941 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002942 } else if (castType->isUnionType()) {
2943 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002944 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002945 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002946 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002947 Field != FieldEnd; ++Field) {
2948 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2949 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2950 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2951 << castExpr->getSourceRange();
2952 break;
2953 }
2954 }
2955 if (Field == FieldEnd)
2956 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2957 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002958 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002959 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002960 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002961 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002962 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002963 }
Mike Stump9afab102009-02-19 03:04:26 +00002964 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002965 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002966 return Diag(castExpr->getLocStart(),
2967 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002968 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00002969 } else if (castType->isExtVectorType()) {
2970 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002971 return true;
2972 } else if (castType->isVectorType()) {
2973 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2974 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00002975 } else if (castExpr->getType()->isVectorType()) {
2976 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2977 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002978 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002979 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002980 } else if (!castType->isArithmeticType()) {
2981 QualType castExprType = castExpr->getType();
2982 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2983 return Diag(castExpr->getLocStart(),
2984 diag::err_cast_pointer_from_non_pointer_int)
2985 << castExprType << castExpr->getSourceRange();
2986 } else if (!castExpr->getType()->isArithmeticType()) {
2987 if (!castType->isIntegralType() && castType->isArithmeticType())
2988 return Diag(castExpr->getLocStart(),
2989 diag::err_cast_pointer_to_non_pointer_int)
2990 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002991 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00002992 if (isa<ObjCSelectorExpr>(castExpr))
2993 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002994 return false;
2995}
2996
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002997bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002998 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002999
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003000 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003001 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003002 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003003 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003004 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003005 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003006 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003007 } else
3008 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003009 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003010 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003011
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003012 return false;
3013}
3014
Nate Begemanbd42e022009-06-26 00:50:28 +00003015bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3016 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3017
Nate Begeman9e063702009-06-27 22:05:55 +00003018 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3019 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003020 if (SrcTy->isVectorType()) {
3021 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3022 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3023 << DestTy << SrcTy << R;
3024 return false;
3025 }
3026
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003027 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003028 // conversion will take place first from scalar to elt type, and then
3029 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003030 if (SrcTy->isPointerType())
3031 return Diag(R.getBegin(),
3032 diag::err_invalid_conversion_between_vector_and_scalar)
3033 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003034 return false;
3035}
3036
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003037Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003038Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003039 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003040 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3041
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003042 assert((Ty != 0) && (Op.get() != 0) &&
3043 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003044
Nate Begemane85f43d2009-08-10 23:49:36 +00003045 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003046 //FIXME: Preserve type source info.
3047 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003048
3049 // If the Expr being casted is a ParenListExpr, handle it specially.
3050 if (isa<ParenListExpr>(castExpr))
3051 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003052 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003053 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003054 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003055 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003056
3057 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003058 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003059 Kind, castExpr, castType,
3060 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003061}
3062
Nate Begemane85f43d2009-08-10 23:49:36 +00003063/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3064/// of comma binary operators.
3065Action::OwningExprResult
3066Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3067 Expr *expr = EA.takeAs<Expr>();
3068 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3069 if (!E)
3070 return Owned(expr);
3071
3072 OwningExprResult Result(*this, E->getExpr(0));
3073
3074 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3075 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3076 Owned(E->getExpr(i)));
3077
3078 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3079}
3080
3081Action::OwningExprResult
3082Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3083 SourceLocation RParenLoc, ExprArg Op,
3084 QualType Ty) {
3085 ParenListExpr *PE = (ParenListExpr *)Op.get();
3086
3087 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3088 // then handle it as such.
3089 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3090 if (PE->getNumExprs() == 0) {
3091 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3092 return ExprError();
3093 }
3094
3095 llvm::SmallVector<Expr *, 8> initExprs;
3096 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3097 initExprs.push_back(PE->getExpr(i));
3098
3099 // FIXME: This means that pretty-printing the final AST will produce curly
3100 // braces instead of the original commas.
3101 Op.release();
3102 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3103 initExprs.size(), RParenLoc);
3104 E->setType(Ty);
3105 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3106 Owned(E));
3107 } else {
3108 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3109 // sequence of BinOp comma operators.
3110 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3111 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3112 }
3113}
3114
3115Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3116 SourceLocation R,
3117 MultiExprArg Val) {
3118 unsigned nexprs = Val.size();
3119 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3120 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3121 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3122 return Owned(expr);
3123}
3124
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003125/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3126/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003127/// C99 6.5.15
3128QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3129 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003130 // C++ is sufficiently different to merit its own checker.
3131 if (getLangOptions().CPlusPlus)
3132 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3133
Chris Lattnere2897262009-02-18 04:28:32 +00003134 UsualUnaryConversions(Cond);
3135 UsualUnaryConversions(LHS);
3136 UsualUnaryConversions(RHS);
3137 QualType CondTy = Cond->getType();
3138 QualType LHSTy = LHS->getType();
3139 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003140
3141 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003142 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3143 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3144 << CondTy;
3145 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003146 }
Mike Stump9afab102009-02-19 03:04:26 +00003147
Chris Lattner992ae932008-01-06 22:42:25 +00003148 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003149 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3150 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003151
Chris Lattner992ae932008-01-06 22:42:25 +00003152 // If both operands have arithmetic type, do the usual arithmetic conversions
3153 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003154 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3155 UsualArithmeticConversions(LHS, RHS);
3156 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003157 }
Mike Stump9afab102009-02-19 03:04:26 +00003158
Chris Lattner992ae932008-01-06 22:42:25 +00003159 // If both operands are the same structure or union type, the result is that
3160 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003161 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3162 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003163 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003164 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003165 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003166 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003167 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003168 }
Mike Stump9afab102009-02-19 03:04:26 +00003169
Chris Lattner992ae932008-01-06 22:42:25 +00003170 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003171 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003172 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3173 if (!LHSTy->isVoidType())
3174 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3175 << RHS->getSourceRange();
3176 if (!RHSTy->isVoidType())
3177 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3178 << LHS->getSourceRange();
3179 ImpCastExprToType(LHS, Context.VoidTy);
3180 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003181 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003182 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003183 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3184 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003185 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003186 RHS->isNullPointerConstant(Context)) {
3187 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3188 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003189 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003190 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003191 LHS->isNullPointerConstant(Context)) {
3192 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3193 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003194 }
David Chisnall44663db2009-08-17 16:35:33 +00003195 // Handle things like Class and struct objc_class*. Here we case the result
3196 // to the pseudo-builtin, because that will be implicitly cast back to the
3197 // redefinition type if an attempt is made to access its fields.
3198 if (LHSTy->isObjCClassType() &&
3199 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3200 ImpCastExprToType(RHS, LHSTy);
3201 return LHSTy;
3202 }
3203 if (RHSTy->isObjCClassType() &&
3204 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3205 ImpCastExprToType(LHS, RHSTy);
3206 return RHSTy;
3207 }
3208 // And the same for struct objc_object* / id
3209 if (LHSTy->isObjCIdType() &&
3210 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3211 ImpCastExprToType(RHS, LHSTy);
3212 return LHSTy;
3213 }
3214 if (RHSTy->isObjCIdType() &&
3215 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3216 ImpCastExprToType(LHS, RHSTy);
3217 return RHSTy;
3218 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003219 // Handle block pointer types.
3220 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3221 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3222 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3223 QualType destType = Context.getPointerType(Context.VoidTy);
3224 ImpCastExprToType(LHS, destType);
3225 ImpCastExprToType(RHS, destType);
3226 return destType;
3227 }
3228 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3229 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3230 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003231 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003232 // We have 2 block pointer types.
3233 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3234 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003235 return LHSTy;
3236 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003237 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003238 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3239 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003240
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003241 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3242 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003243 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3244 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3245 // In this situation, we assume void* type. No especially good
3246 // reason, but this is what gcc does, and we do have to pick
3247 // to get a consistent AST.
3248 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3249 ImpCastExprToType(LHS, incompatTy);
3250 ImpCastExprToType(RHS, incompatTy);
3251 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003252 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003253 // The block pointer types are compatible.
3254 ImpCastExprToType(LHS, LHSTy);
3255 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003256 return LHSTy;
3257 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003258 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003259 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003260
3261 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3262 // Two identical object pointer types are always compatible.
3263 return LHSTy;
3264 }
Steve Naroff329ec222009-07-10 23:34:53 +00003265 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3266 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003267 QualType compositeType = LHSTy;
3268
3269 // If both operands are interfaces and either operand can be
3270 // assigned to the other, use that type as the composite
3271 // type. This allows
3272 // xxx ? (A*) a : (B*) b
3273 // where B is a subclass of A.
3274 //
3275 // Additionally, as for assignment, if either type is 'id'
3276 // allow silent coercion. Finally, if the types are
3277 // incompatible then make sure to use 'id' as the composite
3278 // type so the result is acceptable for sending messages to.
3279
3280 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3281 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003282 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003283 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003284 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003285 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003286 } else if ((LHSTy->isObjCQualifiedIdType() ||
3287 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003288 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003289 // Need to handle "id<xx>" explicitly.
3290 // GCC allows qualified id and any Objective-C type to devolve to
3291 // id. Currently localizing to here until clear this should be
3292 // part of ObjCQualifiedIdTypesAreCompatible.
3293 compositeType = Context.getObjCIdType();
3294 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003295 compositeType = Context.getObjCIdType();
3296 } else {
3297 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3298 << LHSTy << RHSTy
3299 << LHS->getSourceRange() << RHS->getSourceRange();
3300 QualType incompatTy = Context.getObjCIdType();
3301 ImpCastExprToType(LHS, incompatTy);
3302 ImpCastExprToType(RHS, incompatTy);
3303 return incompatTy;
3304 }
3305 // The object pointer types are compatible.
3306 ImpCastExprToType(LHS, compositeType);
3307 ImpCastExprToType(RHS, compositeType);
3308 return compositeType;
3309 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003310 // Check Objective-C object pointer types and 'void *'
3311 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003312 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003313 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3314 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3315 QualType destType = Context.getPointerType(destPointee);
3316 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3317 ImpCastExprToType(RHS, destType); // promote to void*
3318 return destType;
3319 }
3320 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3321 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003322 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003323 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3324 QualType destType = Context.getPointerType(destPointee);
3325 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3326 ImpCastExprToType(LHS, destType); // promote to void*
3327 return destType;
3328 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003329 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3330 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3331 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003332 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3333 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003334
3335 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3336 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3337 // Figure out necessary qualifiers (C99 6.5.15p6)
3338 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3339 QualType destType = Context.getPointerType(destPointee);
3340 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3341 ImpCastExprToType(RHS, destType); // promote to void*
3342 return destType;
3343 }
3344 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3345 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3346 QualType destType = Context.getPointerType(destPointee);
3347 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3348 ImpCastExprToType(RHS, destType); // promote to void*
3349 return destType;
3350 }
3351
3352 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3353 // Two identical pointer types are always compatible.
3354 return LHSTy;
3355 }
3356 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3357 rhptee.getUnqualifiedType())) {
3358 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3359 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3360 // In this situation, we assume void* type. No especially good
3361 // reason, but this is what gcc does, and we do have to pick
3362 // to get a consistent AST.
3363 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3364 ImpCastExprToType(LHS, incompatTy);
3365 ImpCastExprToType(RHS, incompatTy);
3366 return incompatTy;
3367 }
3368 // The pointer types are compatible.
3369 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3370 // differently qualified versions of compatible types, the result type is
3371 // a pointer to an appropriately qualified version of the *composite*
3372 // type.
3373 // FIXME: Need to calculate the composite type.
3374 // FIXME: Need to add qualifiers
3375 ImpCastExprToType(LHS, LHSTy);
3376 ImpCastExprToType(RHS, LHSTy);
3377 return LHSTy;
3378 }
3379
3380 // GCC compatibility: soften pointer/integer mismatch.
3381 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3382 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3383 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3384 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3385 return RHSTy;
3386 }
3387 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3388 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3389 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3390 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3391 return LHSTy;
3392 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003393
Chris Lattner992ae932008-01-06 22:42:25 +00003394 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003395 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3396 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003397 return QualType();
3398}
3399
Steve Naroff87d58b42007-09-16 03:34:24 +00003400/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003401/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003402Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3403 SourceLocation ColonLoc,
3404 ExprArg Cond, ExprArg LHS,
3405 ExprArg RHS) {
3406 Expr *CondExpr = (Expr *) Cond.get();
3407 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003408
3409 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3410 // was the condition.
3411 bool isLHSNull = LHSExpr == 0;
3412 if (isLHSNull)
3413 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003414
3415 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003416 RHSExpr, QuestionLoc);
3417 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003418 return ExprError();
3419
3420 Cond.release();
3421 LHS.release();
3422 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003423 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003424 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003425 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003426}
3427
Chris Lattner4b009652007-07-25 00:24:17 +00003428// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003429// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003430// routine is it effectively iqnores the qualifiers on the top level pointee.
3431// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3432// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003433Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003434Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3435 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003436
David Chisnall44663db2009-08-17 16:35:33 +00003437 if ((lhsType->isObjCClassType() &&
3438 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3439 (rhsType->isObjCClassType() &&
3440 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3441 return Compatible;
3442 }
3443
Chris Lattner4b009652007-07-25 00:24:17 +00003444 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003445 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3446 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003447
Chris Lattner4b009652007-07-25 00:24:17 +00003448 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003449 lhptee = Context.getCanonicalType(lhptee);
3450 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003451
Chris Lattner005ed752008-01-04 18:04:52 +00003452 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003453
3454 // C99 6.5.16.1p1: This following citation is common to constraints
3455 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3456 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003457 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003458 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003459 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003460
Mike Stump9afab102009-02-19 03:04:26 +00003461 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3462 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003463 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003464 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003465 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003466 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003467
Chris Lattner4ca3d772008-01-03 22:56:36 +00003468 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003469 assert(rhptee->isFunctionType());
3470 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003471 }
Mike Stump9afab102009-02-19 03:04:26 +00003472
Chris Lattner4ca3d772008-01-03 22:56:36 +00003473 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003474 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003475 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003476
3477 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003478 assert(lhptee->isFunctionType());
3479 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003480 }
Mike Stump9afab102009-02-19 03:04:26 +00003481 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003482 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003483 lhptee = lhptee.getUnqualifiedType();
3484 rhptee = rhptee.getUnqualifiedType();
3485 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3486 // Check if the pointee types are compatible ignoring the sign.
3487 // We explicitly check for char so that we catch "char" vs
3488 // "unsigned char" on systems where "char" is unsigned.
3489 if (lhptee->isCharType()) {
3490 lhptee = Context.UnsignedCharTy;
3491 } else if (lhptee->isSignedIntegerType()) {
3492 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3493 }
3494 if (rhptee->isCharType()) {
3495 rhptee = Context.UnsignedCharTy;
3496 } else if (rhptee->isSignedIntegerType()) {
3497 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3498 }
3499 if (lhptee == rhptee) {
3500 // Types are compatible ignoring the sign. Qualifier incompatibility
3501 // takes priority over sign incompatibility because the sign
3502 // warning can be disabled.
3503 if (ConvTy != Compatible)
3504 return ConvTy;
3505 return IncompatiblePointerSign;
3506 }
3507 // General pointer incompatibility takes priority over qualifiers.
3508 return IncompatiblePointer;
3509 }
Chris Lattner005ed752008-01-04 18:04:52 +00003510 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003511}
3512
Steve Naroff3454b6c2008-09-04 15:10:53 +00003513/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3514/// block pointer types are compatible or whether a block and normal pointer
3515/// are compatible. It is more restrict than comparing two function pointer
3516// types.
Mike Stump9afab102009-02-19 03:04:26 +00003517Sema::AssignConvertType
3518Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003519 QualType rhsType) {
3520 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003521
Steve Naroff3454b6c2008-09-04 15:10:53 +00003522 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003523 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3524 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003525
Steve Naroff3454b6c2008-09-04 15:10:53 +00003526 // make sure we operate on the canonical type
3527 lhptee = Context.getCanonicalType(lhptee);
3528 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003529
Steve Naroff3454b6c2008-09-04 15:10:53 +00003530 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003531
Steve Naroff3454b6c2008-09-04 15:10:53 +00003532 // For blocks we enforce that qualifiers are identical.
3533 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3534 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003535
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003536 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003537 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003538 return ConvTy;
3539}
3540
Mike Stump9afab102009-02-19 03:04:26 +00003541/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3542/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003543/// pointers. Here are some objectionable examples that GCC considers warnings:
3544///
3545/// int a, *pint;
3546/// short *pshort;
3547/// struct foo *pfoo;
3548///
3549/// pint = pshort; // warning: assignment from incompatible pointer type
3550/// a = pint; // warning: assignment makes integer from pointer without a cast
3551/// pint = a; // warning: assignment makes pointer from integer without a cast
3552/// pint = pfoo; // warning: assignment from incompatible pointer type
3553///
3554/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003555/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003556///
Chris Lattner005ed752008-01-04 18:04:52 +00003557Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003558Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003559 // Get canonical types. We're not formatting these types, just comparing
3560 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003561 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3562 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003563
3564 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003565 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003566
David Chisnall44663db2009-08-17 16:35:33 +00003567 if ((lhsType->isObjCClassType() &&
3568 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3569 (rhsType->isObjCClassType() &&
3570 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3571 return Compatible;
3572 }
3573
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003574 // If the left-hand side is a reference type, then we are in a
3575 // (rare!) case where we've allowed the use of references in C,
3576 // e.g., as a parameter type in a built-in function. In this case,
3577 // just make sure that the type referenced is compatible with the
3578 // right-hand side type. The caller is responsible for adjusting
3579 // lhsType so that the resulting expression does not have reference
3580 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003581 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003582 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003583 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003584 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003585 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003586 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3587 // to the same ExtVector type.
3588 if (lhsType->isExtVectorType()) {
3589 if (rhsType->isExtVectorType())
3590 return lhsType == rhsType ? Compatible : Incompatible;
3591 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3592 return Compatible;
3593 }
3594
Nate Begemanc5f0f652008-07-14 18:02:46 +00003595 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003596 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003597 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003598 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003599 if (getLangOptions().LaxVectorConversions &&
3600 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003601 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003602 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003603 }
3604 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003605 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003606
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003607 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003608 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003609
Chris Lattner390564e2008-04-07 06:49:41 +00003610 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003611 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003612 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003613
Chris Lattner390564e2008-04-07 06:49:41 +00003614 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003615 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003616
Steve Naroff8194a542009-07-20 17:56:53 +00003617 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003618 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003619 if (lhsType->isVoidPointerType()) // an exception to the rule.
3620 return Compatible;
3621 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003622 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003623 if (rhsType->getAs<BlockPointerType>()) {
3624 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003625 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003626
3627 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003628 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003629 return Compatible;
3630 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003631 return Incompatible;
3632 }
3633
3634 if (isa<BlockPointerType>(lhsType)) {
3635 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003636 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003637
Steve Naroffa982c712008-09-29 18:10:17 +00003638 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003639 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003640 return Compatible;
3641
Steve Naroff3454b6c2008-09-04 15:10:53 +00003642 if (rhsType->isBlockPointerType())
3643 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003644
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003645 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003646 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003647 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003648 }
Chris Lattner1853da22008-01-04 23:18:45 +00003649 return Incompatible;
3650 }
3651
Steve Naroff329ec222009-07-10 23:34:53 +00003652 if (isa<ObjCObjectPointerType>(lhsType)) {
3653 if (rhsType->isIntegerType())
3654 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003655
3656 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003657 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003658 if (rhsType->isVoidPointerType()) // an exception to the rule.
3659 return Compatible;
3660 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003661 }
3662 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003663 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3664 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003665 if (Context.typesAreCompatible(lhsType, rhsType))
3666 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003667 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3668 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003669 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003670 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003671 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003672 if (RHSPT->getPointeeType()->isVoidType())
3673 return Compatible;
3674 }
3675 // Treat block pointers as objects.
3676 if (rhsType->isBlockPointerType())
3677 return Compatible;
3678 return Incompatible;
3679 }
Chris Lattner390564e2008-04-07 06:49:41 +00003680 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003681 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003682 if (lhsType == Context.BoolTy)
3683 return Compatible;
3684
3685 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003686 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003687
Mike Stump9afab102009-02-19 03:04:26 +00003688 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003689 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003690
3691 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003692 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003693 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003694 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003695 }
Steve Naroff329ec222009-07-10 23:34:53 +00003696 if (isa<ObjCObjectPointerType>(rhsType)) {
3697 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3698 if (lhsType == Context.BoolTy)
3699 return Compatible;
3700
3701 if (lhsType->isIntegerType())
3702 return PointerToInt;
3703
Steve Naroff8194a542009-07-20 17:56:53 +00003704 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003705 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003706 if (lhsType->isVoidPointerType()) // an exception to the rule.
3707 return Compatible;
3708 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003709 }
3710 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003711 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003712 return Compatible;
3713 return Incompatible;
3714 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003715
Chris Lattner1853da22008-01-04 23:18:45 +00003716 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003717 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003718 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003719 }
3720 return Incompatible;
3721}
3722
Douglas Gregor144b06c2009-04-29 22:16:16 +00003723/// \brief Constructs a transparent union from an expression that is
3724/// used to initialize the transparent union.
3725static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3726 QualType UnionType, FieldDecl *Field) {
3727 // Build an initializer list that designates the appropriate member
3728 // of the transparent union.
3729 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3730 &E, 1,
3731 SourceLocation());
3732 Initializer->setType(UnionType);
3733 Initializer->setInitializedFieldInUnion(Field);
3734
3735 // Build a compound literal constructing a value of the transparent
3736 // union type from this initializer list.
3737 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3738 false);
3739}
3740
3741Sema::AssignConvertType
3742Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3743 QualType FromType = rExpr->getType();
3744
3745 // If the ArgType is a Union type, we want to handle a potential
3746 // transparent_union GCC extension.
3747 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003748 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003749 return Incompatible;
3750
3751 // The field to initialize within the transparent union.
3752 RecordDecl *UD = UT->getDecl();
3753 FieldDecl *InitField = 0;
3754 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003755 for (RecordDecl::field_iterator it = UD->field_begin(),
3756 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003757 it != itend; ++it) {
3758 if (it->getType()->isPointerType()) {
3759 // If the transparent union contains a pointer type, we allow:
3760 // 1) void pointer
3761 // 2) null pointer constant
3762 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003763 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003764 ImpCastExprToType(rExpr, it->getType());
3765 InitField = *it;
3766 break;
3767 }
3768
3769 if (rExpr->isNullPointerConstant(Context)) {
3770 ImpCastExprToType(rExpr, it->getType());
3771 InitField = *it;
3772 break;
3773 }
3774 }
3775
3776 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3777 == Compatible) {
3778 InitField = *it;
3779 break;
3780 }
3781 }
3782
3783 if (!InitField)
3784 return Incompatible;
3785
3786 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3787 return Compatible;
3788}
3789
Chris Lattner005ed752008-01-04 18:04:52 +00003790Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003791Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003792 if (getLangOptions().CPlusPlus) {
3793 if (!lhsType->isRecordType()) {
3794 // C++ 5.17p3: If the left operand is not of class type, the
3795 // expression is implicitly converted (C++ 4) to the
3796 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003797 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3798 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003799 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003800 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003801 }
3802
3803 // FIXME: Currently, we fall through and treat C++ classes like C
3804 // structures.
3805 }
3806
Steve Naroffcdee22d2007-11-27 17:58:44 +00003807 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3808 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003809 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003810 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003811 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003812 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003813 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003814 return Compatible;
3815 }
Mike Stump9afab102009-02-19 03:04:26 +00003816
Chris Lattner5f505bf2007-10-16 02:55:40 +00003817 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003818 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003819 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003820 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003821 //
Mike Stump9afab102009-02-19 03:04:26 +00003822 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003823 if (!lhsType->isReferenceType())
3824 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003825
Chris Lattner005ed752008-01-04 18:04:52 +00003826 Sema::AssignConvertType result =
3827 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003828
Steve Naroff0f32f432007-08-24 22:33:52 +00003829 // C99 6.5.16.1p2: The value of the right operand is converted to the
3830 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003831 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3832 // so that we can use references in built-in functions even in C.
3833 // The getNonReferenceType() call makes sure that the resulting expression
3834 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003835 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003836 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003837 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003838}
3839
Chris Lattner1eafdea2008-11-18 01:30:42 +00003840QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003841 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003842 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003843 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003844 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003845}
3846
Mike Stump9afab102009-02-19 03:04:26 +00003847inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003848 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003849 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003850 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003851 QualType lhsType =
3852 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3853 QualType rhsType =
3854 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003855
Nate Begemanc5f0f652008-07-14 18:02:46 +00003856 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003857 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003858 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003859
Nate Begemanc5f0f652008-07-14 18:02:46 +00003860 // Handle the case of a vector & extvector type of the same size and element
3861 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003862 if (getLangOptions().LaxVectorConversions) {
3863 // FIXME: Should we warn here?
3864 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003865 if (const VectorType *RV = rhsType->getAsVectorType())
3866 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003867 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003868 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003869 }
3870 }
3871 }
Mike Stump9afab102009-02-19 03:04:26 +00003872
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003873 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3874 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3875 bool swapped = false;
3876 if (rhsType->isExtVectorType()) {
3877 swapped = true;
3878 std::swap(rex, lex);
3879 std::swap(rhsType, lhsType);
3880 }
3881
Nate Begemanf1695892009-06-28 19:12:57 +00003882 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003883 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3884 QualType EltTy = LV->getElementType();
3885 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3886 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003887 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003888 if (swapped) std::swap(rex, lex);
3889 return lhsType;
3890 }
3891 }
3892 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3893 rhsType->isRealFloatingType()) {
3894 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003895 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003896 if (swapped) std::swap(rex, lex);
3897 return lhsType;
3898 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003899 }
3900 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003901
Nate Begemanf1695892009-06-28 19:12:57 +00003902 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003903 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003904 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003905 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003906 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003907}
3908
Chris Lattner4b009652007-07-25 00:24:17 +00003909inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003910 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003911{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003912 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003913 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003914
Steve Naroff8f708362007-08-24 19:07:16 +00003915 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003916
Chris Lattner4b009652007-07-25 00:24:17 +00003917 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003918 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003919 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003920}
3921
3922inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003924{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003925 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3926 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3927 return CheckVectorOperands(Loc, lex, rex);
3928 return InvalidOperands(Loc, lex, rex);
3929 }
Chris Lattner4b009652007-07-25 00:24:17 +00003930
Steve Naroff8f708362007-08-24 19:07:16 +00003931 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003932
Chris Lattner4b009652007-07-25 00:24:17 +00003933 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003934 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003935 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003936}
3937
3938inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003939 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003940{
Eli Friedman3cd92882009-03-28 01:22:36 +00003941 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3942 QualType compType = CheckVectorOperands(Loc, lex, rex);
3943 if (CompLHSTy) *CompLHSTy = compType;
3944 return compType;
3945 }
Chris Lattner4b009652007-07-25 00:24:17 +00003946
Eli Friedman3cd92882009-03-28 01:22:36 +00003947 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003948
Chris Lattner4b009652007-07-25 00:24:17 +00003949 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003950 if (lex->getType()->isArithmeticType() &&
3951 rex->getType()->isArithmeticType()) {
3952 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003953 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003954 }
Chris Lattner4b009652007-07-25 00:24:17 +00003955
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003956 // Put any potential pointer into PExp
3957 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00003958 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003959 std::swap(PExp, IExp);
3960
Steve Naroff79ae19a2009-07-14 18:25:06 +00003961 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003962
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003963 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00003964 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00003965
Chris Lattner184f92d2009-04-24 23:50:08 +00003966 // Check for arithmetic on pointers to incomplete types.
3967 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003968 if (getLangOptions().CPlusPlus) {
3969 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003970 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003971 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003972 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003973
3974 // GNU extension: arithmetic on pointer to void
3975 Diag(Loc, diag::ext_gnu_void_ptr)
3976 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003977 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003978 if (getLangOptions().CPlusPlus) {
3979 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3980 << lex->getType() << lex->getSourceRange();
3981 return QualType();
3982 }
3983
3984 // GNU extension: arithmetic on pointer to function
3985 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3986 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00003987 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00003988 // Check if we require a complete type.
3989 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00003990 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00003991 PExp->getType()->isObjCObjectPointerType()) &&
3992 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00003993 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
3994 << PExp->getSourceRange()
3995 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00003996 return QualType();
3997 }
Chris Lattner184f92d2009-04-24 23:50:08 +00003998 // Diagnose bad cases where we step over interface counts.
3999 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4000 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4001 << PointeeTy << PExp->getSourceRange();
4002 return QualType();
4003 }
4004
Eli Friedman3cd92882009-03-28 01:22:36 +00004005 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004006 QualType LHSTy = Context.isPromotableBitField(lex);
4007 if (LHSTy.isNull()) {
4008 LHSTy = lex->getType();
4009 if (LHSTy->isPromotableIntegerType())
4010 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004011 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004012 *CompLHSTy = LHSTy;
4013 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004014 return PExp->getType();
4015 }
4016 }
4017
Chris Lattner1eafdea2008-11-18 01:30:42 +00004018 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004019}
4020
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004021// C99 6.5.6
4022QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004023 SourceLocation Loc, QualType* CompLHSTy) {
4024 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4025 QualType compType = CheckVectorOperands(Loc, lex, rex);
4026 if (CompLHSTy) *CompLHSTy = compType;
4027 return compType;
4028 }
Mike Stump9afab102009-02-19 03:04:26 +00004029
Eli Friedman3cd92882009-03-28 01:22:36 +00004030 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004031
Chris Lattnerf6da2912007-12-09 21:53:25 +00004032 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004033
Chris Lattnerf6da2912007-12-09 21:53:25 +00004034 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004035 if (lex->getType()->isArithmeticType()
4036 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004037 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004038 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004039 }
Steve Naroff329ec222009-07-10 23:34:53 +00004040
Chris Lattnerf6da2912007-12-09 21:53:25 +00004041 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004042 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004043 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004044
Douglas Gregor05e28f62009-03-24 19:52:54 +00004045 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004046
Douglas Gregor05e28f62009-03-24 19:52:54 +00004047 bool ComplainAboutVoid = false;
4048 Expr *ComplainAboutFunc = 0;
4049 if (lpointee->isVoidType()) {
4050 if (getLangOptions().CPlusPlus) {
4051 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4052 << lex->getSourceRange() << rex->getSourceRange();
4053 return QualType();
4054 }
4055
4056 // GNU C extension: arithmetic on pointer to void
4057 ComplainAboutVoid = true;
4058 } else if (lpointee->isFunctionType()) {
4059 if (getLangOptions().CPlusPlus) {
4060 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004061 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004062 return QualType();
4063 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004064
4065 // GNU C extension: arithmetic on pointer to function
4066 ComplainAboutFunc = lex;
4067 } else if (!lpointee->isDependentType() &&
4068 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004069 PDiag(diag::err_typecheck_sub_ptr_object)
4070 << lex->getSourceRange()
4071 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004072 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004073
Chris Lattner184f92d2009-04-24 23:50:08 +00004074 // Diagnose bad cases where we step over interface counts.
4075 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4076 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4077 << lpointee << lex->getSourceRange();
4078 return QualType();
4079 }
4080
Chris Lattnerf6da2912007-12-09 21:53:25 +00004081 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004082 if (rex->getType()->isIntegerType()) {
4083 if (ComplainAboutVoid)
4084 Diag(Loc, diag::ext_gnu_void_ptr)
4085 << lex->getSourceRange() << rex->getSourceRange();
4086 if (ComplainAboutFunc)
4087 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4088 << ComplainAboutFunc->getType()
4089 << ComplainAboutFunc->getSourceRange();
4090
Eli Friedman3cd92882009-03-28 01:22:36 +00004091 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004092 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004093 }
Mike Stump9afab102009-02-19 03:04:26 +00004094
Chris Lattnerf6da2912007-12-09 21:53:25 +00004095 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004096 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004097 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004098
Douglas Gregor05e28f62009-03-24 19:52:54 +00004099 // RHS must be a completely-type object type.
4100 // Handle the GNU void* extension.
4101 if (rpointee->isVoidType()) {
4102 if (getLangOptions().CPlusPlus) {
4103 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4104 << lex->getSourceRange() << rex->getSourceRange();
4105 return QualType();
4106 }
Mike Stump9afab102009-02-19 03:04:26 +00004107
Douglas Gregor05e28f62009-03-24 19:52:54 +00004108 ComplainAboutVoid = true;
4109 } else if (rpointee->isFunctionType()) {
4110 if (getLangOptions().CPlusPlus) {
4111 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004112 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004113 return QualType();
4114 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004115
4116 // GNU extension: arithmetic on pointer to function
4117 if (!ComplainAboutFunc)
4118 ComplainAboutFunc = rex;
4119 } else if (!rpointee->isDependentType() &&
4120 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004121 PDiag(diag::err_typecheck_sub_ptr_object)
4122 << rex->getSourceRange()
4123 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004124 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004125
Eli Friedman143ddc92009-05-16 13:54:38 +00004126 if (getLangOptions().CPlusPlus) {
4127 // Pointee types must be the same: C++ [expr.add]
4128 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4129 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4130 << lex->getType() << rex->getType()
4131 << lex->getSourceRange() << rex->getSourceRange();
4132 return QualType();
4133 }
4134 } else {
4135 // Pointee types must be compatible C99 6.5.6p3
4136 if (!Context.typesAreCompatible(
4137 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4138 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4139 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4140 << lex->getType() << rex->getType()
4141 << lex->getSourceRange() << rex->getSourceRange();
4142 return QualType();
4143 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004144 }
Mike Stump9afab102009-02-19 03:04:26 +00004145
Douglas Gregor05e28f62009-03-24 19:52:54 +00004146 if (ComplainAboutVoid)
4147 Diag(Loc, diag::ext_gnu_void_ptr)
4148 << lex->getSourceRange() << rex->getSourceRange();
4149 if (ComplainAboutFunc)
4150 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4151 << ComplainAboutFunc->getType()
4152 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004153
4154 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004155 return Context.getPointerDiffType();
4156 }
4157 }
Mike Stump9afab102009-02-19 03:04:26 +00004158
Chris Lattner1eafdea2008-11-18 01:30:42 +00004159 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004160}
4161
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004162// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004163QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004164 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004165 // C99 6.5.7p2: Each of the operands shall have integer type.
4166 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004167 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004168
Chris Lattner2c8bff72007-12-12 05:47:28 +00004169 // Shifts don't perform usual arithmetic conversions, they just do integer
4170 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004171 QualType LHSTy = Context.isPromotableBitField(lex);
4172 if (LHSTy.isNull()) {
4173 LHSTy = lex->getType();
4174 if (LHSTy->isPromotableIntegerType())
4175 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004176 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004177 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004178 ImpCastExprToType(lex, LHSTy);
4179
Chris Lattner2c8bff72007-12-12 05:47:28 +00004180 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004181
Ryan Flynnf109fff2009-08-07 16:20:20 +00004182 // Sanity-check shift operands
4183 llvm::APSInt Right;
4184 // Check right/shifter operand
4185 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004186 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004187 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4188 else {
4189 llvm::APInt LeftBits(Right.getBitWidth(),
4190 Context.getTypeSize(lex->getType()));
4191 if (Right.uge(LeftBits))
4192 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4193 }
4194 }
4195
Chris Lattner2c8bff72007-12-12 05:47:28 +00004196 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004197 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004198}
4199
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004200// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004201QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004202 unsigned OpaqueOpc, bool isRelational) {
4203 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4204
Nate Begemanc5f0f652008-07-14 18:02:46 +00004205 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004206 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004207
Chris Lattner254f3bc2007-08-26 01:18:55 +00004208 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004209 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4210 UsualArithmeticConversions(lex, rex);
4211 else {
4212 UsualUnaryConversions(lex);
4213 UsualUnaryConversions(rex);
4214 }
Chris Lattner4b009652007-07-25 00:24:17 +00004215 QualType lType = lex->getType();
4216 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004217
Mike Stumpea3d74e2009-05-07 18:43:07 +00004218 if (!lType->isFloatingType()
4219 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004220 // For non-floating point types, check for self-comparisons of the form
4221 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4222 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004223 // NOTE: Don't warn about comparisons of enum constants. These can arise
4224 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004225 Expr *LHSStripped = lex->IgnoreParens();
4226 Expr *RHSStripped = rex->IgnoreParens();
4227 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4228 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004229 if (DRL->getDecl() == DRR->getDecl() &&
4230 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004231 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004232
4233 if (isa<CastExpr>(LHSStripped))
4234 LHSStripped = LHSStripped->IgnoreParenCasts();
4235 if (isa<CastExpr>(RHSStripped))
4236 RHSStripped = RHSStripped->IgnoreParenCasts();
4237
4238 // Warn about comparisons against a string constant (unless the other
4239 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004240 Expr *literalString = 0;
4241 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004242 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004243 !RHSStripped->isNullPointerConstant(Context)) {
4244 literalString = lex;
4245 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004246 } else if ((isa<StringLiteral>(RHSStripped) ||
4247 isa<ObjCEncodeExpr>(RHSStripped)) &&
4248 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004249 literalString = rex;
4250 literalStringStripped = RHSStripped;
4251 }
4252
4253 if (literalString) {
4254 std::string resultComparison;
4255 switch (Opc) {
4256 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4257 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4258 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4259 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4260 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4261 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4262 default: assert(false && "Invalid comparison operator");
4263 }
4264 Diag(Loc, diag::warn_stringcompare)
4265 << isa<ObjCEncodeExpr>(literalStringStripped)
4266 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004267 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4268 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4269 "strcmp(")
4270 << CodeModificationHint::CreateInsertion(
4271 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004272 resultComparison);
4273 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004274 }
Mike Stump9afab102009-02-19 03:04:26 +00004275
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004276 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004277 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004278
Chris Lattner254f3bc2007-08-26 01:18:55 +00004279 if (isRelational) {
4280 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004281 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004282 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004283 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004284 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004285 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004286 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004287 }
Mike Stump9afab102009-02-19 03:04:26 +00004288
Chris Lattner254f3bc2007-08-26 01:18:55 +00004289 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004290 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004291 }
Mike Stump9afab102009-02-19 03:04:26 +00004292
Chris Lattner22be8422007-08-26 01:10:14 +00004293 bool LHSIsNull = lex->isNullPointerConstant(Context);
4294 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004295
Chris Lattner254f3bc2007-08-26 01:18:55 +00004296 // All of the following pointer related warnings are GCC extensions, except
4297 // when handling null pointer constants. One day, we can consider making them
4298 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004299 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004300 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004301 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004302 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004303 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004304
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004305 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004306 if (LCanPointeeTy == RCanPointeeTy)
4307 return ResultTy;
4308
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004309 // C++ [expr.rel]p2:
4310 // [...] Pointer conversions (4.10) and qualification
4311 // conversions (4.4) are performed on pointer operands (or on
4312 // a pointer operand and a null pointer constant) to bring
4313 // them to their composite pointer type. [...]
4314 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004315 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004316 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004317 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004318 if (T.isNull()) {
4319 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4320 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4321 return QualType();
4322 }
4323
4324 ImpCastExprToType(lex, T);
4325 ImpCastExprToType(rex, T);
4326 return ResultTy;
4327 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004328 // C99 6.5.9p2 and C99 6.5.8p2
4329 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4330 RCanPointeeTy.getUnqualifiedType())) {
4331 // Valid unless a relational comparison of function pointers
4332 if (isRelational && LCanPointeeTy->isFunctionType()) {
4333 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4334 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4335 }
4336 } else if (!isRelational &&
4337 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4338 // Valid unless comparison between non-null pointer and function pointer
4339 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4340 && !LHSIsNull && !RHSIsNull) {
4341 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4342 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4343 }
4344 } else {
4345 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004346 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004347 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004348 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004349 if (LCanPointeeTy != RCanPointeeTy)
4350 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004351 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004352 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004353
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004354 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004355 // Comparison of pointers with null pointer constants and equality
4356 // comparisons of member pointers to null pointer constants.
4357 if (RHSIsNull &&
4358 (lType->isPointerType() ||
4359 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004360 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004361 return ResultTy;
4362 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004363 if (LHSIsNull &&
4364 (rType->isPointerType() ||
4365 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004366 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004367 return ResultTy;
4368 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004369
4370 // Comparison of member pointers.
4371 if (!isRelational &&
4372 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4373 // C++ [expr.eq]p2:
4374 // In addition, pointers to members can be compared, or a pointer to
4375 // member and a null pointer constant. Pointer to member conversions
4376 // (4.11) and qualification conversions (4.4) are performed to bring
4377 // them to a common type. If one operand is a null pointer constant,
4378 // the common type is the type of the other operand. Otherwise, the
4379 // common type is a pointer to member type similar (4.4) to the type
4380 // of one of the operands, with a cv-qualification signature (4.4)
4381 // that is the union of the cv-qualification signatures of the operand
4382 // types.
4383 QualType T = FindCompositePointerType(lex, rex);
4384 if (T.isNull()) {
4385 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4386 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4387 return QualType();
4388 }
4389
4390 ImpCastExprToType(lex, T);
4391 ImpCastExprToType(rex, T);
4392 return ResultTy;
4393 }
4394
4395 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004396 if (lType->isNullPtrType() && rType->isNullPtrType())
4397 return ResultTy;
4398 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004399
Steve Naroff3454b6c2008-09-04 15:10:53 +00004400 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004401 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004402 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4403 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004404
Steve Naroff3454b6c2008-09-04 15:10:53 +00004405 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004406 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004407 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004408 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004409 }
4410 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004411 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004412 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004413 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004414 if (!isRelational
4415 && ((lType->isBlockPointerType() && rType->isPointerType())
4416 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004417 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004418 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004419 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004420 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004421 ->getPointeeType()->isVoidType())))
4422 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4423 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004424 }
4425 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004426 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004427 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004428
Steve Naroff329ec222009-07-10 23:34:53 +00004429 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004430 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004431 const PointerType *LPT = lType->getAs<PointerType>();
4432 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004433 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004434 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004435 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004436 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004437
Steve Naroff030fcda2008-11-17 19:49:16 +00004438 if (!LPtrToVoid && !RPtrToVoid &&
4439 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004440 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004441 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004442 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004443 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004444 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004445 }
Steve Naroff329ec222009-07-10 23:34:53 +00004446 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004447 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004448 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4449 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004450 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004451 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004452 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004453 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004454 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004455 unsigned DiagID = 0;
4456 if (RHSIsNull) {
4457 if (isRelational)
4458 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4459 } else if (isRelational)
4460 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4461 else
4462 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4463
4464 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004465 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004466 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004467 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004468 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004469 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004470 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004471 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004472 unsigned DiagID = 0;
4473 if (LHSIsNull) {
4474 if (isRelational)
4475 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4476 } else if (isRelational)
4477 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4478 else
4479 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004480
Chris Lattner124569f2009-08-23 00:03:44 +00004481 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004482 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004483 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004484 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004485 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004486 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004487 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004488 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004489 if (!isRelational && RHSIsNull
4490 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004491 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004492 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004493 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004494 if (!isRelational && LHSIsNull
4495 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004496 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004497 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004498 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004499 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004500}
4501
Nate Begemanc5f0f652008-07-14 18:02:46 +00004502/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004503/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004504/// like a scalar comparison, a vector comparison produces a vector of integer
4505/// types.
4506QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004507 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004508 bool isRelational) {
4509 // Check to make sure we're operating on vectors of the same type and width,
4510 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004511 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004512 if (vType.isNull())
4513 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004514
Nate Begemanc5f0f652008-07-14 18:02:46 +00004515 QualType lType = lex->getType();
4516 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004517
Nate Begemanc5f0f652008-07-14 18:02:46 +00004518 // For non-floating point types, check for self-comparisons of the form
4519 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4520 // often indicate logic errors in the program.
4521 if (!lType->isFloatingType()) {
4522 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4523 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4524 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004525 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004526 }
Mike Stump9afab102009-02-19 03:04:26 +00004527
Nate Begemanc5f0f652008-07-14 18:02:46 +00004528 // Check for comparisons of floating point operands using != and ==.
4529 if (!isRelational && lType->isFloatingType()) {
4530 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004531 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004532 }
Mike Stump9afab102009-02-19 03:04:26 +00004533
Nate Begemanc5f0f652008-07-14 18:02:46 +00004534 // Return the type for the comparison, which is the same as vector type for
4535 // integer vectors, or an integer type of identical size and number of
4536 // elements for floating point vectors.
4537 if (lType->isIntegerType())
4538 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004539
Nate Begemanc5f0f652008-07-14 18:02:46 +00004540 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004541 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004542 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004543 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004544 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004545 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4546
Mike Stump9afab102009-02-19 03:04:26 +00004547 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004548 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004549 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4550}
4551
Chris Lattner4b009652007-07-25 00:24:17 +00004552inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004553 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004554{
4555 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004556 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004557
Steve Naroff8f708362007-08-24 19:07:16 +00004558 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004559
Chris Lattner4b009652007-07-25 00:24:17 +00004560 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004561 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004562 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004563}
4564
4565inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004566 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004567{
4568 UsualUnaryConversions(lex);
4569 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004570
Eli Friedmanbea3f842008-05-13 20:16:47 +00004571 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004572 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004573 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004574}
4575
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004576/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4577/// is a read-only property; return true if so. A readonly property expression
4578/// depends on various declarations and thus must be treated specially.
4579///
Mike Stump9afab102009-02-19 03:04:26 +00004580static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004581{
4582 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4583 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4584 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4585 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004586 if (const ObjCObjectPointerType *OPT =
4587 BaseType->getAsObjCInterfacePointerType())
4588 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4589 if (S.isPropertyReadonly(PDecl, IFace))
4590 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004591 }
4592 }
4593 return false;
4594}
4595
Chris Lattner4c2642c2008-11-18 01:22:49 +00004596/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4597/// emit an error and return true. If so, return false.
4598static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004599 SourceLocation OrigLoc = Loc;
4600 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4601 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004602 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4603 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004604 if (IsLV == Expr::MLV_Valid)
4605 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004606
Chris Lattner4c2642c2008-11-18 01:22:49 +00004607 unsigned Diag = 0;
4608 bool NeedType = false;
4609 switch (IsLV) { // C99 6.5.16p2
4610 default: assert(0 && "Unknown result from isModifiableLvalue!");
4611 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004612 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004613 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4614 NeedType = true;
4615 break;
Mike Stump9afab102009-02-19 03:04:26 +00004616 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004617 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4618 NeedType = true;
4619 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004620 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004621 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4622 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004623 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004624 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4625 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004626 case Expr::MLV_IncompleteType:
4627 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004628 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004629 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4630 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004631 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004632 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4633 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004634 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004635 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4636 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004637 case Expr::MLV_ReadonlyProperty:
4638 Diag = diag::error_readonly_property_assignment;
4639 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004640 case Expr::MLV_NoSetterProperty:
4641 Diag = diag::error_nosetter_property_assignment;
4642 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004643 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004644
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004645 SourceRange Assign;
4646 if (Loc != OrigLoc)
4647 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004648 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004649 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004650 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004651 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004652 return true;
4653}
4654
4655
4656
4657// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004658QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4659 SourceLocation Loc,
4660 QualType CompoundType) {
4661 // Verify that LHS is a modifiable lvalue, and emit error if not.
4662 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004663 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004664
4665 QualType LHSType = LHS->getType();
4666 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004667
Chris Lattner005ed752008-01-04 18:04:52 +00004668 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004669 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004670 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004671 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004672 // Special case of NSObject attributes on c-style pointer types.
4673 if (ConvTy == IncompatiblePointer &&
4674 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004675 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004676 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004677 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004678 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004679
Chris Lattner34c85082008-08-21 18:04:13 +00004680 // If the RHS is a unary plus or minus, check to see if they = and + are
4681 // right next to each other. If so, the user may have typo'd "x =+ 4"
4682 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004683 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004684 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4685 RHSCheck = ICE->getSubExpr();
4686 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4687 if ((UO->getOpcode() == UnaryOperator::Plus ||
4688 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004689 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004690 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004691 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4692 // And there is a space or other character before the subexpr of the
4693 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004694 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4695 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004696 Diag(Loc, diag::warn_not_compound_assign)
4697 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4698 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004699 }
Chris Lattner34c85082008-08-21 18:04:13 +00004700 }
4701 } else {
4702 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004703 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004704 }
Chris Lattner005ed752008-01-04 18:04:52 +00004705
Chris Lattner1eafdea2008-11-18 01:30:42 +00004706 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4707 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004708 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004709
Chris Lattner4b009652007-07-25 00:24:17 +00004710 // C99 6.5.16p3: The type of an assignment expression is the type of the
4711 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004712 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004713 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4714 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004715 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004716 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004717 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004718}
4719
Chris Lattner1eafdea2008-11-18 01:30:42 +00004720// C99 6.5.17
4721QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004722 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004723 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004724
4725 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4726 // incomplete in C++).
4727
Chris Lattner1eafdea2008-11-18 01:30:42 +00004728 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004729}
4730
4731/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4732/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004733QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4734 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004735 if (Op->isTypeDependent())
4736 return Context.DependentTy;
4737
Chris Lattnere65182c2008-11-21 07:05:48 +00004738 QualType ResType = Op->getType();
4739 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004740
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004741 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4742 // Decrement of bool is not allowed.
4743 if (!isInc) {
4744 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4745 return QualType();
4746 }
4747 // Increment of bool sets it to true, but is deprecated.
4748 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4749 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004750 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004751 } else if (ResType->isAnyPointerType()) {
4752 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004753
Chris Lattnere65182c2008-11-21 07:05:48 +00004754 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004755 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004756 if (getLangOptions().CPlusPlus) {
4757 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4758 << Op->getSourceRange();
4759 return QualType();
4760 }
4761
4762 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004763 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004764 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004765 if (getLangOptions().CPlusPlus) {
4766 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4767 << Op->getType() << Op->getSourceRange();
4768 return QualType();
4769 }
4770
4771 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004772 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004773 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004774 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4775 << Op->getSourceRange()
4776 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004777 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004778 // Diagnose bad cases where we step over interface counts.
4779 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4780 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4781 << PointeeTy << Op->getSourceRange();
4782 return QualType();
4783 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004784 } else if (ResType->isComplexType()) {
4785 // C99 does not support ++/-- on complex types, we allow as an extension.
4786 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004787 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004788 } else {
4789 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004790 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004791 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004792 }
Mike Stump9afab102009-02-19 03:04:26 +00004793 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004794 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004795 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004796 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004797 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004798}
4799
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004800/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004801/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004802/// where the declaration is needed for type checking. We only need to
4803/// handle cases when the expression references a function designator
4804/// or is an lvalue. Here are some examples:
4805/// - &(x) => x
4806/// - &*****f => f for f a function designator.
4807/// - &s.xx => s
4808/// - &s.zz[1].yy -> s, if zz is an array
4809/// - *(x + 1) -> x, if x is an array
4810/// - &"123"[2] -> 0
4811/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004812static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004813 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004814 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004815 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004816 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004817 case Stmt::MemberExprClass:
Douglas Gregore399ad42009-08-26 22:36:53 +00004818 case Stmt::CXXQualifiedMemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004819 // If this is an arrow operator, the address is an offset from
4820 // the base's value, so the object the base refers to is
4821 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004822 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004823 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004824 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004825 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004826 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004827 // FIXME: This code shouldn't be necessary! We should catch the implicit
4828 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004829 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4830 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4831 if (ICE->getSubExpr()->getType()->isArrayType())
4832 return getPrimaryDecl(ICE->getSubExpr());
4833 }
4834 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004835 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004836 case Stmt::UnaryOperatorClass: {
4837 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004838
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004839 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004840 case UnaryOperator::Real:
4841 case UnaryOperator::Imag:
4842 case UnaryOperator::Extension:
4843 return getPrimaryDecl(UO->getSubExpr());
4844 default:
4845 return 0;
4846 }
4847 }
Chris Lattner4b009652007-07-25 00:24:17 +00004848 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004849 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004850 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004851 // If the result of an implicit cast is an l-value, we care about
4852 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004853 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004854 default:
4855 return 0;
4856 }
4857}
4858
4859/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004860/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004861/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004862/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004863/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004864/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004865/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004866QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004867 // Make sure to ignore parentheses in subsequent checks
4868 op = op->IgnoreParens();
4869
Douglas Gregore6be68a2008-12-17 22:52:20 +00004870 if (op->isTypeDependent())
4871 return Context.DependentTy;
4872
Steve Naroff9c6c3592008-01-13 17:10:08 +00004873 if (getLangOptions().C99) {
4874 // Implement C99-only parts of addressof rules.
4875 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4876 if (uOp->getOpcode() == UnaryOperator::Deref)
4877 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4878 // (assuming the deref expression is valid).
4879 return uOp->getSubExpr()->getType();
4880 }
4881 // Technically, there should be a check for array subscript
4882 // expressions here, but the result of one is always an lvalue anyway.
4883 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004884 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004885 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004886
Eli Friedman14ab4c42009-05-16 23:27:50 +00004887 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4888 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004889 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004890 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004891 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004892 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4893 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004894 return QualType();
4895 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004896 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004897 // The operand cannot be a bit-field
4898 Diag(OpLoc, diag::err_typecheck_address_of)
4899 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004900 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004901 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4902 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004903 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004904 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004905 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004906 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004907 } else if (isa<ObjCPropertyRefExpr>(op)) {
4908 // cannot take address of a property expression.
4909 Diag(OpLoc, diag::err_typecheck_address_of)
4910 << "property expression" << op->getSourceRange();
4911 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004912 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004913 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004914 // with the register storage-class specifier.
4915 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4916 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004917 Diag(OpLoc, diag::err_typecheck_address_of)
4918 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004919 return QualType();
4920 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004921 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4922 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004923 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004924 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004925 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004926 // Could be a pointer to member, though, if there is an explicit
4927 // scope qualifier for the class.
4928 if (isa<QualifiedDeclRefExpr>(op)) {
4929 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004930 if (Ctx && Ctx->isRecord()) {
4931 if (FD->getType()->isReferenceType()) {
4932 Diag(OpLoc,
4933 diag::err_cannot_form_pointer_to_member_of_reference_type)
4934 << FD->getDeclName() << FD->getType();
4935 return QualType();
4936 }
4937
Sebastian Redl0c9da212009-02-03 20:19:35 +00004938 return Context.getMemberPointerType(op->getType(),
4939 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004940 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004941 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004942 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004943 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004944 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004945 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4946 return Context.getMemberPointerType(op->getType(),
4947 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4948 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004949 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004950 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004951
Eli Friedman14ab4c42009-05-16 23:27:50 +00004952 if (lval == Expr::LV_IncompleteVoidType) {
4953 // Taking the address of a void variable is technically illegal, but we
4954 // allow it in cases which are otherwise valid.
4955 // Example: "extern void x; void* y = &x;".
4956 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4957 }
4958
Chris Lattner4b009652007-07-25 00:24:17 +00004959 // If the operand has type "type", the result has type "pointer to type".
4960 return Context.getPointerType(op->getType());
4961}
4962
Chris Lattnerda5c0872008-11-23 09:13:29 +00004963QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004964 if (Op->isTypeDependent())
4965 return Context.DependentTy;
4966
Chris Lattnerda5c0872008-11-23 09:13:29 +00004967 UsualUnaryConversions(Op);
4968 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004969
Chris Lattnerda5c0872008-11-23 09:13:29 +00004970 // Note that per both C89 and C99, this is always legal, even if ptype is an
4971 // incomplete type or void. It would be possible to warn about dereferencing
4972 // a void pointer, but it's completely well-defined, and such a warning is
4973 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004974 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004975 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004976
Steve Naroff329ec222009-07-10 23:34:53 +00004977 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4978 return OPT->getPointeeType();
4979
Chris Lattner77d52da2008-11-20 06:06:08 +00004980 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004981 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004982 return QualType();
4983}
4984
4985static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4986 tok::TokenKind Kind) {
4987 BinaryOperator::Opcode Opc;
4988 switch (Kind) {
4989 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004990 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4991 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004992 case tok::star: Opc = BinaryOperator::Mul; break;
4993 case tok::slash: Opc = BinaryOperator::Div; break;
4994 case tok::percent: Opc = BinaryOperator::Rem; break;
4995 case tok::plus: Opc = BinaryOperator::Add; break;
4996 case tok::minus: Opc = BinaryOperator::Sub; break;
4997 case tok::lessless: Opc = BinaryOperator::Shl; break;
4998 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4999 case tok::lessequal: Opc = BinaryOperator::LE; break;
5000 case tok::less: Opc = BinaryOperator::LT; break;
5001 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5002 case tok::greater: Opc = BinaryOperator::GT; break;
5003 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5004 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5005 case tok::amp: Opc = BinaryOperator::And; break;
5006 case tok::caret: Opc = BinaryOperator::Xor; break;
5007 case tok::pipe: Opc = BinaryOperator::Or; break;
5008 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5009 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5010 case tok::equal: Opc = BinaryOperator::Assign; break;
5011 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5012 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5013 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5014 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5015 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5016 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5017 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5018 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5019 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5020 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5021 case tok::comma: Opc = BinaryOperator::Comma; break;
5022 }
5023 return Opc;
5024}
5025
5026static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5027 tok::TokenKind Kind) {
5028 UnaryOperator::Opcode Opc;
5029 switch (Kind) {
5030 default: assert(0 && "Unknown unary op!");
5031 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5032 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5033 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5034 case tok::star: Opc = UnaryOperator::Deref; break;
5035 case tok::plus: Opc = UnaryOperator::Plus; break;
5036 case tok::minus: Opc = UnaryOperator::Minus; break;
5037 case tok::tilde: Opc = UnaryOperator::Not; break;
5038 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005039 case tok::kw___real: Opc = UnaryOperator::Real; break;
5040 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5041 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5042 }
5043 return Opc;
5044}
5045
Douglas Gregord7f915e2008-11-06 23:29:22 +00005046/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5047/// operator @p Opc at location @c TokLoc. This routine only supports
5048/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005049Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5050 unsigned Op,
5051 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005052 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005053 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005054 // The following two variables are used for compound assignment operators
5055 QualType CompLHSTy; // Type of LHS after promotions for computation
5056 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005057
5058 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005059 case BinaryOperator::Assign:
5060 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5061 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005062 case BinaryOperator::PtrMemD:
5063 case BinaryOperator::PtrMemI:
5064 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5065 Opc == BinaryOperator::PtrMemI);
5066 break;
5067 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005068 case BinaryOperator::Div:
5069 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5070 break;
5071 case BinaryOperator::Rem:
5072 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5073 break;
5074 case BinaryOperator::Add:
5075 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5076 break;
5077 case BinaryOperator::Sub:
5078 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5079 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005080 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005081 case BinaryOperator::Shr:
5082 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5083 break;
5084 case BinaryOperator::LE:
5085 case BinaryOperator::LT:
5086 case BinaryOperator::GE:
5087 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005088 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005089 break;
5090 case BinaryOperator::EQ:
5091 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005092 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005093 break;
5094 case BinaryOperator::And:
5095 case BinaryOperator::Xor:
5096 case BinaryOperator::Or:
5097 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5098 break;
5099 case BinaryOperator::LAnd:
5100 case BinaryOperator::LOr:
5101 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5102 break;
5103 case BinaryOperator::MulAssign:
5104 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005105 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5106 CompLHSTy = CompResultTy;
5107 if (!CompResultTy.isNull())
5108 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005109 break;
5110 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005111 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5112 CompLHSTy = CompResultTy;
5113 if (!CompResultTy.isNull())
5114 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005115 break;
5116 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005117 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5118 if (!CompResultTy.isNull())
5119 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005120 break;
5121 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005122 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5123 if (!CompResultTy.isNull())
5124 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005125 break;
5126 case BinaryOperator::ShlAssign:
5127 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005128 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5129 CompLHSTy = CompResultTy;
5130 if (!CompResultTy.isNull())
5131 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005132 break;
5133 case BinaryOperator::AndAssign:
5134 case BinaryOperator::XorAssign:
5135 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005136 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5137 CompLHSTy = CompResultTy;
5138 if (!CompResultTy.isNull())
5139 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005140 break;
5141 case BinaryOperator::Comma:
5142 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5143 break;
5144 }
5145 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005146 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005147 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005148 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5149 else
5150 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005151 CompLHSTy, CompResultTy,
5152 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005153}
5154
Chris Lattner4b009652007-07-25 00:24:17 +00005155// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005156Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5157 tok::TokenKind Kind,
5158 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005159 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005160 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005161
Steve Naroff87d58b42007-09-16 03:34:24 +00005162 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5163 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005164
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005165 if (getLangOptions().CPlusPlus &&
5166 (lhs->getType()->isOverloadableType() ||
5167 rhs->getType()->isOverloadableType())) {
5168 // Find all of the overloaded operators visible from this
5169 // point. We perform both an operator-name lookup from the local
5170 // scope and an argument-dependent lookup based on the types of
5171 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005172 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005173 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5174 if (OverOp != OO_None) {
5175 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5176 Functions);
5177 Expr *Args[2] = { lhs, rhs };
5178 DeclarationName OpName
5179 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5180 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005181 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005182
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005183 // Build the (potentially-overloaded, potentially-dependent)
5184 // binary operation.
5185 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005186 }
5187
Douglas Gregord7f915e2008-11-06 23:29:22 +00005188 // Build a built-in binary operation.
5189 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005190}
5191
Douglas Gregorc78182d2009-03-13 23:49:33 +00005192Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5193 unsigned OpcIn,
5194 ExprArg InputArg) {
5195 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005196
Mike Stumpe127ae32009-05-16 07:39:55 +00005197 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005198 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005199 QualType resultType;
5200 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005201 case UnaryOperator::OffsetOf:
5202 assert(false && "Invalid unary operator");
5203 break;
5204
Chris Lattner4b009652007-07-25 00:24:17 +00005205 case UnaryOperator::PreInc:
5206 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005207 case UnaryOperator::PostInc:
5208 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005209 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005210 Opc == UnaryOperator::PreInc ||
5211 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005212 break;
Mike Stump9afab102009-02-19 03:04:26 +00005213 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005214 resultType = CheckAddressOfOperand(Input, OpLoc);
5215 break;
Mike Stump9afab102009-02-19 03:04:26 +00005216 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005217 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005218 resultType = CheckIndirectionOperand(Input, OpLoc);
5219 break;
5220 case UnaryOperator::Plus:
5221 case UnaryOperator::Minus:
5222 UsualUnaryConversions(Input);
5223 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005224 if (resultType->isDependentType())
5225 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005226 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5227 break;
5228 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5229 resultType->isEnumeralType())
5230 break;
5231 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5232 Opc == UnaryOperator::Plus &&
5233 resultType->isPointerType())
5234 break;
5235
Sebastian Redl8b769972009-01-19 00:08:26 +00005236 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5237 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005238 case UnaryOperator::Not: // bitwise complement
5239 UsualUnaryConversions(Input);
5240 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005241 if (resultType->isDependentType())
5242 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005243 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5244 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5245 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005246 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005247 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005248 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005249 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5250 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005251 break;
5252 case UnaryOperator::LNot: // logical negation
5253 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5254 DefaultFunctionArrayConversion(Input);
5255 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005256 if (resultType->isDependentType())
5257 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005258 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005259 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5260 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005261 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005262 // In C++, it's bool. C++ 5.3.1p8
5263 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005264 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005265 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005266 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005267 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005268 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005269 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005270 resultType = Input->getType();
5271 break;
5272 }
5273 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005274 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005275
5276 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005277 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005278}
5279
Douglas Gregorc78182d2009-03-13 23:49:33 +00005280// Unary Operators. 'Tok' is the token for the operator.
5281Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5282 tok::TokenKind Op, ExprArg input) {
5283 Expr *Input = (Expr*)input.get();
5284 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5285
5286 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5287 // Find all of the overloaded operators visible from this
5288 // point. We perform both an operator-name lookup from the local
5289 // scope and an argument-dependent lookup based on the types of
5290 // the arguments.
5291 FunctionSet Functions;
5292 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5293 if (OverOp != OO_None) {
5294 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5295 Functions);
5296 DeclarationName OpName
5297 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5298 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5299 }
5300
5301 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5302 }
5303
5304 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5305}
5306
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005307/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005308Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5309 SourceLocation LabLoc,
5310 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005311 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005312 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005313
Daniel Dunbar879788d2008-08-04 16:51:22 +00005314 // If we haven't seen this label yet, create a forward reference. It
5315 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005316 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005317 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005318
Chris Lattner4b009652007-07-25 00:24:17 +00005319 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005320 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5321 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005322}
5323
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005324Sema::OwningExprResult
5325Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5326 SourceLocation RPLoc) { // "({..})"
5327 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005328 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5329 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5330
Eli Friedmanbc941e12009-01-24 23:09:00 +00005331 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005332 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005333 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005334
Chris Lattner4b009652007-07-25 00:24:17 +00005335 // FIXME: there are a variety of strange constraints to enforce here, for
5336 // example, it is not possible to goto into a stmt expression apparently.
5337 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005338
Chris Lattner4b009652007-07-25 00:24:17 +00005339 // If there are sub stmts in the compound stmt, take the type of the last one
5340 // as the type of the stmtexpr.
5341 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005342
Chris Lattner200964f2008-07-26 19:51:01 +00005343 if (!Compound->body_empty()) {
5344 Stmt *LastStmt = Compound->body_back();
5345 // If LastStmt is a label, skip down through into the body.
5346 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5347 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005348
Chris Lattner200964f2008-07-26 19:51:01 +00005349 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005350 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005351 }
Mike Stump9afab102009-02-19 03:04:26 +00005352
Eli Friedman2b128322009-03-23 00:24:07 +00005353 // FIXME: Check that expression type is complete/non-abstract; statement
5354 // expressions are not lvalues.
5355
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005356 substmt.release();
5357 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005358}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005359
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005360Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5361 SourceLocation BuiltinLoc,
5362 SourceLocation TypeLoc,
5363 TypeTy *argty,
5364 OffsetOfComponent *CompPtr,
5365 unsigned NumComponents,
5366 SourceLocation RPLoc) {
5367 // FIXME: This function leaks all expressions in the offset components on
5368 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005369 // FIXME: Preserve type source info.
5370 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005371 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005372
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005373 bool Dependent = ArgTy->isDependentType();
5374
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005375 // We must have at least one component that refers to the type, and the first
5376 // one is known to be a field designator. Verify that the ArgTy represents
5377 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005378 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005379 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005380
Eli Friedman2b128322009-03-23 00:24:07 +00005381 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5382 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005383
Eli Friedman342d9432009-02-27 06:44:11 +00005384 // Otherwise, create a null pointer as the base, and iteratively process
5385 // the offsetof designators.
5386 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5387 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005388 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005389 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005390
Chris Lattnerb37522e2007-08-31 21:49:13 +00005391 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5392 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005393 // FIXME: This diagnostic isn't actually visible because the location is in
5394 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005395 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005396 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5397 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005398
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005399 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005400 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005401
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005402 // FIXME: Dependent case loses a lot of information here. And probably
5403 // leaks like a sieve.
5404 for (unsigned i = 0; i != NumComponents; ++i) {
5405 const OffsetOfComponent &OC = CompPtr[i];
5406 if (OC.isBrackets) {
5407 // Offset of an array sub-field. TODO: Should we allow vector elements?
5408 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5409 if (!AT) {
5410 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005411 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5412 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005413 }
5414
5415 // FIXME: C++: Verify that operator[] isn't overloaded.
5416
Eli Friedman342d9432009-02-27 06:44:11 +00005417 // Promote the array so it looks more like a normal array subscript
5418 // expression.
5419 DefaultFunctionArrayConversion(Res);
5420
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005421 // C99 6.5.2.1p1
5422 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005423 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005424 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005425 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005426 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005427 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005428
5429 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5430 OC.LocEnd);
5431 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005432 }
Mike Stump9afab102009-02-19 03:04:26 +00005433
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005434 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005435 if (!RC) {
5436 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005437 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5438 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005439 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005440
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005441 // Get the decl corresponding to this.
5442 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005443 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005444 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005445 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5446 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5447 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005448 DidWarnAboutNonPOD = true;
5449 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005450 }
5451
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005452 FieldDecl *MemberDecl
5453 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5454 LookupMemberName)
5455 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005456 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005457 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005458 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5459 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005460
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005461 // FIXME: C++: Verify that MemberDecl isn't a static field.
5462 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005463 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005464 Res = BuildAnonymousStructUnionMemberReference(
5465 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005466 } else {
5467 // MemberDecl->getType() doesn't get the right qualifiers, but it
5468 // doesn't matter here.
5469 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5470 MemberDecl->getType().getNonReferenceType());
5471 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005472 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005473 }
Mike Stump9afab102009-02-19 03:04:26 +00005474
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005475 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5476 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005477}
5478
5479
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005480Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5481 TypeTy *arg1,TypeTy *arg2,
5482 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005483 // FIXME: Preserve type source info.
5484 QualType argT1 = GetTypeFromParser(arg1);
5485 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005486
Steve Naroff63bad2d2007-08-01 22:05:33 +00005487 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005488
Douglas Gregore6211502009-05-19 22:28:02 +00005489 if (getLangOptions().CPlusPlus) {
5490 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5491 << SourceRange(BuiltinLoc, RPLoc);
5492 return ExprError();
5493 }
5494
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005495 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5496 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005497}
5498
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005499Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5500 ExprArg cond,
5501 ExprArg expr1, ExprArg expr2,
5502 SourceLocation RPLoc) {
5503 Expr *CondExpr = static_cast<Expr*>(cond.get());
5504 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5505 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005506
Steve Naroff93c53012007-08-03 21:21:27 +00005507 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5508
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005509 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005510 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005511 resType = Context.DependentTy;
5512 } else {
5513 // The conditional expression is required to be a constant expression.
5514 llvm::APSInt condEval(32);
5515 SourceLocation ExpLoc;
5516 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005517 return ExprError(Diag(ExpLoc,
5518 diag::err_typecheck_choose_expr_requires_constant)
5519 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005520
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005521 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5522 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5523 }
5524
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005525 cond.release(); expr1.release(); expr2.release();
5526 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5527 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005528}
5529
Steve Naroff52a81c02008-09-03 18:15:37 +00005530//===----------------------------------------------------------------------===//
5531// Clang Extensions.
5532//===----------------------------------------------------------------------===//
5533
5534/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005535void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005536 // Analyze block parameters.
5537 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005538
Steve Naroff52a81c02008-09-03 18:15:37 +00005539 // Add BSI to CurBlock.
5540 BSI->PrevBlockInfo = CurBlock;
5541 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005542
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005543 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005544 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005545 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005546 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005547 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5548 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005549
Steve Naroff52059382008-10-10 01:28:17 +00005550 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005551 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005552}
5553
Mike Stumpc1fddff2009-02-04 22:31:32 +00005554void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005555 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005556
5557 if (ParamInfo.getNumTypeObjects() == 0
5558 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005559 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005560 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5561
Mike Stump458287d2009-04-28 01:10:27 +00005562 if (T->isArrayType()) {
5563 Diag(ParamInfo.getSourceRange().getBegin(),
5564 diag::err_block_returns_array);
5565 return;
5566 }
5567
Mike Stumpc1fddff2009-02-04 22:31:32 +00005568 // The parameter list is optional, if there was none, assume ().
5569 if (!T->isFunctionType())
5570 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5571
5572 CurBlock->hasPrototype = true;
5573 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005574 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005575 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005576 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005577 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005578 // FIXME: remove the attribute.
5579 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005580 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5581
5582 // Do not allow returning a objc interface by-value.
5583 if (RetTy->isObjCInterfaceType()) {
5584 Diag(ParamInfo.getSourceRange().getBegin(),
5585 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5586 return;
5587 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005588 return;
5589 }
5590
Steve Naroff52a81c02008-09-03 18:15:37 +00005591 // Analyze arguments to block.
5592 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5593 "Not a function declarator!");
5594 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005595
Steve Naroff52059382008-10-10 01:28:17 +00005596 CurBlock->hasPrototype = FTI.hasPrototype;
5597 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005598
Steve Naroff52a81c02008-09-03 18:15:37 +00005599 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5600 // no arguments, not a function that takes a single void argument.
5601 if (FTI.hasPrototype &&
5602 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005603 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5604 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005605 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005606 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005607 } else if (FTI.hasPrototype) {
5608 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005609 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005610 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005611 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005612 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005613 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005614 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005615 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005616 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5617 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5618 // If this has an identifier, add it to the scope stack.
5619 if ((*AI)->getIdentifier())
5620 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005621
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005622 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005623 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005624 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005625 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005626 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005627 // FIXME: remove the attribute.
5628 }
5629
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005630 // Analyze the return type.
5631 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5632 QualType RetTy = T->getAsFunctionType()->getResultType();
5633
5634 // Do not allow returning a objc interface by-value.
5635 if (RetTy->isObjCInterfaceType()) {
5636 Diag(ParamInfo.getSourceRange().getBegin(),
5637 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5638 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005639 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005640}
5641
5642/// ActOnBlockError - If there is an error parsing a block, this callback
5643/// is invoked to pop the information about the block from the action impl.
5644void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5645 // Ensure that CurBlock is deleted.
5646 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005647
Chris Lattnere7765e12009-04-19 05:28:12 +00005648 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5649
Steve Naroff52a81c02008-09-03 18:15:37 +00005650 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005651 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005652 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005653 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005654}
5655
5656/// ActOnBlockStmtExpr - This is called when the body of a block statement
5657/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005658Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5659 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005660 // If blocks are disabled, emit an error.
5661 if (!LangOpts.Blocks)
5662 Diag(CaretLoc, diag::err_blocks_disable);
5663
Steve Naroff52a81c02008-09-03 18:15:37 +00005664 // Ensure that CurBlock is deleted.
5665 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005666
Steve Naroff52059382008-10-10 01:28:17 +00005667 PopDeclContext();
5668
Steve Naroff52a81c02008-09-03 18:15:37 +00005669 // Pop off CurBlock, handle nested blocks.
5670 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005671
Steve Naroff52a81c02008-09-03 18:15:37 +00005672 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005673 if (!BSI->ReturnType.isNull())
5674 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005675
Steve Naroff52a81c02008-09-03 18:15:37 +00005676 llvm::SmallVector<QualType, 8> ArgTypes;
5677 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5678 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005679
Mike Stump8e288f42009-07-28 22:04:01 +00005680 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005681 QualType BlockTy;
5682 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005683 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5684 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005685 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005686 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005687 BSI->isVariadic, 0, false, false, 0, 0,
5688 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005689
Eli Friedman2b128322009-03-23 00:24:07 +00005690 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005691 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005692 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005693
Chris Lattnere7765e12009-04-19 05:28:12 +00005694 // If needed, diagnose invalid gotos and switches in the block.
5695 if (CurFunctionNeedsScopeChecking)
5696 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5697 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5698
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005699 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005700 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005701 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5702 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005703}
5704
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005705Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5706 ExprArg expr, TypeTy *type,
5707 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005708 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005709 Expr *E = static_cast<Expr*>(expr.get());
5710 Expr *OrigExpr = E;
5711
Anders Carlsson36760332007-10-15 20:28:48 +00005712 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005713
5714 // Get the va_list type
5715 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005716 if (VaListType->isArrayType()) {
5717 // Deal with implicit array decay; for example, on x86-64,
5718 // va_list is an array, but it's supposed to decay to
5719 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005720 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005721 // Make sure the input expression also decays appropriately.
5722 UsualUnaryConversions(E);
5723 } else {
5724 // Otherwise, the va_list argument must be an l-value because
5725 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005726 if (!E->isTypeDependent() &&
5727 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005728 return ExprError();
5729 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005730
Douglas Gregor25990972009-05-19 23:10:31 +00005731 if (!E->isTypeDependent() &&
5732 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005733 return ExprError(Diag(E->getLocStart(),
5734 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005735 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005736 }
Mike Stump9afab102009-02-19 03:04:26 +00005737
Eli Friedman2b128322009-03-23 00:24:07 +00005738 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005739 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005740
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005741 expr.release();
5742 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5743 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005744}
5745
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005746Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005747 // The type of __null will be int or long, depending on the size of
5748 // pointers on the target.
5749 QualType Ty;
5750 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5751 Ty = Context.IntTy;
5752 else
5753 Ty = Context.LongTy;
5754
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005755 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005756}
5757
Chris Lattner005ed752008-01-04 18:04:52 +00005758bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5759 SourceLocation Loc,
5760 QualType DstType, QualType SrcType,
5761 Expr *SrcExpr, const char *Flavor) {
5762 // Decode the result (notice that AST's are still created for extensions).
5763 bool isInvalid = false;
5764 unsigned DiagKind;
5765 switch (ConvTy) {
5766 default: assert(0 && "Unknown conversion type");
5767 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005768 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005769 DiagKind = diag::ext_typecheck_convert_pointer_int;
5770 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005771 case IntToPointer:
5772 DiagKind = diag::ext_typecheck_convert_int_pointer;
5773 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005774 case IncompatiblePointer:
5775 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5776 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005777 case IncompatiblePointerSign:
5778 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5779 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005780 case FunctionVoidPointer:
5781 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5782 break;
5783 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005784 // If the qualifiers lost were because we were applying the
5785 // (deprecated) C++ conversion from a string literal to a char*
5786 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5787 // Ideally, this check would be performed in
5788 // CheckPointerTypesForAssignment. However, that would require a
5789 // bit of refactoring (so that the second argument is an
5790 // expression, rather than a type), which should be done as part
5791 // of a larger effort to fix CheckPointerTypesForAssignment for
5792 // C++ semantics.
5793 if (getLangOptions().CPlusPlus &&
5794 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5795 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005796 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5797 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005798 case IntToBlockPointer:
5799 DiagKind = diag::err_int_to_block_pointer;
5800 break;
5801 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005802 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005803 break;
Steve Naroff19608432008-10-14 22:18:38 +00005804 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005805 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005806 // it can give a more specific diagnostic.
5807 DiagKind = diag::warn_incompatible_qualified_id;
5808 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005809 case IncompatibleVectors:
5810 DiagKind = diag::warn_incompatible_vectors;
5811 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005812 case Incompatible:
5813 DiagKind = diag::err_typecheck_convert_incompatible;
5814 isInvalid = true;
5815 break;
5816 }
Mike Stump9afab102009-02-19 03:04:26 +00005817
Chris Lattner271d4c22008-11-24 05:29:24 +00005818 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5819 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005820 return isInvalid;
5821}
Anders Carlssond5201b92008-11-30 19:50:32 +00005822
Chris Lattnereec8ae22009-04-25 21:59:05 +00005823bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005824 llvm::APSInt ICEResult;
5825 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5826 if (Result)
5827 *Result = ICEResult;
5828 return false;
5829 }
5830
Anders Carlssond5201b92008-11-30 19:50:32 +00005831 Expr::EvalResult EvalResult;
5832
Mike Stump9afab102009-02-19 03:04:26 +00005833 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005834 EvalResult.HasSideEffects) {
5835 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5836
5837 if (EvalResult.Diag) {
5838 // We only show the note if it's not the usual "invalid subexpression"
5839 // or if it's actually in a subexpression.
5840 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5841 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5842 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5843 }
Mike Stump9afab102009-02-19 03:04:26 +00005844
Anders Carlssond5201b92008-11-30 19:50:32 +00005845 return true;
5846 }
5847
Eli Friedmance329412009-04-25 22:26:58 +00005848 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5849 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005850
Eli Friedmance329412009-04-25 22:26:58 +00005851 if (EvalResult.Diag &&
5852 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5853 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005854
Anders Carlssond5201b92008-11-30 19:50:32 +00005855 if (Result)
5856 *Result = EvalResult.Val.getInt();
5857 return false;
5858}
Douglas Gregor98189262009-06-19 23:52:42 +00005859
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005860Sema::ExpressionEvaluationContext
5861Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5862 // Introduce a new set of potentially referenced declarations to the stack.
5863 if (NewContext == PotentiallyPotentiallyEvaluated)
5864 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5865
5866 std::swap(ExprEvalContext, NewContext);
5867 return NewContext;
5868}
5869
5870void
5871Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5872 ExpressionEvaluationContext NewContext) {
5873 ExprEvalContext = NewContext;
5874
5875 if (OldContext == PotentiallyPotentiallyEvaluated) {
5876 // Mark any remaining declarations in the current position of the stack
5877 // as "referenced". If they were not meant to be referenced, semantic
5878 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5879 PotentiallyReferencedDecls RemainingDecls;
5880 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5881 PotentiallyReferencedDeclStack.pop_back();
5882
5883 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5884 IEnd = RemainingDecls.end();
5885 I != IEnd; ++I)
5886 MarkDeclarationReferenced(I->first, I->second);
5887 }
5888}
Douglas Gregor98189262009-06-19 23:52:42 +00005889
5890/// \brief Note that the given declaration was referenced in the source code.
5891///
5892/// This routine should be invoke whenever a given declaration is referenced
5893/// in the source code, and where that reference occurred. If this declaration
5894/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5895/// C99 6.9p3), then the declaration will be marked as used.
5896///
5897/// \param Loc the location where the declaration was referenced.
5898///
5899/// \param D the declaration that has been referenced by the source code.
5900void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5901 assert(D && "No declaration?");
5902
Douglas Gregorcad27f62009-06-22 23:06:13 +00005903 if (D->isUsed())
5904 return;
5905
Douglas Gregor98189262009-06-19 23:52:42 +00005906 // Mark a parameter declaration "used", regardless of whether we're in a
5907 // template or not.
5908 if (isa<ParmVarDecl>(D))
5909 D->setUsed(true);
5910
5911 // Do not mark anything as "used" within a dependent context; wait for
5912 // an instantiation.
5913 if (CurContext->isDependentContext())
5914 return;
5915
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005916 switch (ExprEvalContext) {
5917 case Unevaluated:
5918 // We are in an expression that is not potentially evaluated; do nothing.
5919 return;
5920
5921 case PotentiallyEvaluated:
5922 // We are in a potentially-evaluated expression, so this declaration is
5923 // "used"; handle this below.
5924 break;
5925
5926 case PotentiallyPotentiallyEvaluated:
5927 // We are in an expression that may be potentially evaluated; queue this
5928 // declaration reference until we know whether the expression is
5929 // potentially evaluated.
5930 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5931 return;
5932 }
5933
Douglas Gregor98189262009-06-19 23:52:42 +00005934 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005935 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005936 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005937 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5938 if (!Constructor->isUsed())
5939 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005940 } else if (Constructor->isImplicit() &&
5941 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005942 if (!Constructor->isUsed())
5943 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5944 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005945 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5946 if (Destructor->isImplicit() && !Destructor->isUsed())
5947 DefineImplicitDestructor(Loc, Destructor);
5948
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005949 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5950 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5951 MethodDecl->getOverloadedOperator() == OO_Equal) {
5952 if (!MethodDecl->isUsed())
5953 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5954 }
5955 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00005956 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005957 // Implicit instantiation of function templates and member functions of
5958 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00005959 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00005960 // FIXME: distinguish between implicit instantiations of function
5961 // templates and explicit specializations (the latter don't get
5962 // instantiated, naturally).
5963 if (Function->getInstantiatedFromMemberFunction() ||
5964 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00005965 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00005966 }
5967
5968
Douglas Gregor98189262009-06-19 23:52:42 +00005969 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00005970 Function->setUsed(true);
5971 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00005972 }
Douglas Gregor98189262009-06-19 23:52:42 +00005973
5974 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00005975 // Implicit instantiation of static data members of class templates.
5976 // FIXME: distinguish between implicit instantiations (which we need to
5977 // actually instantiate) and explicit specializations.
5978 if (Var->isStaticDataMember() &&
5979 Var->getInstantiatedFromStaticDataMember())
5980 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5981
Douglas Gregor98189262009-06-19 23:52:42 +00005982 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00005983
Douglas Gregor98189262009-06-19 23:52:42 +00005984 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00005985 return;
5986}
Douglas Gregor98189262009-06-19 23:52:42 +00005987}
5988