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