blob: 80e07c5f0849a710b68a70f19c41e1974fccc6f2 [file] [log] [blame]
Sebastian Redl2111c852010-06-28 15:09:07 +00001//===--- ExprClassification.cpp - Expression AST Node Implementation ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Expr::classify.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth0010bca2010-06-29 00:23:11 +000014#include "llvm/Support/ErrorHandling.h"
Sebastian Redl2111c852010-06-28 15:09:07 +000015#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22using namespace clang;
23
24typedef Expr::Classification Cl;
25
26static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E);
27static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D);
28static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T);
29static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E);
30static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E);
31static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
32 const ConditionalOperator *E);
33static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
34 Cl::Kinds Kind, SourceLocation &Loc);
35
36Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
37 assert(!TR->isReferenceType() && "Expressions can't have reference type.");
38
39 Cl::Kinds kind = ClassifyInternal(Ctx, this);
40 // C99 6.3.2.1: An lvalue is an expression with an object type or an
41 // incomplete type other than void.
42 if (!Ctx.getLangOptions().CPlusPlus) {
43 // Thus, no functions.
44 if (TR->isFunctionType() || TR == Ctx.OverloadTy)
45 kind = Cl::CL_Function;
46 // No void either, but qualified void is OK because it is "other than void".
47 else if (TR->isVoidType() && !Ctx.getCanonicalType(TR).hasQualifiers())
48 kind = Cl::CL_Void;
49 }
50
51 Cl::ModifiableType modifiable = Cl::CM_Untested;
52 if (Loc)
53 modifiable = IsModifiable(Ctx, this, kind, *Loc);
54 return Classification(kind, modifiable);
55}
56
57static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
58 // This function takes the first stab at classifying expressions.
59 const LangOptions &Lang = Ctx.getLangOptions();
60
61 switch (E->getStmtClass()) {
62 // First come the expressions that are always lvalues, unconditionally.
63
64 case Expr::ObjCIsaExprClass:
65 // C++ [expr.prim.general]p1: A string literal is an lvalue.
66 case Expr::StringLiteralClass:
67 // @encode is equivalent to its string
68 case Expr::ObjCEncodeExprClass:
69 // __func__ and friends are too.
70 case Expr::PredefinedExprClass:
71 // Property references are lvalues
72 case Expr::ObjCPropertyRefExprClass:
73 case Expr::ObjCImplicitSetterGetterRefExprClass:
74 // C++ [expr.typeid]p1: The result of a typeid expression is an lvalue of...
75 case Expr::CXXTypeidExprClass:
76 // Unresolved lookups get classified as lvalues.
77 // FIXME: Is this wise? Should they get their own kind?
78 case Expr::UnresolvedLookupExprClass:
79 case Expr::UnresolvedMemberExprClass:
80 // ObjC instance variables are lvalues
81 // FIXME: ObjC++0x might have different rules
82 case Expr::ObjCIvarRefExprClass:
83 // C99 6.5.2.5p5 says that compound literals are lvalues.
84 // FIXME: C++ might have a different opinion.
85 case Expr::CompoundLiteralExprClass:
86 return Cl::CL_LValue;
87
88 // Next come the complicated cases.
89
90 // C++ [expr.sub]p1: The result is an lvalue of type "T".
91 // However, subscripting vector types is more like member access.
92 case Expr::ArraySubscriptExprClass:
93 if (cast<ArraySubscriptExpr>(E)->getBase()->getType()->isVectorType())
94 return ClassifyInternal(Ctx, cast<ArraySubscriptExpr>(E)->getBase());
95 return Cl::CL_LValue;
96
97 // C++ [expr.prim.general]p3: The result is an lvalue if the entity is a
98 // function or variable and a prvalue otherwise.
99 case Expr::DeclRefExprClass:
100 return ClassifyDecl(Ctx, cast<DeclRefExpr>(E)->getDecl());
101 // We deal with names referenced from blocks the same way.
102 case Expr::BlockDeclRefExprClass:
103 return ClassifyDecl(Ctx, cast<BlockDeclRefExpr>(E)->getDecl());
104
105 // Member access is complex.
106 case Expr::MemberExprClass:
107 return ClassifyMemberExpr(Ctx, cast<MemberExpr>(E));
108
109 case Expr::UnaryOperatorClass:
110 switch (cast<UnaryOperator>(E)->getOpcode()) {
111 // C++ [expr.unary.op]p1: The unary * operator performs indirection:
112 // [...] the result is an lvalue referring to the object or function
113 // to which the expression points.
114 case UnaryOperator::Deref:
115 return Cl::CL_LValue;
116
117 // GNU extensions, simply look through them.
118 case UnaryOperator::Real:
119 case UnaryOperator::Imag:
120 case UnaryOperator::Extension:
121 return ClassifyInternal(Ctx, cast<UnaryOperator>(E)->getSubExpr());
122
123 // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
124 // lvalue, [...]
125 // Not so in C.
126 case UnaryOperator::PreInc:
127 case UnaryOperator::PreDec:
128 return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
129
130 default:
131 return Cl::CL_PRValue;
132 }
133
134 // Implicit casts are lvalues if they're lvalue casts. Other than that, we
135 // only specifically record class temporaries.
136 case Expr::ImplicitCastExprClass:
John McCall5baba9d2010-08-25 10:28:54 +0000137 switch (cast<ImplicitCastExpr>(E)->getValueKind()) {
138 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +0000139 return Lang.CPlusPlus && E->getType()->isRecordType() ?
140 Cl::CL_ClassTemporary : Cl::CL_PRValue;
John McCall5baba9d2010-08-25 10:28:54 +0000141 case VK_LValue:
Sebastian Redl2111c852010-06-28 15:09:07 +0000142 return Cl::CL_LValue;
John McCall5baba9d2010-08-25 10:28:54 +0000143 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +0000144 return Cl::CL_XValue;
145 }
146 llvm_unreachable("Invalid value category of implicit cast.");
Sebastian Redl2111c852010-06-28 15:09:07 +0000147
148 // C++ [expr.prim.general]p4: The presence of parentheses does not affect
149 // whether the expression is an lvalue.
150 case Expr::ParenExprClass:
151 return ClassifyInternal(Ctx, cast<ParenExpr>(E)->getSubExpr());
152
153 case Expr::BinaryOperatorClass:
154 case Expr::CompoundAssignOperatorClass:
155 // C doesn't have any binary expressions that are lvalues.
156 if (Lang.CPlusPlus)
157 return ClassifyBinaryOp(Ctx, cast<BinaryOperator>(E));
158 return Cl::CL_PRValue;
159
160 case Expr::CallExprClass:
161 case Expr::CXXOperatorCallExprClass:
162 case Expr::CXXMemberCallExprClass:
163 return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType());
164
165 // __builtin_choose_expr is equivalent to the chosen expression.
166 case Expr::ChooseExprClass:
167 return ClassifyInternal(Ctx, cast<ChooseExpr>(E)->getChosenSubExpr(Ctx));
168
169 // Extended vector element access is an lvalue unless there are duplicates
170 // in the shuffle expression.
171 case Expr::ExtVectorElementExprClass:
172 return cast<ExtVectorElementExpr>(E)->containsDuplicateElements() ?
173 Cl::CL_DuplicateVectorComponents : Cl::CL_LValue;
174
175 // Simply look at the actual default argument.
176 case Expr::CXXDefaultArgExprClass:
177 return ClassifyInternal(Ctx, cast<CXXDefaultArgExpr>(E)->getExpr());
178
179 // Same idea for temporary binding.
180 case Expr::CXXBindTemporaryExprClass:
181 return ClassifyInternal(Ctx, cast<CXXBindTemporaryExpr>(E)->getSubExpr());
182
183 // And the temporary lifetime guard.
184 case Expr::CXXExprWithTemporariesClass:
185 return ClassifyInternal(Ctx, cast<CXXExprWithTemporaries>(E)->getSubExpr());
186
187 // Casts depend completely on the target type. All casts work the same.
188 case Expr::CStyleCastExprClass:
189 case Expr::CXXFunctionalCastExprClass:
190 case Expr::CXXStaticCastExprClass:
191 case Expr::CXXDynamicCastExprClass:
192 case Expr::CXXReinterpretCastExprClass:
193 case Expr::CXXConstCastExprClass:
194 // Only in C++ can casts be interesting at all.
195 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
196 return ClassifyUnnamed(Ctx, cast<ExplicitCastExpr>(E)->getTypeAsWritten());
197
198 case Expr::ConditionalOperatorClass:
199 // Once again, only C++ is interesting.
200 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
201 return ClassifyConditional(Ctx, cast<ConditionalOperator>(E));
202
203 // ObjC message sends are effectively function calls, if the target function
204 // is known.
205 case Expr::ObjCMessageExprClass:
206 if (const ObjCMethodDecl *Method =
207 cast<ObjCMessageExpr>(E)->getMethodDecl()) {
208 return ClassifyUnnamed(Ctx, Method->getResultType());
209 }
210
211 // Some C++ expressions are always class temporaries.
212 case Expr::CXXConstructExprClass:
213 case Expr::CXXTemporaryObjectExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +0000214 case Expr::CXXScalarValueInitExprClass:
Sebastian Redl2111c852010-06-28 15:09:07 +0000215 return Cl::CL_ClassTemporary;
216
217 // Everything we haven't handled is a prvalue.
218 default:
219 return Cl::CL_PRValue;
220 }
221}
222
223/// ClassifyDecl - Return the classification of an expression referencing the
224/// given declaration.
225static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
226 // C++ [expr.prim.general]p6: The result is an lvalue if the entity is a
227 // function, variable, or data member and a prvalue otherwise.
228 // In C, functions are not lvalues.
229 // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
230 // lvalue unless it's a reference type (C++ [temp.param]p6), so we need to
231 // special-case this.
232 bool islvalue;
233 if (const NonTypeTemplateParmDecl *NTTParm =
234 dyn_cast<NonTypeTemplateParmDecl>(D))
235 islvalue = NTTParm->getType()->isReferenceType();
236 else
237 islvalue = isa<VarDecl>(D) || isa<FieldDecl>(D) ||
238 (Ctx.getLangOptions().CPlusPlus &&
239 (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)));
240
241 return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
242}
243
244/// ClassifyUnnamed - Return the classification of an expression yielding an
245/// unnamed value of the given type. This applies in particular to function
246/// calls and casts.
247static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
248 // In C, function calls are always rvalues.
249 if (!Ctx.getLangOptions().CPlusPlus) return Cl::CL_PRValue;
250
251 // C++ [expr.call]p10: A function call is an lvalue if the result type is an
252 // lvalue reference type or an rvalue reference to function type, an xvalue
253 // if the result type is an rvalue refernence to object type, and a prvalue
254 // otherwise.
255 if (T->isLValueReferenceType())
256 return Cl::CL_LValue;
257 const RValueReferenceType *RV = T->getAs<RValueReferenceType>();
258 if (!RV) // Could still be a class temporary, though.
259 return T->isRecordType() ? Cl::CL_ClassTemporary : Cl::CL_PRValue;
260
261 return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
262}
263
264static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
265 // Handle C first, it's easier.
266 if (!Ctx.getLangOptions().CPlusPlus) {
267 // C99 6.5.2.3p3
268 // For dot access, the expression is an lvalue if the first part is. For
269 // arrow access, it always is an lvalue.
270 if (E->isArrow())
271 return Cl::CL_LValue;
272 // ObjC property accesses are not lvalues, but get special treatment.
273 Expr *Base = E->getBase();
274 if (isa<ObjCPropertyRefExpr>(Base) ||
275 isa<ObjCImplicitSetterGetterRefExpr>(Base))
276 return Cl::CL_SubObjCPropertySetting;
277 return ClassifyInternal(Ctx, Base);
278 }
279
280 NamedDecl *Member = E->getMemberDecl();
281 // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
282 // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
283 // E1.E2 is an lvalue.
284 if (ValueDecl *Value = dyn_cast<ValueDecl>(Member))
285 if (Value->getType()->isReferenceType())
286 return Cl::CL_LValue;
287
288 // Otherwise, one of the following rules applies.
289 // -- If E2 is a static member [...] then E1.E2 is an lvalue.
290 if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
291 return Cl::CL_LValue;
292
293 // -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
294 // E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
295 // otherwise, it is a prvalue.
296 if (isa<FieldDecl>(Member)) {
297 // *E1 is an lvalue
298 if (E->isArrow())
299 return Cl::CL_LValue;
300 return ClassifyInternal(Ctx, E->getBase());
301 }
302
303 // -- If E2 is a [...] member function, [...]
304 // -- If it refers to a static member function [...], then E1.E2 is an
305 // lvalue; [...]
306 // -- Otherwise [...] E1.E2 is a prvalue.
307 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member))
308 return Method->isStatic() ? Cl::CL_LValue : Cl::CL_MemberFunction;
309
310 // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
311 // So is everything else we haven't handled yet.
312 return Cl::CL_PRValue;
313}
314
315static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
316 assert(Ctx.getLangOptions().CPlusPlus &&
317 "This is only relevant for C++.");
318 // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
319 if (E->isAssignmentOp())
320 return Cl::CL_LValue;
321
322 // C++ [expr.comma]p1: the result is of the same value category as its right
323 // operand, [...].
324 if (E->getOpcode() == BinaryOperator::Comma)
325 return ClassifyInternal(Ctx, E->getRHS());
326
327 // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
328 // is a pointer to a data member is of the same value category as its first
329 // operand.
330 if (E->getOpcode() == BinaryOperator::PtrMemD)
331 return E->getType()->isFunctionType() ? Cl::CL_MemberFunction :
332 ClassifyInternal(Ctx, E->getLHS());
333
334 // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
335 // second operand is a pointer to data member and a prvalue otherwise.
336 if (E->getOpcode() == BinaryOperator::PtrMemI)
337 return E->getType()->isFunctionType() ?
338 Cl::CL_MemberFunction : Cl::CL_LValue;
339
340 // All other binary operations are prvalues.
341 return Cl::CL_PRValue;
342}
343
344static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
345 const ConditionalOperator *E) {
346 assert(Ctx.getLangOptions().CPlusPlus &&
347 "This is only relevant for C++.");
348
349 Expr *True = E->getTrueExpr();
350 Expr *False = E->getFalseExpr();
351 // C++ [expr.cond]p2
352 // If either the second or the third operand has type (cv) void, [...]
353 // the result [...] is a prvalue.
354 if (True->getType()->isVoidType() || False->getType()->isVoidType())
355 return Cl::CL_PRValue;
356
357 // Note that at this point, we have already performed all conversions
358 // according to [expr.cond]p3.
359 // C++ [expr.cond]p4: If the second and third operands are glvalues of the
360 // same value category [...], the result is of that [...] value category.
361 // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
362 Cl::Kinds LCl = ClassifyInternal(Ctx, True),
363 RCl = ClassifyInternal(Ctx, False);
364 return LCl == RCl ? LCl : Cl::CL_PRValue;
365}
366
367static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
368 Cl::Kinds Kind, SourceLocation &Loc) {
369 // As a general rule, we only care about lvalues. But there are some rvalues
370 // for which we want to generate special results.
371 if (Kind == Cl::CL_PRValue) {
372 // For the sake of better diagnostics, we want to specifically recognize
373 // use of the GCC cast-as-lvalue extension.
374 if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E->IgnoreParens())){
375 if (CE->getSubExpr()->Classify(Ctx).isLValue()) {
376 Loc = CE->getLParenLoc();
377 return Cl::CM_LValueCast;
378 }
379 }
380 }
381 if (Kind != Cl::CL_LValue)
382 return Cl::CM_RValue;
383
384 // This is the lvalue case.
385 // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
386 if (Ctx.getLangOptions().CPlusPlus && E->getType()->isFunctionType())
387 return Cl::CM_Function;
388
389 // You cannot assign to a variable outside a block from within the block if
390 // it is not marked __block, e.g.
391 // void takeclosure(void (^C)(void));
392 // void func() { int x = 1; takeclosure(^{ x = 7; }); }
393 if (const BlockDeclRefExpr *BDR = dyn_cast<BlockDeclRefExpr>(E)) {
394 if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
395 return Cl::CM_NotBlockQualified;
396 }
397
398 // Assignment to a property in ObjC is an implicit setter access. But a
399 // setter might not exist.
400 if (const ObjCImplicitSetterGetterRefExpr *Expr =
401 dyn_cast<ObjCImplicitSetterGetterRefExpr>(E)) {
402 if (Expr->getSetterMethod() == 0)
403 return Cl::CM_NoSetterProperty;
404 }
405
406 CanQualType CT = Ctx.getCanonicalType(E->getType());
407 // Const stuff is obviously not modifiable.
408 if (CT.isConstQualified())
409 return Cl::CM_ConstQualified;
410 // Arrays are not modifiable, only their elements are.
411 if (CT->isArrayType())
412 return Cl::CM_ArrayType;
413 // Incomplete types are not modifiable.
414 if (CT->isIncompleteType())
415 return Cl::CM_IncompleteType;
416
417 // Records with any const fields (recursively) are not modifiable.
418 if (const RecordType *R = CT->getAs<RecordType>()) {
419 assert(!Ctx.getLangOptions().CPlusPlus &&
420 "C++ struct assignment should be resolved by the "
421 "copy assignment operator.");
422 if (R->hasConstFields())
423 return Cl::CM_ConstQualified;
424 }
425
426 return Cl::CM_Modifiable;
427}
428
429Expr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const {
430 Classification VC = Classify(Ctx);
431 switch (VC.getKind()) {
432 case Cl::CL_LValue: return LV_Valid;
433 case Cl::CL_XValue: return LV_InvalidExpression;
434 case Cl::CL_Function: return LV_NotObjectType;
435 case Cl::CL_Void: return LV_IncompleteVoidType;
436 case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
437 case Cl::CL_MemberFunction: return LV_MemberFunction;
438 case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
439 case Cl::CL_ClassTemporary: return LV_ClassTemporary;
440 case Cl::CL_PRValue: return LV_InvalidExpression;
441 }
Chandler Carruth0010bca2010-06-29 00:23:11 +0000442 llvm_unreachable("Unhandled kind");
Sebastian Redl2111c852010-06-28 15:09:07 +0000443}
444
445Expr::isModifiableLvalueResult
446Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
447 SourceLocation dummy;
448 Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy);
449 switch (VC.getKind()) {
450 case Cl::CL_LValue: break;
451 case Cl::CL_XValue: return MLV_InvalidExpression;
452 case Cl::CL_Function: return MLV_NotObjectType;
453 case Cl::CL_Void: return MLV_IncompleteVoidType;
454 case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
455 case Cl::CL_MemberFunction: return MLV_MemberFunction;
456 case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
457 case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
458 case Cl::CL_PRValue:
459 return VC.getModifiable() == Cl::CM_LValueCast ?
460 MLV_LValueCast : MLV_InvalidExpression;
461 }
462 assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
463 switch (VC.getModifiable()) {
Chandler Carruth0010bca2010-06-29 00:23:11 +0000464 case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
Sebastian Redl2111c852010-06-28 15:09:07 +0000465 case Cl::CM_Modifiable: return MLV_Valid;
Chandler Carruth0010bca2010-06-29 00:23:11 +0000466 case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
Sebastian Redl2111c852010-06-28 15:09:07 +0000467 case Cl::CM_Function: return MLV_NotObjectType;
468 case Cl::CM_LValueCast:
Chandler Carruth0010bca2010-06-29 00:23:11 +0000469 llvm_unreachable("CM_LValueCast and CL_LValue don't match");
Sebastian Redl2111c852010-06-28 15:09:07 +0000470 case Cl::CM_NotBlockQualified: return MLV_NotBlockQualified;
471 case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
472 case Cl::CM_ConstQualified: return MLV_ConstQualified;
473 case Cl::CM_ArrayType: return MLV_ArrayType;
474 case Cl::CM_IncompleteType: return MLV_IncompleteType;
475 }
Chandler Carruth0010bca2010-06-29 00:23:11 +0000476 llvm_unreachable("Unhandled modifiable type");
Sebastian Redl2111c852010-06-28 15:09:07 +0000477}