brintos

brintos / llvm-project-archived public Read only

0
0
Text · 30.4 KiB · aeacd0d Raw
785 lines · cpp
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-exception6//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 22using namespace clang;23 24using Cl = Expr::Classification;25 26static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E);27static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D);28static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T);29static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E);30static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E);31static Cl::Kinds ClassifyConditional(ASTContext &Ctx,32                                     const Expr *trueExpr,33                                     const Expr *falseExpr);34static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,35                                       Cl::Kinds Kind, SourceLocation &Loc);36 37Cl 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 an42  //   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 void49    // 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.83static 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 normal90  // prvalues.91  return Cl::CL_PRValue;92}93 94static 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 108static 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 lvalues123  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 lvalues136    // FIXME: ObjC++0x might have different rules137  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 string150  case Expr::ObjCEncodeExprClass:151    // Except we special case them as prvalues when they are used to152    // 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 applies157    // 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 expand223    // it and check it.224    return Cl::CL_PRValue;225 226  // Make HLSL this reference-like227  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 lvalue248    //                 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 the255      // 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 a267    //   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 function282      //   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 member291    // 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 an304      //   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, we324    // 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 affect329    //   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, an335    // 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 duplicates364    // 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 function420    // 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_LValue456              : Cl::CL_XValue;457 458  case Expr::InitListExprClass:459    // An init list can be an lvalue if it is bound to a reference and460    // contains only one element. In that case, we look at that element461    // for an exact classification. Init list creation takes care of the462    // 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 the487/// given declaration.488static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) {489  // C++ [expr.prim.id.unqual]p3: The result is an lvalue if the entity is a490  // function, variable, or data member, or a template parameter object and a491  // prvalue otherwise.492  // In C, functions are not lvalues.493  // In addition, NonTypeTemplateParmDecl derives from VarDecl but isn't an494  // 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  else510    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 an520/// unnamed value of the given type. This applies in particular to function521/// calls and casts.522static 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 an527  //   lvalue reference type or an rvalue reference to function type, an xvalue528  //   if the result type is an rvalue reference to object type, and a prvalue529  //   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 539static 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.3p3547    // For dot access, the expression is an lvalue if the first part is. For548    // 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", then561  //   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, then572  //      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 lvalue576    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 an586  //         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 601static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) {602  assert(Ctx.getLangOpts().CPlusPlus &&603         "This is only relevant for C++.");604 605  // For binary operators which are unknown due to type dependence, the606  // convention is to classify them as a prvalue. This does not matter much, but607  // it needs to agree with how they are created.608  if (E->getType() == Ctx.DependentTy)609    return Cl::CL_PRValue;610 611  // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand.612  // Except we override this for writes to ObjC properties.613  if (E->isAssignmentOp())614    return (E->getLHS()->getObjectKind() == OK_ObjCProperty615              ? Cl::CL_PRValue : Cl::CL_LValue);616 617  // C++ [expr.comma]p1: the result is of the same value category as its right618  //   operand, [...].619  if (E->getOpcode() == BO_Comma)620    return ClassifyInternal(Ctx, E->getRHS());621 622  // C++ [expr.mptr.oper]p6: The result of a .* expression whose second operand623  //   is a pointer to a data member is of the same value category as its first624  //   operand.625  if (E->getOpcode() == BO_PtrMemD)626    return (E->getType()->isFunctionType() ||627            E->hasPlaceholderType(BuiltinType::BoundMember))628             ? Cl::CL_MemberFunction629             : ClassifyInternal(Ctx, E->getLHS());630 631  // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its632  //   second operand is a pointer to data member and a prvalue otherwise.633  if (E->getOpcode() == BO_PtrMemI)634    return (E->getType()->isFunctionType() ||635            E->hasPlaceholderType(BuiltinType::BoundMember))636             ? Cl::CL_MemberFunction637             : Cl::CL_LValue;638 639  // All other binary operations are prvalues.640  return Cl::CL_PRValue;641}642 643static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,644                                     const Expr *False) {645  assert(Ctx.getLangOpts().CPlusPlus &&646         "This is only relevant for C++.");647 648  // C++ [expr.cond]p2649  //   If either the second or the third operand has type (cv) void,650  //   one of the following shall hold:651  if (True->getType()->isVoidType() || False->getType()->isVoidType()) {652    // The second or the third operand (but not both) is a (possibly653    // parenthesized) throw-expression; the result is of the [...] value654    // category of the other.655    bool TrueIsThrow = isa<CXXThrowExpr>(True->IgnoreParenImpCasts());656    bool FalseIsThrow = isa<CXXThrowExpr>(False->IgnoreParenImpCasts());657    if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False)658                                           : (FalseIsThrow ? True : nullptr))659      return ClassifyInternal(Ctx, NonThrow);660 661    //   [Otherwise] the result [...] is a prvalue.662    return Cl::CL_PRValue;663  }664 665  // Note that at this point, we have already performed all conversions666  // according to [expr.cond]p3.667  // C++ [expr.cond]p4: If the second and third operands are glvalues of the668  //   same value category [...], the result is of that [...] value category.669  // C++ [expr.cond]p5: Otherwise, the result is a prvalue.670  Cl::Kinds LCl = ClassifyInternal(Ctx, True),671            RCl = ClassifyInternal(Ctx, False);672  return LCl == RCl ? LCl : Cl::CL_PRValue;673}674 675static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E,676                                       Cl::Kinds Kind, SourceLocation &Loc) {677  // As a general rule, we only care about lvalues. But there are some rvalues678  // for which we want to generate special results.679  if (Kind == Cl::CL_PRValue) {680    // For the sake of better diagnostics, we want to specifically recognize681    // use of the GCC cast-as-lvalue extension.682    if (const auto *CE = dyn_cast<ExplicitCastExpr>(E->IgnoreParens())) {683      if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) {684        Loc = CE->getExprLoc();685        return Cl::CM_LValueCast;686      }687    }688  }689  if (Kind != Cl::CL_LValue)690    return Cl::CM_RValue;691 692  // This is the lvalue case.693  // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)694  if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())695    return Cl::CM_Function;696 697  // Assignment to a property in ObjC is an implicit setter access. But a698  // setter might not exist.699  if (const auto *Expr = dyn_cast<ObjCPropertyRefExpr>(E)) {700    if (Expr->isImplicitProperty() &&701        Expr->getImplicitPropertySetter() == nullptr)702      return Cl::CM_NoSetterProperty;703  }704 705  CanQualType CT = Ctx.getCanonicalType(E->getType());706  // Const stuff is obviously not modifiable.707  if (CT.isConstQualified())708    return Cl::CM_ConstQualified;709  if (Ctx.getLangOpts().OpenCL &&710      CT.getQualifiers().getAddressSpace() == LangAS::opencl_constant)711    return Cl::CM_ConstAddrSpace;712 713  // Arrays are not modifiable, only their elements are.714  if (CT->isArrayType() &&715      !(Ctx.getLangOpts().HLSL && CT->isConstantArrayType()))716    return Cl::CM_ArrayType;717  // Incomplete types are not modifiable.718  if (CT->isIncompleteType())719    return Cl::CM_IncompleteType;720 721  // Records with any const fields (recursively) are not modifiable.722  if (const RecordType *R = CT->getAs<RecordType>())723    if (R->hasConstFields())724      return Cl::CM_ConstQualifiedField;725 726  return Cl::CM_Modifiable;727}728 729Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const {730  Classification VC = Classify(Ctx);731  switch (VC.getKind()) {732  case Cl::CL_LValue: return LV_Valid;733  case Cl::CL_XValue: return LV_InvalidExpression;734  case Cl::CL_Function: return LV_NotObjectType;735  case Cl::CL_Void: return LV_InvalidExpression;736  case Cl::CL_AddressableVoid: return LV_IncompleteVoidType;737  case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents;738  case Cl::CL_MemberFunction: return LV_MemberFunction;739  case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting;740  case Cl::CL_ClassTemporary: return LV_ClassTemporary;741  case Cl::CL_ArrayTemporary: return LV_ArrayTemporary;742  case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression;743  case Cl::CL_PRValue: return LV_InvalidExpression;744  }745  llvm_unreachable("Unhandled kind");746}747 748Expr::isModifiableLvalueResult749Expr::isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc) const {750  SourceLocation dummy;751  Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy);752  switch (VC.getKind()) {753  case Cl::CL_LValue: break;754  case Cl::CL_XValue: return MLV_InvalidExpression;755  case Cl::CL_Function: return MLV_NotObjectType;756  case Cl::CL_Void: return MLV_InvalidExpression;757  case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType;758  case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents;759  case Cl::CL_MemberFunction: return MLV_MemberFunction;760  case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting;761  case Cl::CL_ClassTemporary: return MLV_ClassTemporary;762  case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary;763  case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression;764  case Cl::CL_PRValue:765    return VC.getModifiable() == Cl::CM_LValueCast ?766      MLV_LValueCast : MLV_InvalidExpression;767  }768  assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind");769  switch (VC.getModifiable()) {770  case Cl::CM_Untested: llvm_unreachable("Did not test modifiability");771  case Cl::CM_Modifiable: return MLV_Valid;772  case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match");773  case Cl::CM_Function: return MLV_NotObjectType;774  case Cl::CM_LValueCast:775    llvm_unreachable("CM_LValueCast and CL_LValue don't match");776  case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;777  case Cl::CM_ConstQualified: return MLV_ConstQualified;778  case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField;779  case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace;780  case Cl::CM_ArrayType: return MLV_ArrayType;781  case Cl::CM_IncompleteType: return MLV_IncompleteType;782  }783  llvm_unreachable("Unhandled modifiable type");784}785