1 //===--- ExprClassification.cpp - Expression AST Node Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Expr::classify.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/ErrorHandling.h"
15 #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"
22 using namespace clang;
24 typedef Expr::Classification Cl;
26 static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E);
27 static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D);
28 static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T);
29 static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E);
30 static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E);
31 static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
32 const ConditionalOperator *E);
33 static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
34 Cl::Kinds Kind, SourceLocation &Loc);
36 Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
37 assert(!TR->isReferenceType() && "Expressions can't have reference type.");
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())
51 Cl::ModifiableType modifiable = Cl::CM_Untested;
53 modifiable = IsModifiable(Ctx, this, kind, *Loc);
54 return Classification(kind, modifiable);
57 static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
58 // This function takes the first stab at classifying expressions.
59 const LangOptions &Lang = Ctx.getLangOptions();
61 switch (E->getStmtClass()) {
62 // First come the expressions that are always lvalues, unconditionally.
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:
88 // Next come the complicated cases.
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());
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());
105 // Member access is complex.
106 case Expr::MemberExprClass:
107 return ClassifyMemberExpr(Ctx, cast<MemberExpr>(E));
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.
115 return Cl::CL_LValue;
117 // GNU extensions, simply look through them.
121 return ClassifyInternal(Ctx, cast<UnaryOperator>(E)->getSubExpr());
123 // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
128 return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
131 return Cl::CL_PRValue;
134 // Implicit casts are lvalues if they're lvalue casts. Other than that, we
135 // only specifically record class temporaries.
136 case Expr::ImplicitCastExprClass:
137 switch (cast<ImplicitCastExpr>(E)->getValueKind()) {
139 return Lang.CPlusPlus && E->getType()->isRecordType() ?
140 Cl::CL_ClassTemporary : Cl::CL_PRValue;
142 return Cl::CL_LValue;
144 return Cl::CL_XValue;
146 llvm_unreachable("Invalid value category of implicit cast.");
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());
153 case Expr::BinaryOperatorClass:
154 case Expr::CompoundAssignOperatorClass:
155 // C doesn't have any binary expressions that are lvalues.
157 return ClassifyBinaryOp(Ctx, cast<BinaryOperator>(E));
158 return Cl::CL_PRValue;
160 case Expr::CallExprClass:
161 case Expr::CXXOperatorCallExprClass:
162 case Expr::CXXMemberCallExprClass:
163 return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType());
165 // __builtin_choose_expr is equivalent to the chosen expression.
166 case Expr::ChooseExprClass:
167 return ClassifyInternal(Ctx, cast<ChooseExpr>(E)->getChosenSubExpr(Ctx));
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;
175 // Simply look at the actual default argument.
176 case Expr::CXXDefaultArgExprClass:
177 return ClassifyInternal(Ctx, cast<CXXDefaultArgExpr>(E)->getExpr());
179 // Same idea for temporary binding.
180 case Expr::CXXBindTemporaryExprClass:
181 return ClassifyInternal(Ctx, cast<CXXBindTemporaryExpr>(E)->getSubExpr());
183 // And the temporary lifetime guard.
184 case Expr::CXXExprWithTemporariesClass:
185 return ClassifyInternal(Ctx, cast<CXXExprWithTemporaries>(E)->getSubExpr());
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());
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));
203 // ObjC message sends are effectively function calls, if the target function
205 case Expr::ObjCMessageExprClass:
206 if (const ObjCMethodDecl *Method =
207 cast<ObjCMessageExpr>(E)->getMethodDecl()) {
208 return ClassifyUnnamed(Ctx, Method->getResultType());
211 // Some C++ expressions are always class temporaries.
212 case Expr::CXXConstructExprClass:
213 case Expr::CXXTemporaryObjectExprClass:
214 case Expr::CXXScalarValueInitExprClass:
215 return Cl::CL_ClassTemporary;
217 // Everything we haven't handled is a prvalue.
219 return Cl::CL_PRValue;
223 /// ClassifyDecl - Return the classification of an expression referencing the
224 /// given declaration.
225 static 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.
233 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
234 return Cl::CL_MemberFunction;
237 if (const NonTypeTemplateParmDecl *NTTParm =
238 dyn_cast<NonTypeTemplateParmDecl>(D))
239 islvalue = NTTParm->getType()->isReferenceType();
241 islvalue = isa<VarDecl>(D) || isa<FieldDecl>(D) ||
242 (Ctx.getLangOptions().CPlusPlus &&
243 (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)));
245 return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
248 /// ClassifyUnnamed - Return the classification of an expression yielding an
249 /// unnamed value of the given type. This applies in particular to function
251 static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
252 // In C, function calls are always rvalues.
253 if (!Ctx.getLangOptions().CPlusPlus) return Cl::CL_PRValue;
255 // C++ [expr.call]p10: A function call is an lvalue if the result type is an
256 // lvalue reference type or an rvalue reference to function type, an xvalue
257 // if the result type is an rvalue refernence to object type, and a prvalue
259 if (T->isLValueReferenceType())
260 return Cl::CL_LValue;
261 const RValueReferenceType *RV = T->getAs<RValueReferenceType>();
262 if (!RV) // Could still be a class temporary, though.
263 return T->isRecordType() ? Cl::CL_ClassTemporary : Cl::CL_PRValue;
265 return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
268 static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
269 // Handle C first, it's easier.
270 if (!Ctx.getLangOptions().CPlusPlus) {
272 // For dot access, the expression is an lvalue if the first part is. For
273 // arrow access, it always is an lvalue.
275 return Cl::CL_LValue;
276 // ObjC property accesses are not lvalues, but get special treatment.
277 Expr *Base = E->getBase();
278 if (isa<ObjCPropertyRefExpr>(Base) ||
279 isa<ObjCImplicitSetterGetterRefExpr>(Base))
280 return Cl::CL_SubObjCPropertySetting;
281 return ClassifyInternal(Ctx, Base);
284 NamedDecl *Member = E->getMemberDecl();
285 // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
286 // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
287 // E1.E2 is an lvalue.
288 if (ValueDecl *Value = dyn_cast<ValueDecl>(Member))
289 if (Value->getType()->isReferenceType())
290 return Cl::CL_LValue;
292 // Otherwise, one of the following rules applies.
293 // -- If E2 is a static member [...] then E1.E2 is an lvalue.
294 if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
295 return Cl::CL_LValue;
297 // -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
298 // E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
299 // otherwise, it is a prvalue.
300 if (isa<FieldDecl>(Member)) {
303 return Cl::CL_LValue;
304 return ClassifyInternal(Ctx, E->getBase());
307 // -- If E2 is a [...] member function, [...]
308 // -- If it refers to a static member function [...], then E1.E2 is an
310 // -- Otherwise [...] E1.E2 is a prvalue.
311 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member))
312 return Method->isStatic() ? Cl::CL_LValue : Cl::CL_MemberFunction;
314 // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
315 // So is everything else we haven't handled yet.
316 return Cl::CL_PRValue;
319 static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
320 assert(Ctx.getLangOptions().CPlusPlus &&
321 "This is only relevant for C++.");
322 // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
323 if (E->isAssignmentOp())
324 return Cl::CL_LValue;
326 // C++ [expr.comma]p1: the result is of the same value category as its right
328 if (E->getOpcode() == BO_Comma)
329 return ClassifyInternal(Ctx, E->getRHS());
331 // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
332 // is a pointer to a data member is of the same value category as its first
334 if (E->getOpcode() == BO_PtrMemD)
335 return E->getType()->isFunctionType() ? Cl::CL_MemberFunction :
336 ClassifyInternal(Ctx, E->getLHS());
338 // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
339 // second operand is a pointer to data member and a prvalue otherwise.
340 if (E->getOpcode() == BO_PtrMemI)
341 return E->getType()->isFunctionType() ?
342 Cl::CL_MemberFunction : Cl::CL_LValue;
344 // All other binary operations are prvalues.
345 return Cl::CL_PRValue;
348 static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
349 const ConditionalOperator *E) {
350 assert(Ctx.getLangOptions().CPlusPlus &&
351 "This is only relevant for C++.");
353 Expr *True = E->getTrueExpr();
354 Expr *False = E->getFalseExpr();
356 // If either the second or the third operand has type (cv) void, [...]
357 // the result [...] is a prvalue.
358 if (True->getType()->isVoidType() || False->getType()->isVoidType())
359 return Cl::CL_PRValue;
361 // Note that at this point, we have already performed all conversions
362 // according to [expr.cond]p3.
363 // C++ [expr.cond]p4: If the second and third operands are glvalues of the
364 // same value category [...], the result is of that [...] value category.
365 // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
366 Cl::Kinds LCl = ClassifyInternal(Ctx, True),
367 RCl = ClassifyInternal(Ctx, False);
368 return LCl == RCl ? LCl : Cl::CL_PRValue;
371 static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
372 Cl::Kinds Kind, SourceLocation &Loc) {
373 // As a general rule, we only care about lvalues. But there are some rvalues
374 // for which we want to generate special results.
375 if (Kind == Cl::CL_PRValue) {
376 // For the sake of better diagnostics, we want to specifically recognize
377 // use of the GCC cast-as-lvalue extension.
378 if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E->IgnoreParens())){
379 if (CE->getSubExpr()->Classify(Ctx).isLValue()) {
380 Loc = CE->getLParenLoc();
381 return Cl::CM_LValueCast;
385 if (Kind != Cl::CL_LValue)
386 return Cl::CM_RValue;
388 // This is the lvalue case.
389 // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
390 if (Ctx.getLangOptions().CPlusPlus && E->getType()->isFunctionType())
391 return Cl::CM_Function;
393 // You cannot assign to a variable outside a block from within the block if
394 // it is not marked __block, e.g.
395 // void takeclosure(void (^C)(void));
396 // void func() { int x = 1; takeclosure(^{ x = 7; }); }
397 if (const BlockDeclRefExpr *BDR = dyn_cast<BlockDeclRefExpr>(E)) {
398 if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
399 return Cl::CM_NotBlockQualified;
402 // Assignment to a property in ObjC is an implicit setter access. But a
403 // setter might not exist.
404 if (const ObjCImplicitSetterGetterRefExpr *Expr =
405 dyn_cast<ObjCImplicitSetterGetterRefExpr>(E)) {
406 if (Expr->getSetterMethod() == 0)
407 return Cl::CM_NoSetterProperty;
410 CanQualType CT = Ctx.getCanonicalType(E->getType());
411 // Const stuff is obviously not modifiable.
412 if (CT.isConstQualified())
413 return Cl::CM_ConstQualified;
414 // Arrays are not modifiable, only their elements are.
415 if (CT->isArrayType())
416 return Cl::CM_ArrayType;
417 // Incomplete types are not modifiable.
418 if (CT->isIncompleteType())
419 return Cl::CM_IncompleteType;
421 // Records with any const fields (recursively) are not modifiable.
422 if (const RecordType *R = CT->getAs<RecordType>()) {
423 assert(!Ctx.getLangOptions().CPlusPlus &&
424 "C++ struct assignment should be resolved by the "
425 "copy assignment operator.");
426 if (R->hasConstFields())
427 return Cl::CM_ConstQualified;
430 return Cl::CM_Modifiable;
433 Expr::isLvalueResult Expr::isLvalue(ASTContext &Ctx) const {
434 Classification VC = Classify(Ctx);
435 switch (VC.getKind()) {
436 case Cl::CL_LValue: return LV_Valid;
437 case Cl::CL_XValue: return LV_InvalidExpression;
438 case Cl::CL_Function: return LV_NotObjectType;
439 case Cl::CL_Void: return LV_IncompleteVoidType;
440 case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
441 case Cl::CL_MemberFunction: return LV_MemberFunction;
442 case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
443 case Cl::CL_ClassTemporary: return LV_ClassTemporary;
444 case Cl::CL_PRValue: return LV_InvalidExpression;
446 llvm_unreachable("Unhandled kind");
449 Expr::isModifiableLvalueResult
450 Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
451 SourceLocation dummy;
452 Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy);
453 switch (VC.getKind()) {
454 case Cl::CL_LValue: break;
455 case Cl::CL_XValue: return MLV_InvalidExpression;
456 case Cl::CL_Function: return MLV_NotObjectType;
457 case Cl::CL_Void: return MLV_IncompleteVoidType;
458 case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
459 case Cl::CL_MemberFunction: return MLV_MemberFunction;
460 case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
461 case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
463 return VC.getModifiable() == Cl::CM_LValueCast ?
464 MLV_LValueCast : MLV_InvalidExpression;
466 assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
467 switch (VC.getModifiable()) {
468 case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
469 case Cl::CM_Modifiable: return MLV_Valid;
470 case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
471 case Cl::CM_Function: return MLV_NotObjectType;
472 case Cl::CM_LValueCast:
473 llvm_unreachable("CM_LValueCast and CL_LValue don't match");
474 case Cl::CM_NotBlockQualified: return MLV_NotBlockQualified;
475 case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
476 case Cl::CM_ConstQualified: return MLV_ConstQualified;
477 case Cl::CM_ArrayType: return MLV_ArrayType;
478 case Cl::CM_IncompleteType: return MLV_IncompleteType;
480 llvm_unreachable("Unhandled modifiable type");