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