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