1//===- ExprClassification.cpp - Expression AST Node Implementation --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements Expr::classify.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "llvm/Support/ErrorHandling.h"
21
22using namespace clang;
23
24using Cl = Expr::Classification;
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 Expr *trueExpr,
33 const Expr *falseExpr);
34static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
35 Cl::Kinds Kind, SourceLocation &Loc);
36
37Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
38 assert(!TR->isReferenceType() && "Expressions can't have reference type.");
39
40 Cl::Kinds kind = ClassifyInternal(Ctx, E: this);
41 // C99 6.3.2.1: An lvalue is an expression with an object type or an
42 // incomplete type other than void.
43 if (!Ctx.getLangOpts().CPlusPlus) {
44 // Thus, no functions.
45 if (TR->isFunctionType() || TR == Ctx.OverloadTy)
46 kind = Cl::CL_Function;
47 // No void either, but qualified void is OK because it is "other than void".
48 // Void "lvalues" are classified as addressable void values, which are void
49 // expressions whose address can be taken.
50 else if (TR->isVoidType() && !TR.hasQualifiers())
51 kind = (kind == Cl::CL_LValue ? Cl::CL_AddressableVoid : Cl::CL_Void);
52 }
53
54 // Enable this assertion for testing.
55 switch (kind) {
56 case Cl::CL_LValue:
57 assert(isLValue());
58 break;
59 case Cl::CL_XValue:
60 assert(isXValue());
61 break;
62 case Cl::CL_Function:
63 case Cl::CL_Void:
64 case Cl::CL_AddressableVoid:
65 case Cl::CL_DuplicateVectorComponents:
66 case Cl::CL_MemberFunction:
67 case Cl::CL_SubObjCPropertySetting:
68 case Cl::CL_ClassTemporary:
69 case Cl::CL_ArrayTemporary:
70 case Cl::CL_ObjCMessageRValue:
71 case Cl::CL_PRValue:
72 assert(isPRValue());
73 break;
74 }
75
76 Cl::ModifiableType modifiable = Cl::CM_Untested;
77 if (Loc)
78 modifiable = IsModifiable(Ctx, E: this, Kind: kind, Loc&: *Loc);
79 return Classification(kind, modifiable);
80}
81
82/// Classify an expression which creates a temporary, based on its type.
83static Cl::Kinds ClassifyTemporary(QualType T) {
84 if (T->isRecordType())
85 return Cl::CL_ClassTemporary;
86 if (T->isArrayType())
87 return Cl::CL_ArrayTemporary;
88
89 // No special classification: these don't behave differently from normal
90 // prvalues.
91 return Cl::CL_PRValue;
92}
93
94static Cl::Kinds ClassifyExprValueKind(const LangOptions &Lang,
95 const Expr *E,
96 ExprValueKind Kind) {
97 switch (Kind) {
98 case VK_PRValue:
99 return Lang.CPlusPlus ? ClassifyTemporary(T: E->getType()) : Cl::CL_PRValue;
100 case VK_LValue:
101 return Cl::CL_LValue;
102 case VK_XValue:
103 return Cl::CL_XValue;
104 }
105 llvm_unreachable("Invalid value category of implicit cast.");
106}
107
108static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
109 // This function takes the first stab at classifying expressions.
110 const LangOptions &Lang = Ctx.getLangOpts();
111
112 switch (E->getStmtClass()) {
113 case Stmt::NoStmtClass:
114#define ABSTRACT_STMT(Kind)
115#define STMT(Kind, Base) case Expr::Kind##Class:
116#define EXPR(Kind, Base)
117#include "clang/AST/StmtNodes.inc"
118 llvm_unreachable("cannot classify a statement");
119
120 // First come the expressions that are always lvalues, unconditionally.
121 case Expr::ObjCIsaExprClass:
122 // C++ [expr.prim.general]p1: A string literal is an lvalue.
123 case Expr::StringLiteralClass:
124 // @encode is equivalent to its string
125 case Expr::ObjCEncodeExprClass:
126 // __func__ and friends are too.
127 case Expr::PredefinedExprClass:
128 // Property references are lvalues
129 case Expr::ObjCSubscriptRefExprClass:
130 case Expr::ObjCPropertyRefExprClass:
131 // C++ [expr.typeid]p1: The result of a typeid expression is an lvalue of...
132 case Expr::CXXTypeidExprClass:
133 case Expr::CXXUuidofExprClass:
134 // Unresolved lookups and uncorrected typos get classified as lvalues.
135 // FIXME: Is this wise? Should they get their own kind?
136 case Expr::UnresolvedLookupExprClass:
137 case Expr::UnresolvedMemberExprClass:
138 case Expr::TypoExprClass:
139 case Expr::DependentCoawaitExprClass:
140 case Expr::CXXDependentScopeMemberExprClass:
141 case Expr::DependentScopeDeclRefExprClass:
142 // ObjC instance variables are lvalues
143 // FIXME: ObjC++0x might have different rules
144 case Expr::ObjCIvarRefExprClass:
145 case Expr::FunctionParmPackExprClass:
146 case Expr::MSPropertyRefExprClass:
147 case Expr::MSPropertySubscriptExprClass:
148 case Expr::OMPArraySectionExprClass:
149 case Expr::OMPArrayShapingExprClass:
150 case Expr::OMPIteratorExprClass:
151 return Cl::CL_LValue;
152
153 // C99 6.5.2.5p5 says that compound literals are lvalues.
154 // In C++, they're prvalue temporaries, except for file-scope arrays.
155 case Expr::CompoundLiteralExprClass:
156 return !E->isLValue() ? ClassifyTemporary(T: E->getType()) : Cl::CL_LValue;
157
158 // Expressions that are prvalues.
159 case Expr::CXXBoolLiteralExprClass:
160 case Expr::CXXPseudoDestructorExprClass:
161 case Expr::UnaryExprOrTypeTraitExprClass:
162 case Expr::CXXNewExprClass:
163 case Expr::CXXNullPtrLiteralExprClass:
164 case Expr::ImaginaryLiteralClass:
165 case Expr::GNUNullExprClass:
166 case Expr::OffsetOfExprClass:
167 case Expr::CXXThrowExprClass:
168 case Expr::ShuffleVectorExprClass:
169 case Expr::ConvertVectorExprClass:
170 case Expr::IntegerLiteralClass:
171 case Expr::FixedPointLiteralClass:
172 case Expr::CharacterLiteralClass:
173 case Expr::AddrLabelExprClass:
174 case Expr::CXXDeleteExprClass:
175 case Expr::ImplicitValueInitExprClass:
176 case Expr::BlockExprClass:
177 case Expr::FloatingLiteralClass:
178 case Expr::CXXNoexceptExprClass:
179 case Expr::CXXScalarValueInitExprClass:
180 case Expr::TypeTraitExprClass:
181 case Expr::ArrayTypeTraitExprClass:
182 case Expr::ExpressionTraitExprClass:
183 case Expr::ObjCSelectorExprClass:
184 case Expr::ObjCProtocolExprClass:
185 case Expr::ObjCStringLiteralClass:
186 case Expr::ObjCBoxedExprClass:
187 case Expr::ObjCArrayLiteralClass:
188 case Expr::ObjCDictionaryLiteralClass:
189 case Expr::ObjCBoolLiteralExprClass:
190 case Expr::ObjCAvailabilityCheckExprClass:
191 case Expr::ParenListExprClass:
192 case Expr::SizeOfPackExprClass:
193 case Expr::SubstNonTypeTemplateParmPackExprClass:
194 case Expr::AsTypeExprClass:
195 case Expr::ObjCIndirectCopyRestoreExprClass:
196 case Expr::AtomicExprClass:
197 case Expr::CXXFoldExprClass:
198 case Expr::ArrayInitLoopExprClass:
199 case Expr::ArrayInitIndexExprClass:
200 case Expr::NoInitExprClass:
201 case Expr::DesignatedInitUpdateExprClass:
202 case Expr::SourceLocExprClass:
203 case Expr::ConceptSpecializationExprClass:
204 case Expr::RequiresExprClass:
205 return Cl::CL_PRValue;
206
207 // Make HLSL this reference-like
208 case Expr::CXXThisExprClass:
209 return Lang.HLSL ? Cl::CL_LValue : Cl::CL_PRValue;
210
211 case Expr::ConstantExprClass:
212 return ClassifyInternal(Ctx, cast<ConstantExpr>(E)->getSubExpr());
213
214 // Next come the complicated cases.
215 case Expr::SubstNonTypeTemplateParmExprClass:
216 return ClassifyInternal(Ctx,
217 cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
218
219 case Expr::PackIndexingExprClass:
220 return ClassifyInternal(Ctx, cast<PackIndexingExpr>(E)->getSelectedExpr());
221
222 // C, C++98 [expr.sub]p1: The result is an lvalue of type "T".
223 // C++11 (DR1213): in the case of an array operand, the result is an lvalue
224 // if that operand is an lvalue and an xvalue otherwise.
225 // Subscripting vector types is more like member access.
226 case Expr::ArraySubscriptExprClass:
227 if (cast<ArraySubscriptExpr>(E)->getBase()->getType()->isVectorType())
228 return ClassifyInternal(Ctx, cast<ArraySubscriptExpr>(E)->getBase());
229 if (Lang.CPlusPlus11) {
230 // Step over the array-to-pointer decay if present, but not over the
231 // temporary materialization.
232 auto *Base = cast<ArraySubscriptExpr>(E)->getBase()->IgnoreImpCasts();
233 if (Base->getType()->isArrayType())
234 return ClassifyInternal(Ctx, Base);
235 }
236 return Cl::CL_LValue;
237
238 // Subscripting matrix types behaves like member accesses.
239 case Expr::MatrixSubscriptExprClass:
240 return ClassifyInternal(Ctx, cast<MatrixSubscriptExpr>(E)->getBase());
241
242 // C++ [expr.prim.general]p3: The result is an lvalue if the entity is a
243 // function or variable and a prvalue otherwise.
244 case Expr::DeclRefExprClass:
245 if (E->getType() == Ctx.UnknownAnyTy)
246 return isa<FunctionDecl>(cast<DeclRefExpr>(E)->getDecl())
247 ? Cl::CL_PRValue : Cl::CL_LValue;
248 return ClassifyDecl(Ctx, cast<DeclRefExpr>(E)->getDecl());
249
250 // Member access is complex.
251 case Expr::MemberExprClass:
252 return ClassifyMemberExpr(Ctx, cast<MemberExpr>(E));
253
254 case Expr::UnaryOperatorClass:
255 switch (cast<UnaryOperator>(E)->getOpcode()) {
256 // C++ [expr.unary.op]p1: The unary * operator performs indirection:
257 // [...] the result is an lvalue referring to the object or function
258 // to which the expression points.
259 case UO_Deref:
260 return Cl::CL_LValue;
261
262 // GNU extensions, simply look through them.
263 case UO_Extension:
264 return ClassifyInternal(Ctx, cast<UnaryOperator>(E)->getSubExpr());
265
266 // Treat _Real and _Imag basically as if they were member
267 // expressions: l-value only if the operand is a true l-value.
268 case UO_Real:
269 case UO_Imag: {
270 const Expr *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
271 Cl::Kinds K = ClassifyInternal(Ctx, E: Op);
272 if (K != Cl::CL_LValue) return K;
273
274 if (isa<ObjCPropertyRefExpr>(Op))
275 return Cl::CL_SubObjCPropertySetting;
276 return Cl::CL_LValue;
277 }
278
279 // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
280 // lvalue, [...]
281 // Not so in C.
282 case UO_PreInc:
283 case UO_PreDec:
284 return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
285
286 default:
287 return Cl::CL_PRValue;
288 }
289
290 case Expr::RecoveryExprClass:
291 case Expr::OpaqueValueExprClass:
292 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
293
294 // Pseudo-object expressions can produce l-values with reference magic.
295 case Expr::PseudoObjectExprClass:
296 return ClassifyExprValueKind(Lang, E,
297 cast<PseudoObjectExpr>(E)->getValueKind());
298
299 // Implicit casts are lvalues if they're lvalue casts. Other than that, we
300 // only specifically record class temporaries.
301 case Expr::ImplicitCastExprClass:
302 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
303
304 // C++ [expr.prim.general]p4: The presence of parentheses does not affect
305 // whether the expression is an lvalue.
306 case Expr::ParenExprClass:
307 return ClassifyInternal(Ctx, cast<ParenExpr>(E)->getSubExpr());
308
309 // C11 6.5.1.1p4: [A generic selection] is an lvalue, a function designator,
310 // or a void expression if its result expression is, respectively, an
311 // lvalue, a function designator, or a void expression.
312 case Expr::GenericSelectionExprClass:
313 if (cast<GenericSelectionExpr>(E)->isResultDependent())
314 return Cl::CL_PRValue;
315 return ClassifyInternal(Ctx,cast<GenericSelectionExpr>(E)->getResultExpr());
316
317 case Expr::BinaryOperatorClass:
318 case Expr::CompoundAssignOperatorClass:
319 // C doesn't have any binary expressions that are lvalues.
320 if (Lang.CPlusPlus)
321 return ClassifyBinaryOp(Ctx, cast<BinaryOperator>(E));
322 return Cl::CL_PRValue;
323
324 case Expr::CallExprClass:
325 case Expr::CXXOperatorCallExprClass:
326 case Expr::CXXMemberCallExprClass:
327 case Expr::UserDefinedLiteralClass:
328 case Expr::CUDAKernelCallExprClass:
329 return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType(Ctx));
330
331 case Expr::CXXRewrittenBinaryOperatorClass:
332 return ClassifyInternal(
333 Ctx, cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
334
335 // __builtin_choose_expr is equivalent to the chosen expression.
336 case Expr::ChooseExprClass:
337 return ClassifyInternal(Ctx, cast<ChooseExpr>(E)->getChosenSubExpr());
338
339 // Extended vector element access is an lvalue unless there are duplicates
340 // in the shuffle expression.
341 case Expr::ExtVectorElementExprClass:
342 if (cast<ExtVectorElementExpr>(E)->containsDuplicateElements())
343 return Cl::CL_DuplicateVectorComponents;
344 if (cast<ExtVectorElementExpr>(E)->isArrow())
345 return Cl::CL_LValue;
346 return ClassifyInternal(Ctx, cast<ExtVectorElementExpr>(E)->getBase());
347
348 // Simply look at the actual default argument.
349 case Expr::CXXDefaultArgExprClass:
350 return ClassifyInternal(Ctx, cast<CXXDefaultArgExpr>(E)->getExpr());
351
352 // Same idea for default initializers.
353 case Expr::CXXDefaultInitExprClass:
354 return ClassifyInternal(Ctx, cast<CXXDefaultInitExpr>(E)->getExpr());
355
356 // Same idea for temporary binding.
357 case Expr::CXXBindTemporaryExprClass:
358 return ClassifyInternal(Ctx, cast<CXXBindTemporaryExpr>(E)->getSubExpr());
359
360 // And the cleanups guard.
361 case Expr::ExprWithCleanupsClass:
362 return ClassifyInternal(Ctx, cast<ExprWithCleanups>(E)->getSubExpr());
363
364 // Casts depend completely on the target type. All casts work the same.
365 case Expr::CStyleCastExprClass:
366 case Expr::CXXFunctionalCastExprClass:
367 case Expr::CXXStaticCastExprClass:
368 case Expr::CXXDynamicCastExprClass:
369 case Expr::CXXReinterpretCastExprClass:
370 case Expr::CXXConstCastExprClass:
371 case Expr::CXXAddrspaceCastExprClass:
372 case Expr::ObjCBridgedCastExprClass:
373 case Expr::BuiltinBitCastExprClass:
374 // Only in C++ can casts be interesting at all.
375 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
376 return ClassifyUnnamed(Ctx, cast<ExplicitCastExpr>(E)->getTypeAsWritten());
377
378 case Expr::CXXUnresolvedConstructExprClass:
379 return ClassifyUnnamed(Ctx,
380 cast<CXXUnresolvedConstructExpr>(E)->getTypeAsWritten());
381
382 case Expr::BinaryConditionalOperatorClass: {
383 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
384 const auto *co = cast<BinaryConditionalOperator>(E);
385 return ClassifyConditional(Ctx, co->getTrueExpr(), co->getFalseExpr());
386 }
387
388 case Expr::ConditionalOperatorClass: {
389 // Once again, only C++ is interesting.
390 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
391 const auto *co = cast<ConditionalOperator>(E);
392 return ClassifyConditional(Ctx, co->getTrueExpr(), co->getFalseExpr());
393 }
394
395 // ObjC message sends are effectively function calls, if the target function
396 // is known.
397 case Expr::ObjCMessageExprClass:
398 if (const ObjCMethodDecl *Method =
399 cast<ObjCMessageExpr>(E)->getMethodDecl()) {
400 Cl::Kinds kind = ClassifyUnnamed(Ctx, T: Method->getReturnType());
401 return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind;
402 }
403 return Cl::CL_PRValue;
404
405 // Some C++ expressions are always class temporaries.
406 case Expr::CXXConstructExprClass:
407 case Expr::CXXInheritedCtorInitExprClass:
408 case Expr::CXXTemporaryObjectExprClass:
409 case Expr::LambdaExprClass:
410 case Expr::CXXStdInitializerListExprClass:
411 return Cl::CL_ClassTemporary;
412
413 case Expr::VAArgExprClass:
414 return ClassifyUnnamed(Ctx, T: E->getType());
415
416 case Expr::DesignatedInitExprClass:
417 return ClassifyInternal(Ctx, cast<DesignatedInitExpr>(E)->getInit());
418
419 case Expr::StmtExprClass: {
420 const CompoundStmt *S = cast<StmtExpr>(E)->getSubStmt();
421 if (const auto *LastExpr = dyn_cast_or_null<Expr>(S->body_back()))
422 return ClassifyUnnamed(Ctx, LastExpr->getType());
423 return Cl::CL_PRValue;
424 }
425
426 case Expr::PackExpansionExprClass:
427 return ClassifyInternal(Ctx, cast<PackExpansionExpr>(E)->getPattern());
428
429 case Expr::MaterializeTemporaryExprClass:
430 return cast<MaterializeTemporaryExpr>(E)->isBoundToLvalueReference()
431 ? Cl::CL_LValue
432 : Cl::CL_XValue;
433
434 case Expr::InitListExprClass:
435 // An init list can be an lvalue if it is bound to a reference and
436 // contains only one element. In that case, we look at that element
437 // for an exact classification. Init list creation takes care of the
438 // value kind for us, so we only need to fine-tune.
439 if (E->isPRValue())
440 return ClassifyExprValueKind(Lang, E, Kind: E->getValueKind());
441 assert(cast<InitListExpr>(E)->getNumInits() == 1 &&
442 "Only 1-element init lists can be glvalues.");
443 return ClassifyInternal(Ctx, cast<InitListExpr>(E)->getInit(0));
444
445 case Expr::CoawaitExprClass:
446 case Expr::CoyieldExprClass:
447 return ClassifyInternal(Ctx, cast<CoroutineSuspendExpr>(E)->getResumeExpr());
448 case Expr::SYCLUniqueStableNameExprClass:
449 return Cl::CL_PRValue;
450 break;
451
452 case Expr::CXXParenListInitExprClass:
453 if (isa<ArrayType>(E->getType()))
454 return Cl::CL_ArrayTemporary;
455 return Cl::CL_ClassTemporary;
456 }
457
458 llvm_unreachable("unhandled expression kind in classification");
459}
460
461/// ClassifyDecl - Return the classification of an expression referencing the
462/// given declaration.
463static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
464 // C++ [expr.prim.general]p6: The result is an lvalue if the entity is a
465 // function, variable, or data member and a prvalue otherwise.
466 // In C, functions are not lvalues.
467 // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
468 // lvalue unless it's a reference type (C++ [temp.param]p6), so we need to
469 // special-case this.
470
471 if (const auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
472 if (M->isImplicitObjectMemberFunction())
473 return Cl::CL_MemberFunction;
474 if (M->isStatic())
475 return Cl::CL_LValue;
476 return Cl::CL_PRValue;
477 }
478
479 bool islvalue;
480 if (const auto *NTTParm = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
481 islvalue = NTTParm->getType()->isReferenceType() ||
482 NTTParm->getType()->isRecordType();
483 else
484 islvalue =
485 isa<VarDecl, FieldDecl, IndirectFieldDecl, BindingDecl, MSGuidDecl,
486 UnnamedGlobalConstantDecl, TemplateParamObjectDecl>(Val: D) ||
487 (Ctx.getLangOpts().CPlusPlus &&
488 (isa<FunctionDecl, MSPropertyDecl, FunctionTemplateDecl>(Val: D)));
489
490 return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
491}
492
493/// ClassifyUnnamed - Return the classification of an expression yielding an
494/// unnamed value of the given type. This applies in particular to function
495/// calls and casts.
496static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
497 // In C, function calls are always rvalues.
498 if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue;
499
500 // C++ [expr.call]p10: A function call is an lvalue if the result type is an
501 // lvalue reference type or an rvalue reference to function type, an xvalue
502 // if the result type is an rvalue reference to object type, and a prvalue
503 // otherwise.
504 if (T->isLValueReferenceType())
505 return Cl::CL_LValue;
506 const auto *RV = T->getAs<RValueReferenceType>();
507 if (!RV) // Could still be a class temporary, though.
508 return ClassifyTemporary(T);
509
510 return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
511}
512
513static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
514 if (E->getType() == Ctx.UnknownAnyTy)
515 return (isa<FunctionDecl>(Val: E->getMemberDecl())
516 ? Cl::CL_PRValue : Cl::CL_LValue);
517
518 // Handle C first, it's easier.
519 if (!Ctx.getLangOpts().CPlusPlus) {
520 // C99 6.5.2.3p3
521 // For dot access, the expression is an lvalue if the first part is. For
522 // arrow access, it always is an lvalue.
523 if (E->isArrow())
524 return Cl::CL_LValue;
525 // ObjC property accesses are not lvalues, but get special treatment.
526 Expr *Base = E->getBase()->IgnoreParens();
527 if (isa<ObjCPropertyRefExpr>(Val: Base))
528 return Cl::CL_SubObjCPropertySetting;
529 return ClassifyInternal(Ctx, E: Base);
530 }
531
532 NamedDecl *Member = E->getMemberDecl();
533 // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
534 // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
535 // E1.E2 is an lvalue.
536 if (const auto *Value = dyn_cast<ValueDecl>(Member))
537 if (Value->getType()->isReferenceType())
538 return Cl::CL_LValue;
539
540 // Otherwise, one of the following rules applies.
541 // -- If E2 is a static member [...] then E1.E2 is an lvalue.
542 if (isa<VarDecl>(Val: Member) && Member->getDeclContext()->isRecord())
543 return Cl::CL_LValue;
544
545 // -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
546 // E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
547 // otherwise, it is a prvalue.
548 if (isa<FieldDecl>(Val: Member)) {
549 // *E1 is an lvalue
550 if (E->isArrow())
551 return Cl::CL_LValue;
552 Expr *Base = E->getBase()->IgnoreParenImpCasts();
553 if (isa<ObjCPropertyRefExpr>(Val: Base))
554 return Cl::CL_SubObjCPropertySetting;
555 return ClassifyInternal(Ctx, E: E->getBase());
556 }
557
558 // -- If E2 is a [...] member function, [...]
559 // -- If it refers to a static member function [...], then E1.E2 is an
560 // lvalue; [...]
561 // -- Otherwise [...] E1.E2 is a prvalue.
562 if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
563 if (Method->isStatic())
564 return Cl::CL_LValue;
565 if (Method->isImplicitObjectMemberFunction())
566 return Cl::CL_MemberFunction;
567 return Cl::CL_PRValue;
568 }
569
570 // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
571 // So is everything else we haven't handled yet.
572 return Cl::CL_PRValue;
573}
574
575static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
576 assert(Ctx.getLangOpts().CPlusPlus &&
577 "This is only relevant for C++.");
578 // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
579 // Except we override this for writes to ObjC properties.
580 if (E->isAssignmentOp())
581 return (E->getLHS()->getObjectKind() == OK_ObjCProperty
582 ? Cl::CL_PRValue : Cl::CL_LValue);
583
584 // C++ [expr.comma]p1: the result is of the same value category as its right
585 // operand, [...].
586 if (E->getOpcode() == BO_Comma)
587 return ClassifyInternal(Ctx, E: E->getRHS());
588
589 // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
590 // is a pointer to a data member is of the same value category as its first
591 // operand.
592 if (E->getOpcode() == BO_PtrMemD)
593 return (E->getType()->isFunctionType() ||
594 E->hasPlaceholderType(BuiltinType::BoundMember))
595 ? Cl::CL_MemberFunction
596 : ClassifyInternal(Ctx, E: E->getLHS());
597
598 // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
599 // second operand is a pointer to data member and a prvalue otherwise.
600 if (E->getOpcode() == BO_PtrMemI)
601 return (E->getType()->isFunctionType() ||
602 E->hasPlaceholderType(BuiltinType::BoundMember))
603 ? Cl::CL_MemberFunction
604 : Cl::CL_LValue;
605
606 // All other binary operations are prvalues.
607 return Cl::CL_PRValue;
608}
609
610static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,
611 const Expr *False) {
612 assert(Ctx.getLangOpts().CPlusPlus &&
613 "This is only relevant for C++.");
614
615 // C++ [expr.cond]p2
616 // If either the second or the third operand has type (cv) void,
617 // one of the following shall hold:
618 if (True->getType()->isVoidType() || False->getType()->isVoidType()) {
619 // The second or the third operand (but not both) is a (possibly
620 // parenthesized) throw-expression; the result is of the [...] value
621 // category of the other.
622 bool TrueIsThrow = isa<CXXThrowExpr>(Val: True->IgnoreParenImpCasts());
623 bool FalseIsThrow = isa<CXXThrowExpr>(Val: False->IgnoreParenImpCasts());
624 if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False)
625 : (FalseIsThrow ? True : nullptr))
626 return ClassifyInternal(Ctx, E: NonThrow);
627
628 // [Otherwise] the result [...] is a prvalue.
629 return Cl::CL_PRValue;
630 }
631
632 // Note that at this point, we have already performed all conversions
633 // according to [expr.cond]p3.
634 // C++ [expr.cond]p4: If the second and third operands are glvalues of the
635 // same value category [...], the result is of that [...] value category.
636 // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
637 Cl::Kinds LCl = ClassifyInternal(Ctx, E: True),
638 RCl = ClassifyInternal(Ctx, E: False);
639 return LCl == RCl ? LCl : Cl::CL_PRValue;
640}
641
642static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
643 Cl::Kinds Kind, SourceLocation &Loc) {
644 // As a general rule, we only care about lvalues. But there are some rvalues
645 // for which we want to generate special results.
646 if (Kind == Cl::CL_PRValue) {
647 // For the sake of better diagnostics, we want to specifically recognize
648 // use of the GCC cast-as-lvalue extension.
649 if (const auto *CE = dyn_cast<ExplicitCastExpr>(Val: E->IgnoreParens())) {
650 if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) {
651 Loc = CE->getExprLoc();
652 return Cl::CM_LValueCast;
653 }
654 }
655 }
656 if (Kind != Cl::CL_LValue)
657 return Cl::CM_RValue;
658
659 // This is the lvalue case.
660 // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
661 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())
662 return Cl::CM_Function;
663
664 // Assignment to a property in ObjC is an implicit setter access. But a
665 // setter might not exist.
666 if (const auto *Expr = dyn_cast<ObjCPropertyRefExpr>(Val: E)) {
667 if (Expr->isImplicitProperty() &&
668 Expr->getImplicitPropertySetter() == nullptr)
669 return Cl::CM_NoSetterProperty;
670 }
671
672 CanQualType CT = Ctx.getCanonicalType(T: E->getType());
673 // Const stuff is obviously not modifiable.
674 if (CT.isConstQualified())
675 return Cl::CM_ConstQualified;
676 if (Ctx.getLangOpts().OpenCL &&
677 CT.getQualifiers().getAddressSpace() == LangAS::opencl_constant)
678 return Cl::CM_ConstAddrSpace;
679
680 // Arrays are not modifiable, only their elements are.
681 if (CT->isArrayType())
682 return Cl::CM_ArrayType;
683 // Incomplete types are not modifiable.
684 if (CT->isIncompleteType())
685 return Cl::CM_IncompleteType;
686
687 // Records with any const fields (recursively) are not modifiable.
688 if (const RecordType *R = CT->getAs<RecordType>())
689 if (R->hasConstFields())
690 return Cl::CM_ConstQualifiedField;
691
692 return Cl::CM_Modifiable;
693}
694
695Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const {
696 Classification VC = Classify(Ctx);
697 switch (VC.getKind()) {
698 case Cl::CL_LValue: return LV_Valid;
699 case Cl::CL_XValue: return LV_InvalidExpression;
700 case Cl::CL_Function: return LV_NotObjectType;
701 case Cl::CL_Void: return LV_InvalidExpression;
702 case Cl::CL_AddressableVoid: return LV_IncompleteVoidType;
703 case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
704 case Cl::CL_MemberFunction: return LV_MemberFunction;
705 case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
706 case Cl::CL_ClassTemporary: return LV_ClassTemporary;
707 case Cl::CL_ArrayTemporary: return LV_ArrayTemporary;
708 case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression;
709 case Cl::CL_PRValue: return LV_InvalidExpression;
710 }
711 llvm_unreachable("Unhandled kind");
712}
713
714Expr::isModifiableLvalueResult
715Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
716 SourceLocation dummy;
717 Classification VC = ClassifyModifiable(Ctx, Loc&: Loc ? *Loc : dummy);
718 switch (VC.getKind()) {
719 case Cl::CL_LValue: break;
720 case Cl::CL_XValue: return MLV_InvalidExpression;
721 case Cl::CL_Function: return MLV_NotObjectType;
722 case Cl::CL_Void: return MLV_InvalidExpression;
723 case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType;
724 case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
725 case Cl::CL_MemberFunction: return MLV_MemberFunction;
726 case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
727 case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
728 case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary;
729 case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression;
730 case Cl::CL_PRValue:
731 return VC.getModifiable() == Cl::CM_LValueCast ?
732 MLV_LValueCast : MLV_InvalidExpression;
733 }
734 assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
735 switch (VC.getModifiable()) {
736 case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
737 case Cl::CM_Modifiable: return MLV_Valid;
738 case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
739 case Cl::CM_Function: return MLV_NotObjectType;
740 case Cl::CM_LValueCast:
741 llvm_unreachable("CM_LValueCast and CL_LValue don't match");
742 case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
743 case Cl::CM_ConstQualified: return MLV_ConstQualified;
744 case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField;
745 case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace;
746 case Cl::CM_ArrayType: return MLV_ArrayType;
747 case Cl::CM_IncompleteType: return MLV_IncompleteType;
748 }
749 llvm_unreachable("Unhandled modifiable type");
750}
751

source code of clang/lib/AST/ExprClassification.cpp