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