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
22 using namespace clang;
23
24 using Cl = Expr::Classification;
25
26 static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E);
27 static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D);
28 static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T);
29 static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E);
30 static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E);
31 static Cl::Kinds ClassifyConditional(ASTContext &Ctx,
32 const Expr *trueExpr,
33 const Expr *falseExpr);
34 static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
35 Cl::Kinds Kind, SourceLocation &Loc);
36
ClassifyImpl(ASTContext & Ctx,SourceLocation * Loc) const37 Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
38 assert(!TR->isReferenceType() && "Expressions can't have reference type.");
39
40 Cl::Kinds kind = ClassifyInternal(Ctx, 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, this, kind, *Loc);
79 return Classification(kind, modifiable);
80 }
81
82 /// Classify an expression which creates a temporary, based on its type.
ClassifyTemporary(QualType T)83 static 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
ClassifyExprValueKind(const LangOptions & Lang,const Expr * E,ExprValueKind Kind)94 static 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(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
ClassifyInternal(ASTContext & Ctx,const Expr * E)108 static 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(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 // C, C++98 [expr.sub]p1: The result is an lvalue of type "T".
220 // C++11 (DR1213): in the case of an array operand, the result is an lvalue
221 // if that operand is an lvalue and an xvalue otherwise.
222 // Subscripting vector types is more like member access.
223 case Expr::ArraySubscriptExprClass:
224 if (cast<ArraySubscriptExpr>(E)->getBase()->getType()->isVectorType())
225 return ClassifyInternal(Ctx, cast<ArraySubscriptExpr>(E)->getBase());
226 if (Lang.CPlusPlus11) {
227 // Step over the array-to-pointer decay if present, but not over the
228 // temporary materialization.
229 auto *Base = cast<ArraySubscriptExpr>(E)->getBase()->IgnoreImpCasts();
230 if (Base->getType()->isArrayType())
231 return ClassifyInternal(Ctx, Base);
232 }
233 return Cl::CL_LValue;
234
235 // Subscripting matrix types behaves like member accesses.
236 case Expr::MatrixSubscriptExprClass:
237 return ClassifyInternal(Ctx, cast<MatrixSubscriptExpr>(E)->getBase());
238
239 // C++ [expr.prim.general]p3: The result is an lvalue if the entity is a
240 // function or variable and a prvalue otherwise.
241 case Expr::DeclRefExprClass:
242 if (E->getType() == Ctx.UnknownAnyTy)
243 return isa<FunctionDecl>(cast<DeclRefExpr>(E)->getDecl())
244 ? Cl::CL_PRValue : Cl::CL_LValue;
245 return ClassifyDecl(Ctx, cast<DeclRefExpr>(E)->getDecl());
246
247 // Member access is complex.
248 case Expr::MemberExprClass:
249 return ClassifyMemberExpr(Ctx, cast<MemberExpr>(E));
250
251 case Expr::UnaryOperatorClass:
252 switch (cast<UnaryOperator>(E)->getOpcode()) {
253 // C++ [expr.unary.op]p1: The unary * operator performs indirection:
254 // [...] the result is an lvalue referring to the object or function
255 // to which the expression points.
256 case UO_Deref:
257 return Cl::CL_LValue;
258
259 // GNU extensions, simply look through them.
260 case UO_Extension:
261 return ClassifyInternal(Ctx, cast<UnaryOperator>(E)->getSubExpr());
262
263 // Treat _Real and _Imag basically as if they were member
264 // expressions: l-value only if the operand is a true l-value.
265 case UO_Real:
266 case UO_Imag: {
267 const Expr *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
268 Cl::Kinds K = ClassifyInternal(Ctx, Op);
269 if (K != Cl::CL_LValue) return K;
270
271 if (isa<ObjCPropertyRefExpr>(Op))
272 return Cl::CL_SubObjCPropertySetting;
273 return Cl::CL_LValue;
274 }
275
276 // C++ [expr.pre.incr]p1: The result is the updated operand; it is an
277 // lvalue, [...]
278 // Not so in C.
279 case UO_PreInc:
280 case UO_PreDec:
281 return Lang.CPlusPlus ? Cl::CL_LValue : Cl::CL_PRValue;
282
283 default:
284 return Cl::CL_PRValue;
285 }
286
287 case Expr::RecoveryExprClass:
288 case Expr::OpaqueValueExprClass:
289 return ClassifyExprValueKind(Lang, E, E->getValueKind());
290
291 // Pseudo-object expressions can produce l-values with reference magic.
292 case Expr::PseudoObjectExprClass:
293 return ClassifyExprValueKind(Lang, E,
294 cast<PseudoObjectExpr>(E)->getValueKind());
295
296 // Implicit casts are lvalues if they're lvalue casts. Other than that, we
297 // only specifically record class temporaries.
298 case Expr::ImplicitCastExprClass:
299 return ClassifyExprValueKind(Lang, E, E->getValueKind());
300
301 // C++ [expr.prim.general]p4: The presence of parentheses does not affect
302 // whether the expression is an lvalue.
303 case Expr::ParenExprClass:
304 return ClassifyInternal(Ctx, cast<ParenExpr>(E)->getSubExpr());
305
306 // C11 6.5.1.1p4: [A generic selection] is an lvalue, a function designator,
307 // or a void expression if its result expression is, respectively, an
308 // lvalue, a function designator, or a void expression.
309 case Expr::GenericSelectionExprClass:
310 if (cast<GenericSelectionExpr>(E)->isResultDependent())
311 return Cl::CL_PRValue;
312 return ClassifyInternal(Ctx,cast<GenericSelectionExpr>(E)->getResultExpr());
313
314 case Expr::BinaryOperatorClass:
315 case Expr::CompoundAssignOperatorClass:
316 // C doesn't have any binary expressions that are lvalues.
317 if (Lang.CPlusPlus)
318 return ClassifyBinaryOp(Ctx, cast<BinaryOperator>(E));
319 return Cl::CL_PRValue;
320
321 case Expr::CallExprClass:
322 case Expr::CXXOperatorCallExprClass:
323 case Expr::CXXMemberCallExprClass:
324 case Expr::UserDefinedLiteralClass:
325 case Expr::CUDAKernelCallExprClass:
326 return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType(Ctx));
327
328 case Expr::CXXRewrittenBinaryOperatorClass:
329 return ClassifyInternal(
330 Ctx, cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
331
332 // __builtin_choose_expr is equivalent to the chosen expression.
333 case Expr::ChooseExprClass:
334 return ClassifyInternal(Ctx, cast<ChooseExpr>(E)->getChosenSubExpr());
335
336 // Extended vector element access is an lvalue unless there are duplicates
337 // in the shuffle expression.
338 case Expr::ExtVectorElementExprClass:
339 if (cast<ExtVectorElementExpr>(E)->containsDuplicateElements())
340 return Cl::CL_DuplicateVectorComponents;
341 if (cast<ExtVectorElementExpr>(E)->isArrow())
342 return Cl::CL_LValue;
343 return ClassifyInternal(Ctx, cast<ExtVectorElementExpr>(E)->getBase());
344
345 // Simply look at the actual default argument.
346 case Expr::CXXDefaultArgExprClass:
347 return ClassifyInternal(Ctx, cast<CXXDefaultArgExpr>(E)->getExpr());
348
349 // Same idea for default initializers.
350 case Expr::CXXDefaultInitExprClass:
351 return ClassifyInternal(Ctx, cast<CXXDefaultInitExpr>(E)->getExpr());
352
353 // Same idea for temporary binding.
354 case Expr::CXXBindTemporaryExprClass:
355 return ClassifyInternal(Ctx, cast<CXXBindTemporaryExpr>(E)->getSubExpr());
356
357 // And the cleanups guard.
358 case Expr::ExprWithCleanupsClass:
359 return ClassifyInternal(Ctx, cast<ExprWithCleanups>(E)->getSubExpr());
360
361 // Casts depend completely on the target type. All casts work the same.
362 case Expr::CStyleCastExprClass:
363 case Expr::CXXFunctionalCastExprClass:
364 case Expr::CXXStaticCastExprClass:
365 case Expr::CXXDynamicCastExprClass:
366 case Expr::CXXReinterpretCastExprClass:
367 case Expr::CXXConstCastExprClass:
368 case Expr::CXXAddrspaceCastExprClass:
369 case Expr::ObjCBridgedCastExprClass:
370 case Expr::BuiltinBitCastExprClass:
371 // Only in C++ can casts be interesting at all.
372 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
373 return ClassifyUnnamed(Ctx, cast<ExplicitCastExpr>(E)->getTypeAsWritten());
374
375 case Expr::CXXUnresolvedConstructExprClass:
376 return ClassifyUnnamed(Ctx,
377 cast<CXXUnresolvedConstructExpr>(E)->getTypeAsWritten());
378
379 case Expr::BinaryConditionalOperatorClass: {
380 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
381 const auto *co = cast<BinaryConditionalOperator>(E);
382 return ClassifyConditional(Ctx, co->getTrueExpr(), co->getFalseExpr());
383 }
384
385 case Expr::ConditionalOperatorClass: {
386 // Once again, only C++ is interesting.
387 if (!Lang.CPlusPlus) return Cl::CL_PRValue;
388 const auto *co = cast<ConditionalOperator>(E);
389 return ClassifyConditional(Ctx, co->getTrueExpr(), co->getFalseExpr());
390 }
391
392 // ObjC message sends are effectively function calls, if the target function
393 // is known.
394 case Expr::ObjCMessageExprClass:
395 if (const ObjCMethodDecl *Method =
396 cast<ObjCMessageExpr>(E)->getMethodDecl()) {
397 Cl::Kinds kind = ClassifyUnnamed(Ctx, Method->getReturnType());
398 return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind;
399 }
400 return Cl::CL_PRValue;
401
402 // Some C++ expressions are always class temporaries.
403 case Expr::CXXConstructExprClass:
404 case Expr::CXXInheritedCtorInitExprClass:
405 case Expr::CXXTemporaryObjectExprClass:
406 case Expr::LambdaExprClass:
407 case Expr::CXXStdInitializerListExprClass:
408 return Cl::CL_ClassTemporary;
409
410 case Expr::VAArgExprClass:
411 return ClassifyUnnamed(Ctx, E->getType());
412
413 case Expr::DesignatedInitExprClass:
414 return ClassifyInternal(Ctx, cast<DesignatedInitExpr>(E)->getInit());
415
416 case Expr::StmtExprClass: {
417 const CompoundStmt *S = cast<StmtExpr>(E)->getSubStmt();
418 if (const auto *LastExpr = dyn_cast_or_null<Expr>(S->body_back()))
419 return ClassifyUnnamed(Ctx, LastExpr->getType());
420 return Cl::CL_PRValue;
421 }
422
423 case Expr::PackExpansionExprClass:
424 return ClassifyInternal(Ctx, cast<PackExpansionExpr>(E)->getPattern());
425
426 case Expr::MaterializeTemporaryExprClass:
427 return cast<MaterializeTemporaryExpr>(E)->isBoundToLvalueReference()
428 ? Cl::CL_LValue
429 : Cl::CL_XValue;
430
431 case Expr::InitListExprClass:
432 // An init list can be an lvalue if it is bound to a reference and
433 // contains only one element. In that case, we look at that element
434 // for an exact classification. Init list creation takes care of the
435 // value kind for us, so we only need to fine-tune.
436 if (E->isPRValue())
437 return ClassifyExprValueKind(Lang, E, E->getValueKind());
438 assert(cast<InitListExpr>(E)->getNumInits() == 1 &&
439 "Only 1-element init lists can be glvalues.");
440 return ClassifyInternal(Ctx, cast<InitListExpr>(E)->getInit(0));
441
442 case Expr::CoawaitExprClass:
443 case Expr::CoyieldExprClass:
444 return ClassifyInternal(Ctx, cast<CoroutineSuspendExpr>(E)->getResumeExpr());
445 case Expr::SYCLUniqueStableNameExprClass:
446 return Cl::CL_PRValue;
447 break;
448
449 case Expr::CXXParenListInitExprClass:
450 if (isa<ArrayType>(E->getType()))
451 return Cl::CL_ArrayTemporary;
452 return Cl::CL_ClassTemporary;
453 }
454
455 llvm_unreachable("unhandled expression kind in classification");
456 }
457
458 /// ClassifyDecl - Return the classification of an expression referencing the
459 /// given declaration.
ClassifyDecl(ASTContext & Ctx,const Decl * D)460 static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
461 // C++ [expr.prim.general]p6: The result is an lvalue if the entity is a
462 // function, variable, or data member and a prvalue otherwise.
463 // In C, functions are not lvalues.
464 // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
465 // lvalue unless it's a reference type (C++ [temp.param]p6), so we need to
466 // special-case this.
467
468 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
469 return Cl::CL_MemberFunction;
470
471 bool islvalue;
472 if (const auto *NTTParm = dyn_cast<NonTypeTemplateParmDecl>(D))
473 islvalue = NTTParm->getType()->isReferenceType() ||
474 NTTParm->getType()->isRecordType();
475 else
476 islvalue =
477 isa<VarDecl, FieldDecl, IndirectFieldDecl, BindingDecl, MSGuidDecl,
478 UnnamedGlobalConstantDecl, TemplateParamObjectDecl>(D) ||
479 (Ctx.getLangOpts().CPlusPlus &&
480 (isa<FunctionDecl, MSPropertyDecl, FunctionTemplateDecl>(D)));
481
482 return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
483 }
484
485 /// ClassifyUnnamed - Return the classification of an expression yielding an
486 /// unnamed value of the given type. This applies in particular to function
487 /// calls and casts.
ClassifyUnnamed(ASTContext & Ctx,QualType T)488 static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
489 // In C, function calls are always rvalues.
490 if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue;
491
492 // C++ [expr.call]p10: A function call is an lvalue if the result type is an
493 // lvalue reference type or an rvalue reference to function type, an xvalue
494 // if the result type is an rvalue reference to object type, and a prvalue
495 // otherwise.
496 if (T->isLValueReferenceType())
497 return Cl::CL_LValue;
498 const auto *RV = T->getAs<RValueReferenceType>();
499 if (!RV) // Could still be a class temporary, though.
500 return ClassifyTemporary(T);
501
502 return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
503 }
504
ClassifyMemberExpr(ASTContext & Ctx,const MemberExpr * E)505 static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
506 if (E->getType() == Ctx.UnknownAnyTy)
507 return (isa<FunctionDecl>(E->getMemberDecl())
508 ? Cl::CL_PRValue : Cl::CL_LValue);
509
510 // Handle C first, it's easier.
511 if (!Ctx.getLangOpts().CPlusPlus) {
512 // C99 6.5.2.3p3
513 // For dot access, the expression is an lvalue if the first part is. For
514 // arrow access, it always is an lvalue.
515 if (E->isArrow())
516 return Cl::CL_LValue;
517 // ObjC property accesses are not lvalues, but get special treatment.
518 Expr *Base = E->getBase()->IgnoreParens();
519 if (isa<ObjCPropertyRefExpr>(Base))
520 return Cl::CL_SubObjCPropertySetting;
521 return ClassifyInternal(Ctx, Base);
522 }
523
524 NamedDecl *Member = E->getMemberDecl();
525 // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
526 // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
527 // E1.E2 is an lvalue.
528 if (const auto *Value = dyn_cast<ValueDecl>(Member))
529 if (Value->getType()->isReferenceType())
530 return Cl::CL_LValue;
531
532 // Otherwise, one of the following rules applies.
533 // -- If E2 is a static member [...] then E1.E2 is an lvalue.
534 if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
535 return Cl::CL_LValue;
536
537 // -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
538 // E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
539 // otherwise, it is a prvalue.
540 if (isa<FieldDecl>(Member)) {
541 // *E1 is an lvalue
542 if (E->isArrow())
543 return Cl::CL_LValue;
544 Expr *Base = E->getBase()->IgnoreParenImpCasts();
545 if (isa<ObjCPropertyRefExpr>(Base))
546 return Cl::CL_SubObjCPropertySetting;
547 return ClassifyInternal(Ctx, E->getBase());
548 }
549
550 // -- If E2 is a [...] member function, [...]
551 // -- If it refers to a static member function [...], then E1.E2 is an
552 // lvalue; [...]
553 // -- Otherwise [...] E1.E2 is a prvalue.
554 if (const auto *Method = dyn_cast<CXXMethodDecl>(Member))
555 return Method->isStatic() ? Cl::CL_LValue : Cl::CL_MemberFunction;
556
557 // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
558 // So is everything else we haven't handled yet.
559 return Cl::CL_PRValue;
560 }
561
ClassifyBinaryOp(ASTContext & Ctx,const BinaryOperator * E)562 static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
563 assert(Ctx.getLangOpts().CPlusPlus &&
564 "This is only relevant for C++.");
565 // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
566 // Except we override this for writes to ObjC properties.
567 if (E->isAssignmentOp())
568 return (E->getLHS()->getObjectKind() == OK_ObjCProperty
569 ? Cl::CL_PRValue : Cl::CL_LValue);
570
571 // C++ [expr.comma]p1: the result is of the same value category as its right
572 // operand, [...].
573 if (E->getOpcode() == BO_Comma)
574 return ClassifyInternal(Ctx, E->getRHS());
575
576 // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
577 // is a pointer to a data member is of the same value category as its first
578 // operand.
579 if (E->getOpcode() == BO_PtrMemD)
580 return (E->getType()->isFunctionType() ||
581 E->hasPlaceholderType(BuiltinType::BoundMember))
582 ? Cl::CL_MemberFunction
583 : ClassifyInternal(Ctx, E->getLHS());
584
585 // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
586 // second operand is a pointer to data member and a prvalue otherwise.
587 if (E->getOpcode() == BO_PtrMemI)
588 return (E->getType()->isFunctionType() ||
589 E->hasPlaceholderType(BuiltinType::BoundMember))
590 ? Cl::CL_MemberFunction
591 : Cl::CL_LValue;
592
593 // All other binary operations are prvalues.
594 return Cl::CL_PRValue;
595 }
596
ClassifyConditional(ASTContext & Ctx,const Expr * True,const Expr * False)597 static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,
598 const Expr *False) {
599 assert(Ctx.getLangOpts().CPlusPlus &&
600 "This is only relevant for C++.");
601
602 // C++ [expr.cond]p2
603 // If either the second or the third operand has type (cv) void,
604 // one of the following shall hold:
605 if (True->getType()->isVoidType() || False->getType()->isVoidType()) {
606 // The second or the third operand (but not both) is a (possibly
607 // parenthesized) throw-expression; the result is of the [...] value
608 // category of the other.
609 bool TrueIsThrow = isa<CXXThrowExpr>(True->IgnoreParenImpCasts());
610 bool FalseIsThrow = isa<CXXThrowExpr>(False->IgnoreParenImpCasts());
611 if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False)
612 : (FalseIsThrow ? True : nullptr))
613 return ClassifyInternal(Ctx, NonThrow);
614
615 // [Otherwise] the result [...] is a prvalue.
616 return Cl::CL_PRValue;
617 }
618
619 // Note that at this point, we have already performed all conversions
620 // according to [expr.cond]p3.
621 // C++ [expr.cond]p4: If the second and third operands are glvalues of the
622 // same value category [...], the result is of that [...] value category.
623 // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
624 Cl::Kinds LCl = ClassifyInternal(Ctx, True),
625 RCl = ClassifyInternal(Ctx, False);
626 return LCl == RCl ? LCl : Cl::CL_PRValue;
627 }
628
IsModifiable(ASTContext & Ctx,const Expr * E,Cl::Kinds Kind,SourceLocation & Loc)629 static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
630 Cl::Kinds Kind, SourceLocation &Loc) {
631 // As a general rule, we only care about lvalues. But there are some rvalues
632 // for which we want to generate special results.
633 if (Kind == Cl::CL_PRValue) {
634 // For the sake of better diagnostics, we want to specifically recognize
635 // use of the GCC cast-as-lvalue extension.
636 if (const auto *CE = dyn_cast<ExplicitCastExpr>(E->IgnoreParens())) {
637 if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) {
638 Loc = CE->getExprLoc();
639 return Cl::CM_LValueCast;
640 }
641 }
642 }
643 if (Kind != Cl::CL_LValue)
644 return Cl::CM_RValue;
645
646 // This is the lvalue case.
647 // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
648 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())
649 return Cl::CM_Function;
650
651 // Assignment to a property in ObjC is an implicit setter access. But a
652 // setter might not exist.
653 if (const auto *Expr = dyn_cast<ObjCPropertyRefExpr>(E)) {
654 if (Expr->isImplicitProperty() &&
655 Expr->getImplicitPropertySetter() == nullptr)
656 return Cl::CM_NoSetterProperty;
657 }
658
659 CanQualType CT = Ctx.getCanonicalType(E->getType());
660 // Const stuff is obviously not modifiable.
661 if (CT.isConstQualified())
662 return Cl::CM_ConstQualified;
663 if (Ctx.getLangOpts().OpenCL &&
664 CT.getQualifiers().getAddressSpace() == LangAS::opencl_constant)
665 return Cl::CM_ConstAddrSpace;
666
667 // Arrays are not modifiable, only their elements are.
668 if (CT->isArrayType())
669 return Cl::CM_ArrayType;
670 // Incomplete types are not modifiable.
671 if (CT->isIncompleteType())
672 return Cl::CM_IncompleteType;
673
674 // Records with any const fields (recursively) are not modifiable.
675 if (const RecordType *R = CT->getAs<RecordType>())
676 if (R->hasConstFields())
677 return Cl::CM_ConstQualifiedField;
678
679 return Cl::CM_Modifiable;
680 }
681
ClassifyLValue(ASTContext & Ctx) const682 Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const {
683 Classification VC = Classify(Ctx);
684 switch (VC.getKind()) {
685 case Cl::CL_LValue: return LV_Valid;
686 case Cl::CL_XValue: return LV_InvalidExpression;
687 case Cl::CL_Function: return LV_NotObjectType;
688 case Cl::CL_Void: return LV_InvalidExpression;
689 case Cl::CL_AddressableVoid: return LV_IncompleteVoidType;
690 case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
691 case Cl::CL_MemberFunction: return LV_MemberFunction;
692 case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
693 case Cl::CL_ClassTemporary: return LV_ClassTemporary;
694 case Cl::CL_ArrayTemporary: return LV_ArrayTemporary;
695 case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression;
696 case Cl::CL_PRValue: return LV_InvalidExpression;
697 }
698 llvm_unreachable("Unhandled kind");
699 }
700
701 Expr::isModifiableLvalueResult
isModifiableLvalue(ASTContext & Ctx,SourceLocation * Loc) const702 Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
703 SourceLocation dummy;
704 Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy);
705 switch (VC.getKind()) {
706 case Cl::CL_LValue: break;
707 case Cl::CL_XValue: return MLV_InvalidExpression;
708 case Cl::CL_Function: return MLV_NotObjectType;
709 case Cl::CL_Void: return MLV_InvalidExpression;
710 case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType;
711 case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
712 case Cl::CL_MemberFunction: return MLV_MemberFunction;
713 case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
714 case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
715 case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary;
716 case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression;
717 case Cl::CL_PRValue:
718 return VC.getModifiable() == Cl::CM_LValueCast ?
719 MLV_LValueCast : MLV_InvalidExpression;
720 }
721 assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
722 switch (VC.getModifiable()) {
723 case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
724 case Cl::CM_Modifiable: return MLV_Valid;
725 case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
726 case Cl::CM_Function: return MLV_NotObjectType;
727 case Cl::CM_LValueCast:
728 llvm_unreachable("CM_LValueCast and CL_LValue don't match");
729 case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
730 case Cl::CM_ConstQualified: return MLV_ConstQualified;
731 case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField;
732 case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace;
733 case Cl::CM_ArrayType: return MLV_ArrayType;
734 case Cl::CM_IncompleteType: return MLV_IncompleteType;
735 }
736 llvm_unreachable("Unhandled modifiable type");
737 }
738