xref: /freebsd/contrib/llvm-project/clang/lib/AST/ExprClassification.cpp (revision 770cf0a5f02dc8983a89c6568d741fbc25baa999)
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::DependentCoawaitExprClass:
133   case Expr::CXXDependentScopeMemberExprClass:
134   case Expr::DependentScopeDeclRefExprClass:
135     // ObjC instance variables are lvalues
136     // FIXME: ObjC++0x might have different rules
137   case Expr::ObjCIvarRefExprClass:
138   case Expr::FunctionParmPackExprClass:
139   case Expr::MSPropertyRefExprClass:
140   case Expr::MSPropertySubscriptExprClass:
141   case Expr::ArraySectionExprClass:
142   case Expr::OMPArrayShapingExprClass:
143   case Expr::OMPIteratorExprClass:
144   case Expr::HLSLOutArgExprClass:
145     return Cl::CL_LValue;
146 
147     // C++ [expr.prim.general]p1: A string literal is an lvalue.
148   case Expr::StringLiteralClass:
149     // @encode is equivalent to its string
150   case Expr::ObjCEncodeExprClass:
151     // Except we special case them as prvalues when they are used to
152     // initialize a char array.
153     return E->isLValue() ? Cl::CL_LValue : Cl::CL_PRValue;
154 
155     // __func__ and friends are too.
156     // The char array initialization special case also applies
157     // when they are transparent.
158   case Expr::PredefinedExprClass: {
159     auto *PE = cast<PredefinedExpr>(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   case Expr::OpenACCAsteriskSizeExprClass:
474     return Cl::CL_PRValue;
475     break;
476 
477   case Expr::CXXParenListInitExprClass:
478     if (isa<ArrayType>(E->getType()))
479       return Cl::CL_ArrayTemporary;
480     return Cl::CL_ClassTemporary;
481   }
482 
483   llvm_unreachable("unhandled expression kind in classification");
484 }
485 
486 /// ClassifyDecl - Return the classification of an expression referencing the
487 /// given declaration.
488 static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {
489   // C++ [expr.prim.id.unqual]p3: The result is an lvalue if the entity is a
490   // function, variable, or data member, or a template parameter object and a
491   // prvalue otherwise.
492   // In C, functions are not lvalues.
493   // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an
494   // lvalue unless it's a reference type or a class type (C++ [temp.param]p8),
495   // so we need to special-case this.
496 
497   if (const auto *M = dyn_cast<CXXMethodDecl>(D)) {
498     if (M->isImplicitObjectMemberFunction())
499       return Cl::CL_MemberFunction;
500     if (M->isStatic())
501       return Cl::CL_LValue;
502     return Cl::CL_PRValue;
503   }
504 
505   bool islvalue;
506   if (const auto *NTTParm = dyn_cast<NonTypeTemplateParmDecl>(D))
507     islvalue = NTTParm->getType()->isReferenceType() ||
508                NTTParm->getType()->isRecordType();
509   else
510     islvalue =
511         isa<VarDecl, FieldDecl, IndirectFieldDecl, BindingDecl, MSGuidDecl,
512             UnnamedGlobalConstantDecl, TemplateParamObjectDecl>(D) ||
513         (Ctx.getLangOpts().CPlusPlus &&
514          (isa<FunctionDecl, MSPropertyDecl, FunctionTemplateDecl>(D)));
515 
516   return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
517 }
518 
519 /// ClassifyUnnamed - Return the classification of an expression yielding an
520 /// unnamed value of the given type. This applies in particular to function
521 /// calls and casts.
522 static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
523   // In C, function calls are always rvalues.
524   if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue;
525 
526   // C++ [expr.call]p10: A function call is an lvalue if the result type is an
527   //   lvalue reference type or an rvalue reference to function type, an xvalue
528   //   if the result type is an rvalue reference to object type, and a prvalue
529   //   otherwise.
530   if (T->isLValueReferenceType())
531     return Cl::CL_LValue;
532   const auto *RV = T->getAs<RValueReferenceType>();
533   if (!RV) // Could still be a class temporary, though.
534     return ClassifyTemporary(T);
535 
536   return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue;
537 }
538 
539 static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) {
540   if (E->getType() == Ctx.UnknownAnyTy)
541     return (isa<FunctionDecl>(E->getMemberDecl())
542               ? Cl::CL_PRValue : Cl::CL_LValue);
543 
544   // Handle C first, it's easier.
545   if (!Ctx.getLangOpts().CPlusPlus) {
546     // C99 6.5.2.3p3
547     // For dot access, the expression is an lvalue if the first part is. For
548     // arrow access, it always is an lvalue.
549     if (E->isArrow())
550       return Cl::CL_LValue;
551     // ObjC property accesses are not lvalues, but get special treatment.
552     Expr *Base = E->getBase()->IgnoreParens();
553     if (isa<ObjCPropertyRefExpr>(Base))
554       return Cl::CL_SubObjCPropertySetting;
555     return ClassifyInternal(Ctx, Base);
556   }
557 
558   NamedDecl *Member = E->getMemberDecl();
559   // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2.
560   // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then
561   //   E1.E2 is an lvalue.
562   if (const auto *Value = dyn_cast<ValueDecl>(Member))
563     if (Value->getType()->isReferenceType())
564       return Cl::CL_LValue;
565 
566   //   Otherwise, one of the following rules applies.
567   //   -- If E2 is a static member [...] then E1.E2 is an lvalue.
568   if (isa<VarDecl>(Member) && Member->getDeclContext()->isRecord())
569     return Cl::CL_LValue;
570 
571   //   -- If E2 is a non-static data member [...]. If E1 is an lvalue, then
572   //      E1.E2 is an lvalue; if E1 is an xvalue, then E1.E2 is an xvalue;
573   //      otherwise, it is a prvalue.
574   if (isa<FieldDecl>(Member)) {
575     // *E1 is an lvalue
576     if (E->isArrow())
577       return Cl::CL_LValue;
578     Expr *Base = E->getBase()->IgnoreParenImpCasts();
579     if (isa<ObjCPropertyRefExpr>(Base))
580       return Cl::CL_SubObjCPropertySetting;
581     return ClassifyInternal(Ctx, E->getBase());
582   }
583 
584   //   -- If E2 is a [...] member function, [...]
585   //      -- If it refers to a static member function [...], then E1.E2 is an
586   //         lvalue; [...]
587   //      -- Otherwise [...] E1.E2 is a prvalue.
588   if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
589     if (Method->isStatic())
590       return Cl::CL_LValue;
591     if (Method->isImplicitObjectMemberFunction())
592       return Cl::CL_MemberFunction;
593     return Cl::CL_PRValue;
594   }
595 
596   //   -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue.
597   // So is everything else we haven't handled yet.
598   return Cl::CL_PRValue;
599 }
600 
601 static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {
602   assert(Ctx.getLangOpts().CPlusPlus &&
603          "This is only relevant for C++.");
604   // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.
605   // Except we override this for writes to ObjC properties.
606   if (E->isAssignmentOp())
607     return (E->getLHS()->getObjectKind() == OK_ObjCProperty
608               ? Cl::CL_PRValue : Cl::CL_LValue);
609 
610   // C++ [expr.comma]p1: the result is of the same value category as its right
611   //   operand, [...].
612   if (E->getOpcode() == BO_Comma)
613     return ClassifyInternal(Ctx, E->getRHS());
614 
615   // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand
616   //   is a pointer to a data member is of the same value category as its first
617   //   operand.
618   if (E->getOpcode() == BO_PtrMemD)
619     return (E->getType()->isFunctionType() ||
620             E->hasPlaceholderType(BuiltinType::BoundMember))
621              ? Cl::CL_MemberFunction
622              : ClassifyInternal(Ctx, E->getLHS());
623 
624   // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its
625   //   second operand is a pointer to data member and a prvalue otherwise.
626   if (E->getOpcode() == BO_PtrMemI)
627     return (E->getType()->isFunctionType() ||
628             E->hasPlaceholderType(BuiltinType::BoundMember))
629              ? Cl::CL_MemberFunction
630              : Cl::CL_LValue;
631 
632   // All other binary operations are prvalues.
633   return Cl::CL_PRValue;
634 }
635 
636 static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,
637                                      const Expr *False) {
638   assert(Ctx.getLangOpts().CPlusPlus &&
639          "This is only relevant for C++.");
640 
641   // C++ [expr.cond]p2
642   //   If either the second or the third operand has type (cv) void,
643   //   one of the following shall hold:
644   if (True->getType()->isVoidType() || False->getType()->isVoidType()) {
645     // The second or the third operand (but not both) is a (possibly
646     // parenthesized) throw-expression; the result is of the [...] value
647     // category of the other.
648     bool TrueIsThrow = isa<CXXThrowExpr>(True->IgnoreParenImpCasts());
649     bool FalseIsThrow = isa<CXXThrowExpr>(False->IgnoreParenImpCasts());
650     if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False)
651                                            : (FalseIsThrow ? True : nullptr))
652       return ClassifyInternal(Ctx, NonThrow);
653 
654     //   [Otherwise] the result [...] is a prvalue.
655     return Cl::CL_PRValue;
656   }
657 
658   // Note that at this point, we have already performed all conversions
659   // according to [expr.cond]p3.
660   // C++ [expr.cond]p4: If the second and third operands are glvalues of the
661   //   same value category [...], the result is of that [...] value category.
662   // C++ [expr.cond]p5: Otherwise, the result is a prvalue.
663   Cl::Kinds LCl = ClassifyInternal(Ctx, True),
664             RCl = ClassifyInternal(Ctx, False);
665   return LCl == RCl ? LCl : Cl::CL_PRValue;
666 }
667 
668 static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,
669                                        Cl::Kinds Kind, SourceLocation &Loc) {
670   // As a general rule, we only care about lvalues. But there are some rvalues
671   // for which we want to generate special results.
672   if (Kind == Cl::CL_PRValue) {
673     // For the sake of better diagnostics, we want to specifically recognize
674     // use of the GCC cast-as-lvalue extension.
675     if (const auto *CE = dyn_cast<ExplicitCastExpr>(E->IgnoreParens())) {
676       if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) {
677         Loc = CE->getExprLoc();
678         return Cl::CM_LValueCast;
679       }
680     }
681   }
682   if (Kind != Cl::CL_LValue)
683     return Cl::CM_RValue;
684 
685   // This is the lvalue case.
686   // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
687   if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())
688     return Cl::CM_Function;
689 
690   // Assignment to a property in ObjC is an implicit setter access. But a
691   // setter might not exist.
692   if (const auto *Expr = dyn_cast<ObjCPropertyRefExpr>(E)) {
693     if (Expr->isImplicitProperty() &&
694         Expr->getImplicitPropertySetter() == nullptr)
695       return Cl::CM_NoSetterProperty;
696   }
697 
698   CanQualType CT = Ctx.getCanonicalType(E->getType());
699   // Const stuff is obviously not modifiable.
700   if (CT.isConstQualified())
701     return Cl::CM_ConstQualified;
702   if (Ctx.getLangOpts().OpenCL &&
703       CT.getQualifiers().getAddressSpace() == LangAS::opencl_constant)
704     return Cl::CM_ConstAddrSpace;
705 
706   // Arrays are not modifiable, only their elements are.
707   if (CT->isArrayType() &&
708       !(Ctx.getLangOpts().HLSL && CT->isConstantArrayType()))
709     return Cl::CM_ArrayType;
710   // Incomplete types are not modifiable.
711   if (CT->isIncompleteType())
712     return Cl::CM_IncompleteType;
713 
714   // Records with any const fields (recursively) are not modifiable.
715   if (const RecordType *R = CT->getAs<RecordType>())
716     if (R->hasConstFields())
717       return Cl::CM_ConstQualifiedField;
718 
719   return Cl::CM_Modifiable;
720 }
721 
722 Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const {
723   Classification VC = Classify(Ctx);
724   switch (VC.getKind()) {
725   case Cl::CL_LValue: return LV_Valid;
726   case Cl::CL_XValue: return LV_InvalidExpression;
727   case Cl::CL_Function: return LV_NotObjectType;
728   case Cl::CL_Void: return LV_InvalidExpression;
729   case Cl::CL_AddressableVoid: return LV_IncompleteVoidType;
730   case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;
731   case Cl::CL_MemberFunction: return LV_MemberFunction;
732   case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;
733   case Cl::CL_ClassTemporary: return LV_ClassTemporary;
734   case Cl::CL_ArrayTemporary: return LV_ArrayTemporary;
735   case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression;
736   case Cl::CL_PRValue: return LV_InvalidExpression;
737   }
738   llvm_unreachable("Unhandled kind");
739 }
740 
741 Expr::isModifiableLvalueResult
742 Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {
743   SourceLocation dummy;
744   Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy);
745   switch (VC.getKind()) {
746   case Cl::CL_LValue: break;
747   case Cl::CL_XValue: return MLV_InvalidExpression;
748   case Cl::CL_Function: return MLV_NotObjectType;
749   case Cl::CL_Void: return MLV_InvalidExpression;
750   case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType;
751   case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;
752   case Cl::CL_MemberFunction: return MLV_MemberFunction;
753   case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;
754   case Cl::CL_ClassTemporary: return MLV_ClassTemporary;
755   case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary;
756   case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression;
757   case Cl::CL_PRValue:
758     return VC.getModifiable() == Cl::CM_LValueCast ?
759       MLV_LValueCast : MLV_InvalidExpression;
760   }
761   assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");
762   switch (VC.getModifiable()) {
763   case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");
764   case Cl::CM_Modifiable: return MLV_Valid;
765   case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");
766   case Cl::CM_Function: return MLV_NotObjectType;
767   case Cl::CM_LValueCast:
768     llvm_unreachable("CM_LValueCast and CL_LValue don't match");
769   case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
770   case Cl::CM_ConstQualified: return MLV_ConstQualified;
771   case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField;
772   case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace;
773   case Cl::CM_ArrayType: return MLV_ArrayType;
774   case Cl::CM_IncompleteType: return MLV_IncompleteType;
775   }
776   llvm_unreachable("Unhandled modifiable type");
777 }
778