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