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